mardi 31 octobre 2017

Do I need a factory with an abstrack factory in this scenario?

Sorry if someone asked this already, but I did not found a question with this specific scenario:

I have an entity with an status and a type. For each status and for each type, I should show the user a different page, and this page is some kind complex to create so it is created with the builder pattern. But, in some cases, these pages could be the same. And with some status, I do not need to check the type.

Some examples that could occur:

  • Status 1 with any type -> Page "1"
  • Status 2 with type A -> Page "2A"
  • Status 2 with type B -> Page "2B"
  • Status 3 with type A -> Page "3X"
  • Status 3 with type B -> Page "3X"
  • Status 3 with type C -> Page "3C"

I thought about implementing a factory (with an switch case for each status) that will create and return the result of an abstract factory (with a factory for each type). But, I will need some abstract classes to solve the "same page" problem in between these factories.

Do I really need this complex structure?

How can I convert this Ruby code to C++?

I want to write some code for Game Development with C++ but I can't figure out how to do it, I can only write it in Ruby, this is the code prototype:

class Component
    # ...
end

class Transform < Component
    # ...
end

class Renderer < Component
    # ...
end

class GameObject
    def initialize
        @components = {}
    end

    def update
        @components.each do |component|
            component.update
        end
    end

    def render
        @components.each do |component|
            component.render
        end
    end

    def add_component(component_class)
        component = component_class.new
        @components[component_class] = component
    end

    def rem_component(component_class)
        component = @components.delete(component_class)
        component.destroy if component
    end

    def get_component(component_class)
        return @components[component_class]
    end
end

I don't know how to create the functions GameObject#rem_component and GameObject#get_component. Please, give me some ideas

Describe the oft quoted disadvantage of Revealing Module Pattern with an example

I read Javascript Design Patterns, and then a bunch of SO answers on RMP, and I keep finding that where disadvantage is mentioned, it's the straight up quote from the book:

A disadvantage of this pattern is that if a private function refers to a public function, that public function can’t be overridden if a patch is necessary. This is because the private function will continue to refer to the private implementation, and the pattern doesn’t apply to public members, only to functions.

Public object members that refer to private variables are also subject to the no-patch rule.

As a result of this, modules created with the Revealing Module pattern may be more fragile than those created with the original Module pattern, so care should be taken during usage.

Sorry that I'm stupid but the above explanation just isn't doing it for me. Can someone provide a code-rich visual example of what that disadvantage means?

Polymorphic substitutions with overloaded methods without using instanceof or type checks

I need your advise again. I want to save Objects of Arc and Line in one ArrayList, then get the intersection of both. The question is how can I cast i and j to its original class. I know that instanceof works but that would be the dirtiest method.

public class Intersection {
    public static boolean intersect(ArrayList<Curve> list1, ArrayList<Curve> list2) {
        for (Curve i : list1) {
            for (Curve j : list2) {
                if (i.intersection(j).length > 0) 
                    return true;
            }
        }
        return false;
    }
}

public abstract class Curve {
    public Point[] intersection(Curve c) {
        return new Point[] {};
    }
}

public class Line extends Curve {
    public Point[] intersection(Line l) {
        // returns intersection Point of this and l
    }

    public Point[] intersection(Arc a) {
        // returns intersection Point(s)
    }
}

public class Arc extends Curve {
    public Point[] intersection(Line l) {
        // return intersection Point(s) of this and l
    }

    public Point[] intersection(Arc a) {
        // returns intersection Point(s)
    }
}

Thanks for your help!

How to share memory over long chain of method calls?

I need to figure out a way to save and log a method request and response conditionally, with the condition being the latency of the top-level method crossing the p50 latency. The call visualization is as follows:

topLevel() -> method1() -> method2() -> ... -> makeRequest()

In makeRequest is where the request and response to that request are that I need to log.

But I'll only know if I need to actually log those at some point on the way back up the call stack - if topLevel method is taking too long.

So to me, the only option is to save the request and response in makeRequest no matter what and make that available to the topLevel method. The topLevel method will check if latency is above p50 and conditionally log the request and response.

This all leads to the titular question: How to share memory over long chain of method calls?

I don't want to be passing objects back through multiple method calls, polluting function signatures.

What is the best pattern for this? Maybe using a local cache to save the request and response and then retrieving it in topLevel? Is there an aspect oriented approach to solving this?

Angular Dart errorRenderer pattern

How to use Error Renderer pattern from Angular Dart Components Part of documentation indicates that it is possible.

http://ift.tt/2lvnzot

replaceErrors(Map overrides) → ErrorFn Convience function for replacing multiple errors for Components using the errorRenderer pattern.

http://ift.tt/2yhJeGP

But it is not mentioned how to use it in practice.

What is the difference between MVC Controller and Action method in terms of Design Pattern in C#?

Can anybody please explain what is the difference between MVC Controller and Action methods in terms of design pattern?Which one is Singleton and why?How is dependency injection inbuilt into MVC Design Pattern in C#?

Would be great even if you can lead me to any good links which provide an in-depth explanation on these topics.

Thanks in advance.

Google Calendar(Android) edit event - what is UI pattern?

I created mobile app for android(with Xamarin Forms). Now I do not like the look of it, I want to update it. I like the look of the app Google Calendar. It is true material design(I read a lot about it). I like how to add and edit events in calendar. For example this:

enter image description here

The edit button, the data ratio and the picture above - are excellent. I want to do the same. What is the name of this pattern? I read a lot about material design but I did not find article about this solution(pattern).

How it's called? What can I read guide(about this pattern edit)?

lundi 30 octobre 2017

How to get whole members of regex android

My problems is about getting members of regex. Here is my code

 Pattern p = Pattern.compile("aa(a+bb)b*", Pattern.DOTALL);

Is there a any way to find&PRINT members of this regular expression for example I want to get 3 members of this (aa(a+bb)b*) expression by randomly.

For example :

aaa , aaab, aabb

or aabb, aaabbb, aabbbbbb
or aaab,aaabbb,aabbbbbbb etc.

I will be grateful if you can help

Why does JAX_RS use ResponseBuilder to build Response

I see that

Response.ok(entity).build();

returns Response via ResponseBuilder, and that it is a common pattern to arrive at the target object(Response in this case) through an intermediate object(ResponseBuilder). Why is it so? Why not directly do something like:

ResponseBuilder.one-step-ok-build(entity);

What is wrong with java's implementationof the observer pattern?

Informing myself about the observer pattern I stumbled across quite a few statements that suggested to make a custom implementation of the pattern without specifying what's really wrong with java's implementation. Is it because java.util.Observable is an abstract class instead of an interface? Yet, as far as I can see it allows for both a PULL and a PUSH mode. What could I do better in a custom implementation?

What are these Design Patterns?

So I'm trying to learn some Design Pattern Templates, and we've got these examples from my Study Program.

I'm really bad at telling, so could the community please help me tell which Design Pattern these images are and possibly give a small description about the characteristics?

We've mainly gone through following patterns: Strategy, Abstract Factory, Factory, Composite, Visitor, Observer and Facade. So I'm guessing the images are representing some of these patterns(or possibly none).

Here they are:

A: enter image description here B: enter image description here C: enter image description here D: enter image description here E: enter image description here

Thankful for your help!

JavaScript parameter dependent class inheritance

I have the following classes hierarchy:

  Renderer (can render some data on screen)
     |
 DbRenderer (fetch data from the database)
     |
JsonRenderer (my class. converts specific data into needed format supported by Renderer)

It works well but requires to pass DB connection parameters into JsonRenderer constructor in order to call constructor() of DbRenderer via super() since this parameter is obligatory there.

So, it looks like:

const renderer = new JsonRenderer(dbParams);

, where

class JsonRenderer extends DbRenderer {}

But, I want to make dbParams optional and change classes hierarchy to the following:

   Renderer
      |
  JsonRenderer

I can do it by creating separate class:

class JsonRenderer2 extends Renderer {}

Off course separate class will be a source of code duplication and this is not a good idea.

Is there some solution for my situation without changing of Renderer and DbRenderer parent classes?

Java: Decorator Pattern - reference to main abstract class

I have a question to the Decorator Pattern. I have read this article http://ift.tt/2bXolo8

Everything is clear to me, I only have one question:

This class inhertis from the abstract class SandWichDecorator:

public class CheeseDecorator extends SandWichDecorator{
Sandwich currentSandwich;

public CheeseDecorator(Sandwich sw){
    currentSandwich = sw;
}

@Override
public String getDescription(){
    return currentSandwich.getDescription() + ", Cheese";
}
@Override
public BigDecimal price() {
    return currentSandwich.price().add(new BigDecimal("0.50"));
} }

Why is the reference to the abstract class Sandwich "Sandwich currentSandwich;" in the CheeseDecorator class? Wouldn't it be easier to put it into the abstract class SandWichDecorator? And every class extending SandWichDecorator would automatically have the reference.

Thank you for your help, Peter

Patterns and practices in translations development

What are the patterns and best practices when developing translations engine if there are different rules and levels of translations? For example: a specific translation for user group, if not found pull the translation for that locale, if not found pull the translation for that language, if not found pull the default (base) translation (EN).

Database tables and entities with different data structures handle it in the dao or in the service

SQL TABLE

Client Table

+--+----+
|id|name|
+--+----+
|1 |Jhon|
+--+----+

Sensor System Table

+--+----+---------+
|id|name|client_id|
+--+----+---------+
|1 |sys1|1        |
+--+----+---------+

client_id -> foreign key client(id)

ENTITY PHP

class Client
{
 private $id;
 private $name;
 private $sensorSystem;
}

class SensorSystem
{
 private $id;
 private $name;
}

Well, when I need to add a new sensor system to the database, the Service must pass both entities (Client, SensorSystem) to the DAO and then the DAO will evade the responsibility of converting the entity data into the table fields; or is the Service having the responsibility to divide the entity data into an array (['idSensor' => '1', 'nameSensore' => 'name', 'idClient' => '1']) and then pass the array to the DAO ??

I know that Serivice is handling the entity data and DAO to manipulate data in the database, but given the different data structures, who has the responsibility to convert table data into entity attributes and vice versa?

Interfaces and classes vs Simple Factory design pattern

One of my friend told me if I want to be a good programmer then I need to learn Design Patterns. And I started on that site : http://ift.tt/2kOwAUY

I started from Simple Factory. And as you can see on that page you need to implement :

  • interface Door
  • class WoodenDoor
  • class DoorFactory

And you can use it like this (PHP) :

$door = DoorFactory::makeDoor(100, 200);
echo 'Width: ' . $door->getWidth();
echo 'Height: ' . $door->getHeight();

But I was wondering why I need the layer of class DoorFactory which gives me new instance of WoodenDoor with given parameter when I can simply do :

Door door = new WoodenDoor(100, 200);

What is the big deal in making that factory when I can simple create instance by passing given constructor parameter by using new ClassName statement?

Interaction between methods in child and parent class in java

I am new to programming and I have the following question about architecture and method interaction.

My question is how best to make the following interaction in the following classes. Editor is base abstract class and EditorController is ManagedBean/CDI controller for the jsf. Load method is used directly in the jsf(xhtml) file and becouse of this i don`t want to overload it and repeat most of the logic in the child classes.

the first way that comes to my mind is:

public abstract class Editor {
    ...
    ...

    void delete(id) {
        preLoad();
        this.currentEntity = getService().findByPrimaryKey(id);
         loadAdditionalData();
         this.editMode = true;
         this.newObject = false;
         loadComplete();
    }

    protected void preLoad() {
    }

    protected void loadAdditionalData() {
    }

    protected void loadComplete() {
    }
}

@Named("editor")
@ViewScoped
public class EditorController {
    ...
    ...
    @Override
    protected void loadComplete() {
        // do stuff
    }
}

Second way in my mind is with listener like this:

public abstract class Editor {
    ...
    ...

    final protected OnLoadListener DEFAULT_ON_LOAD_LISTENER = new OnLoadListener() {};

    void delete(id) {
        getOnLoadListener.onPreLoad();
        this.currentEntity = getService().findByPrimaryKey(id);
        getOnLoadListener.onPostLoad();
        this.editMode = true;
        this.newObject = false;
        getOnLoadListener.onLoadComplete();
    }

    public abstract class OnLoadListener {
        void onPreLoad() {}
        void onPostLoad() {}
        void onComplete() {}
    }

    @NotNull protected OnLoadListener getOnLoadListener() {
        return DEFAULT_ON_LOAD_LISTENER;
    }
}

@Named("editor")
@ViewScoped
public class EditorController {

    private OnLoadListener onLoadListener = new OnLoadListener() {
        @Override
        public void onLoadComplete() {
            // do stuff 
        }
    }

    @Override
    @NotNull protected OnLoadListener getOnLoadListener() {
        return onLoadListener;
    }
}

If there is a better way, please tell me :).

Is this a strategy pattern?

I was wondering if this falls under a strategy pattern:

I have a list of IConverters (They convert files to ingame assets). They all sit inside of a ConverterManager. Every IConverter has an extension type it looks for. So say we have a file with .exe extension. The ConverterManager will look for the converter that looks for the .exe extension. If it exists it will pass the path of the file through, if it doesn't, it won't do anything.

I was wondering if this is a strategy pattern though as I am calculating what behaviour to choose based on the extension of the file.

Thanks in advance.

dimanche 29 octobre 2017

Design pattern for switching based on instance of without using instance of keyword

I'm facing a design challenge where I have to switch based on the instance of an object. I have been told that it's a bad idea to use instanceof operator in Java. Someone suggested visitor pattern, but in the scenario I'm facing switching has to be done based on one objects instance and not two. So I feel like it might overkill to use visitor pattern which is quite specific and confusing. Please suggest the right approach. Following is a sample

VehicleHandler ( Vehicle vehicle){



if( vehicle instanceof Car)


// Do something which cant be tied to Car's impl ( Dont want busiess logic to be in the class itself

else if(vehicle instanceof Bike)
// Do something  
}

Car and Bike implement marker interface Vehicle. There are many classes having functions which takes vehicle as arguments and will need to bifurcate in each of those classes such as VehicleTransformer, VehicleValidator etc. Those methods are doing completely unrelated actions. Please help me identify the right design pattern for this problem.

Java instantiating child object from parent object

I have a following class that shares the same "state" and performs CRUD actions.

public class Client {
    private String state;
    public Client(args){
        this.state = buildStateFromArgs();  // this value will not change
    }

    public void createUser();
    public User getUser();
    public User updateUser();
    public void deleteUser();

    public void createJob();
    public Job getJob();
    public Job updateJob();
    public void deleteJob();

    // other CRUD functions ....
}

I am thinking of refactoring it to something like

public class Client {
    public Client(args){
        this.state = buildStateFromArgs();
    }
    private String state;
}

public class UserClient extends Client{
    public void createUser();
    public User getUser();
    public User updateUser();
    public void deleteUser();
}

But I am not sure what is the best approach to instatiate the child class. Suppose this is the current implementation,

Client client = new Client(args);
client.createUser();
client.createJob();

Should I simply just downcast?

Client client = new Client(args);
UserClient userClient = (UserClient) client;
userClient.createUser();
JobClient jobClient = (JobClient) client;
jobClient.createJob();

Or should I construct the child from parent?

Client client = new Client(args);
UserClient userClient = new UserClient(client);
userClient.createUser();
JobClient jobClient = new JobClient(client);
jobClient.createJob();

Or is there a better design pattern suited for this kind of problem?

Why are variables not part of the contract in interfaces?

Today I stumbled across the observer pattern. In most versions the concreteObserver HAS-A concreteSubject as one of its instance variables. This is, in order to get information about the changed state of the subject.

Generally spoken, why don't we simply put the variable into the IObserver interface? This way the "contract with the outer world" interfaces impose on classes would not only apply to methods but also for variables? Wouldn't that be a good thing because programmers would be more guided towards implementing the interface or certain patterns that are based on interfaces?

HTML5 - pattern won't work properly

I am making a pattern which needs the following,

8-10 string length

1 number,1 latin letter,1 special characters.

Here is my pattern

pattern="(?=.\d)(?=.[A-Za-z])(?=.[@#$%^&()_+]).{8,10}"

   <input type="password" placeholder="Password" pattern="(?=.*\d)(?=.*[A-Za-z])(?=.*[@#$%^&*()_+]).{8,10}" class="form__input" required title="One latin,One number,One Symbol" />

Why it won't work ?

Is order of decorators important while using Decorator Design Pattern in Java?

While reading about use of Java I/O classes I've seen multiple variants of many objects used to get another result and I wonder if is it important to put these objects in specific order or I just have to use them no matter in what order.

samedi 28 octobre 2017

constructor injection vs method injection

Laravel encourages dependency injection. Since I am using laravel on my project, I figured I'll try using this approach.

I am taking advantage of Laravel's service container by type hinting my dependencies and letting it resolve them. I have four controllers. All of them extend a base class called GlobalController. I also have two models. All of them extend a base class called GlobalModel.

My first attempt is (sort of) using method injection. GlobalController looks like this:

namespace App\Http\Controllers;

use Illuminate\Http\Request;;
use App\Models\GlobalModel;

class GlobalController extends Controller
{

    public function __construct()
    {
        $this->middleware(['authenticate', 'token']);
    }

    // functions that handle normal http requests and ajax requests

    }

One of the controllers that extends from GlobalController is called UserController. Some of its functions are:

  • index - show all data
  • edit - show edit form
  • update - updates to database

Edit and update use route-model-binding.

namespace App\Http\Controllers;

use Illuminate\Http\Request;;
use App\Models\User;

class UserController extends GlobalController
{

    public function index(User $user)
    {
        $users = $user->all();
        return view('pages/view_users')->with('users', $users);
    }

    public function edit(User $user)
    {
        return view('pages/edit_user')->with('user', $user);
    }

    public function update(Request $request, User $user)
    {
        $data = $request->all();
        if ($user->validate($data))
        {
            $user->update($data);
            return $this->successResponse($request, 'users', 'Successfully edited user');
        }
        return $this->failedResponse($request, $user);
    }

    // other functions

    }

While this is working fine, Request and User get injected many times. If I have to change a Request implementation (for example), I'll have to manually change many functions to type hint that particular Request object. Not good at all. Since they are usually called in most functions, I tried doing constructor injection.

Here is GlobalController using constructor injection:

namespace App\Http\Controllers;

use Illuminate\Http\Request;;;
use App\Models\GlobalModel;

class GlobalController extends Controller
{
    protected $request;
    protected $model; // use polymorphism

    public function __construct(Request $request, GlobalModel $model)
    {
        $this->request = $request;
        $this->model = $model;
        $this->middleware(['authenticate', 'token']);
    }

    // functions that handle normal http requests and ajax requests

}

And here is UserController using constructor injection containing the same functions:

namespace App\Http\Controllers;

use Illuminate\Http\Request;;
use App\Models\User;

class UserController extends GlobalController
{

    public function __construct(Request $request, User $user) // use polymorphism
    {
        parent::__construct($request, $user);
    }

    public function index()
    {
        $users = $this->model->all();
        return view('pages/view_users')->with('users', $users);
    }

    public function edit(int $id)
    {
        $this->model = $this->model->find($id);
        return view('pages/edit_user')->with('user', $this->model);
    }

    public function update(int $id)
    {
        $this->model = $this->model->find($id);
        $data = $this->request->all();
        if ($this->model->validate($data))
        {
            $this->model->update($data);
            return $this->successResponse('users', 'Successfully edited user');
        }
        return $this->failedResponse();
    }

    // other functions

}

Now, I can't put my finger on it, but I think this implementation seems not right. It became less readable. The usage of $model and $this have made the code more disgusting.

I am so confused. I understand the benefits I can get from dependency injection, but I am sure my implementations of method injection and constructor injection are extremely wrong. What implementation should I choose? Or should I choose any from these two at all?

Bash pattern matching 'or' using ${}

hashrate=${line//*:/}
hashrate=${hashrate//H\/s/}

I'm trying to unify this regex replace into a single command,something like:

hashrate=${line//*:\+/H\/s/}

However, this last option doesn't work. i also tried with \|, but it doesn't seem to work and i haven't find anything useful in bash manuals and documentation. I need to use ${} instead of sed, even if using it solves my problem.

Spring - designing utility modules

A Spring application design question. I want to write a utility java library and this is going to be a dependency across all my other small applications. All my applications are spring based applications. Is it a good practice to use auto wiring in the utility library module. And this utility library needs few properties to be read from the properties file. How are we going to approach writing my common utility library when the other applications which uses this module would be spring based?

HTML field validation, pattern attribute

I don't know what the bold part means: "<"input name="zip_code" type="text" pattern="\d{5}(-\d{4})?" required="required" /> Can anyone help me?

Best place for training PHP design patterns

Do you know any place on the internet where developers can train, experiment, learn and find many examples in use of design patterns for PHP?

C++ example for the Chain of Responsibility design pattern

a simple example of the Chain of Responsibility pattern. any comments would be welcome. thanks!

vendredi 27 octobre 2017

Matcher not matching patterns properly

I'm making a program that validates license plates for 31 States, each have different format and go from certain values also they should not include the letters I,O or Q in any of the license plates, here are the formats:

AGUASCALIENTES --from AAA-0001 to AFZ- 9999 

BAJA CALIFORNIA-- from AGA-0001 to CYZ-9999 

BAJA CALIFORNIA SUR-- from  CZA-0001 to DEZ-9999 

CAMPECHE -- from DFA-0001 to DKZ-9999 

CHIAPAS --  from DLA-0001 to DSZ-9999 

CHIHUAHUA -- from   DTA-0001 to ETZ-9999 

COAHUILA -- from EUA-0001 to FPZ-9999 

COLIMA --   from FRA-0001 to FWZ-9999 

DURANGO -- from FXA-0001 to GFZ-9999 

STATE OF MEXICO -- from LGA-0001 to PEZ-9999 

GUANAJUATO -- from  GGA-0001 to GYZ-9999 

GUERRERO -- from GZA-0001 to HFZ-9999 

HIDALGO --  from HGA-0001 to HRZ-9999 

JALISCO -- from HSA-0001 to LFZ-9999 

MICHOACÁN -- from PFA-0001  to  PUZ-9999 

MORELOS --  from PVA-0001   to  RDZ-9999 

NAYARIT -- from REA-0001    to  RJZ-9999 

NUEVO LEÓN -- from  RKA-0001    to  TGZ-999 

OAXACA --   from THA-0001   to  TMZ-9999 

PUEBLA--    from TNA-0001   to  UJZ-9999 

QUERÉTARO-- from    UKA-0001    to  UPZ-9999 

QUINTANA ROO-- from URA-0001    to  UVZ-9999 

SAN LUIS POTOSÍ-- from  UWA-0001    to  VEZ-9999 

SINALOA-- from  VFA-0001    to  VSZ-9999 

SONORA-- from   VTA-0001    to  WKZ-9999 

TABASCO-- from  WLA-0001    to  WWZ-9999 

TAMAULIPAS-- from WXA-0001  to  XSZ-9999 

TLAXCALA-- from XTA-0001    to  XXZ-9999 

VERACRUZ-- from XYA-0001    to  YVZ-9999 

YUCATÁN-- from  YWA-0001    to  ZCZ-9999 

ZACATECAS-- fromZDA-0001    to  ZHZ-9999 

So acording to the format a license plate for Campeche would go like this : DGB-5643

I made these patterns

   Pattern p1 = Pattern.compile("[a][a-z&&[^ioqghjklmnprstuvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m1 = p1.matcher(field_val.getText()); // aguascalientes

    Pattern p2 = Pattern.compile("[a|b|c][a-z&&[^ioqhjklmnprstuvwx]][a-z][-]\\d\\d\\d\\d");
    Matcher m2 = p2.matcher(field_val.getText()); // bajac

    Pattern p3 = Pattern.compile("[c|d][a-z&&[^ioqfghjklmnprstuvwxy]][a-z][-]\\d\\d\\d\\d");
    Matcher m3 = p3.matcher(field_val.getText()); // bajasur

    Pattern p4 = Pattern.compile("[d][a-z&&[^ioqabcdelmnprstuvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m4 = p4.matcher(field_val.getText()); // campeche

    Pattern p5 = Pattern.compile("[d][a-z&&[^ioqabcdefghjktuvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m5 = p5.matcher(field_val.getText()); // chiapas

    Pattern p6 = Pattern.compile("[d|e][a-z&&[^ioqabcdefghjklmnprsuvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m6 = p6.matcher(field_val.getText()); // chihuahua

    Pattern p7 = Pattern.compile("[e|f][a-z&&[^ioqabcdefghjklmnvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m7 = p7.matcher(field_val.getText()); // coahuila

    Pattern p8 = Pattern.compile("[f][a-z&&[^ioqabcdefghjklmnpxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m8 = p8.matcher(field_val.getText()); // colima

    Pattern p9 = Pattern.compile("[f|g][a-z&&[^ioqghjklmnprstuvw]][a-z][-]\\d\\d\\d\\d");
    Matcher m9 = p9.matcher(field_val.getText()); // durango

    Pattern p10 = Pattern.compile("[l|m|n|p][a-z&&[^ioqf]][a-z][-]\\d\\d\\d\\d");
    Matcher m10 = p10.matcher(field_val.getText()); // edomex

    Pattern p11 = Pattern.compile("[g][a-z&&[^ioqabcdefz]][a-z][-]\\d\\d\\d\\d");
    Matcher m11 = p11.matcher(field_val.getText()); // guanajuato

    Pattern p12 = Pattern.compile("[g|h][a-z&&[^ioqghjklmnprstuvwxy]][a-z][-]\\d\\d\\d\\d");
    Matcher m12 = p12.matcher(field_val.getText()); // guerrero

    Pattern p13 = Pattern.compile("[h][a-z&&[^ioqabcdefstuvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m13 = p13.matcher(field_val.getText()); // hidalgo

    Pattern p14 = Pattern.compile("[h|j|k|l][a-z&&[^ioqabcdetuvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m14 = p14.matcher(field_val.getText()); // jalisco

    Pattern p15 = Pattern.compile("[p][a-z&&[^ioqabcdevwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m15 = p15.matcher(field_val.getText()); // michoacan

    Pattern p16 = Pattern.compile("[p|r][a-z&&[^ioqefghjklmnprstu]][a-z][-]\\d\\d\\d\\d");
    Matcher m16 = p16.matcher(field_val.getText()); // morelos

    Pattern p17 = Pattern.compile("[r][a-z&&[^ioqabcdklmnprstuvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m17 = p17.matcher(field_val.getText()); // nayarit

    Pattern p18 = Pattern.compile("[r|s|t][a-z&&[^ioqhj]][a-z][-]\\d\\d\\d\\d");
    Matcher m18 = p18.matcher(field_val.getText()); // nuevoleon

    Pattern p19 = Pattern.compile("[t][a-z&&[^ioqabcdefgnprstuvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m19 = p19.matcher(field_val.getText()); // oaxaca

    Pattern p20 = Pattern.compile("[t|u][a-z&&[^ioqklm]][a-z][-]\\d\\d\\d\\d");
    Matcher m20 = p20.matcher(field_val.getText()); // puebla

    Pattern p21 = Pattern.compile("[u][a-z&&[^ioqabcdefghjrstuvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m21 = p21.matcher(field_val.getText()); // queretaro

    Pattern p22 = Pattern.compile("[u][a-z&&[^ioqabcdefghjklmnpwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m22 = p22.matcher(field_val.getText()); // quintanaroo

    Pattern p23 = Pattern.compile("[u|v][a-z&&[^ioqfghjklmnprstuv]][a-z][-]\\d\\d\\d\\d");
    Matcher m23 = p23.matcher(field_val.getText()); // sanluispotosi

    Pattern p24 = Pattern.compile("[v][a-z&&[^ioqabcdetuvwxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m24 = p24.matcher(field_val.getText()); // sinaloa

    Pattern p25 = Pattern.compile("[v|w][a-z&&[^ioqlmnprs]][a-z][-]\\d\\d\\d\\d");
    Matcher m25 = p25.matcher(field_val.getText()); // sonora

    Pattern p26 = Pattern.compile("[w][a-z&&[^ioqabcdefghjkxyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m26 = p26.matcher(field_val.getText()); // tabasco

    Pattern p27 = Pattern.compile("[w|x][a-z&&[^ioqtuvw]][a-z][-]\\d\\d\\d\\d");
    Matcher m27 = p27.matcher(field_val.getText()); // tamaulipas

    Pattern p28 = Pattern.compile("[x][a-z&&[^ioqabcdefghjklmnprsyz]][a-z][-]\\d\\d\\d\\d");
    Matcher m28 = p28.matcher(field_val.getText()); // tlaxcala

    Pattern p29 = Pattern.compile("[x][a-z&&[^ioqwx]][a-z][-]\\d\\d\\d\\d");
    Matcher m29 = p29.matcher(field_val.getText()); // veracruz

    Pattern p30 = Pattern.compile("[y|z][a-z&&[^ioqdefghjklmnprstuv]][a-z][-]\\d\\d\\d\\d");
    Matcher m30 = p30.matcher(field_val.getText()); // yucatan

    Pattern p31 = Pattern.compile("[z][a-z&&[^ioqabcjklmnprstuvwxy]][a-z][-]\\d\\d\\d\\d");
    Matcher m31 = p31.matcher(field_val.getText()); // zacatecas

I'm sending the result to a textfield called res

here are the matchers

 if (m1.find()) {

        res.setText(" Your State is  Aguascalientes");
    } else if (m2.find()) {

        res.setText(" Your State is  Baja");
    } else if (m3.find()) {

        res.setText(" Your State is  Baja Sur");
    } else if (m4.find()) {

        res.setText(" Your State is  Campeche");
    } else if (m5.find()) {

        res.setText(" Your State is  Chiapas");
    } else if (m6.find()) {

        res.setText(" Your State is  Chihuahua");
    } else if (m7.find()) {

        res.setText(" Your State is  Coahuila");
    } else if (m8.find()) {

        res.setText(" Your State is  Colima");
    } else if (m9.find()) {

        res.setText(" Your State is  Durango");
    } else if (m10.find()) {

        res.setText(" Your State is  Edomex");
    } else if (m11.find()) {

        res.setText(" Your State is  Guanajuato");
    } else if (m12.find()) {

        res.setText(" Your State is  Guerrero");
    } else if (m13.find()) {

        res.setText(" Your State is  Hidalgo");
    } else if (m14.find()) {

        res.setText(" Your State is  Jalisco");
    } else if (m15.find()) {

        res.setText(" Your State is  Michoacan");
    } else if (m16.find()) {

        res.setText(" Your State is  Morelos");
    } else if (m17.find()) {

        res.setText(" Your State is  Nayarit");
    } else if (m18.find()) {

        res.setText(" Your State is  Nuevo Leon");
    } else if (m19.find()) {

        res.setText(" Your State is  Oaxaca");
    } else if (m20.find()) {

        res.setText(" Your State is  Puebla");
    } else if (m21.find()) {

        res.setText(" Your State is  Queretaro");
    } else if (m22.find()) {

        res.setText(" Your State is  Quintana Roo");
    } else if (m23.find()) {

        res.setText(" Your State is  San Luis Potosi");
    } else if (m24.find()) {

        res.setText(" Your State is  Sinaloa");
    } else if (m25.find()) {

        res.setText(" Your State is  Sonora");
    } else if (m26.find()) {

        res.setText(" Your State is  Tabasco");
    } else if (m27.find()) {

        res.setText(" Your State is  Tamaulipas");
    } else if (m28.find()) {

        res.setText(" Your State is  Tlaxcala");
    } else if (m29.find()) {

        res.setText(" Your State is  Veracruz");
    } else if (m30.find()) {

        res.setText(" Your State is  Yucatan");
    } else if (m31.find()) {

        res.setText(" Your State is  Zacatecas");
    }

In cases where the first Letter Repeats in two or three states i don't get the correct match for the state i want

For example i input ABH-6262 and i get Your State is Baja California as a result and i'm expecting to get Aguascalientes

JavaFX Window Changer using FXML

I'm currently attempting to make a Window (Scene) changer when clicking on a button. Specifically, changing the window when logging in a user. I would like to know how I can possibly reduce redundant code, and placing the methods responsible for changing windows in a centralized place. Is there a specific design pattern to follow?

So far, I have this:

Main.java

public class Main extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = (Parent) FXMLLoader.load(getClass().getResource("Login.fxml"));
        Scene scene = new Scene(root);
        scene.getStylesheets().add("Styles.css");
        stage.setScene(scene);
        stage.setTitle("App");
        stage.setResizable(false);
        stage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

LoginController.java

public class LoginController implements Initializable {

    @FXML
    private TextField email;
    @FXML
    private PasswordField password;
    @FXML
    private Button buttonLogin;

    private Stage stage;

    @Override
    public void initialize(URL url, ResourceBundle rb) {}    

    @FXML
    private void login(ActionEvent event) throws Exception {
        stage = (Stage) buttonLogin.getScene().getWindow();
        Parent root = (Parent) FXMLLoader.load(getClass().getResource("Profile.fxml"));
        Scene scene = new Scene(root);
        scene.getStylesheets().add("Styles.css");
        stage.setScene(scene);
        stage.centerOnScreen();
        stage.show();
    }
}

Thanks!

Is it acceptable to return a canonical representation subclass from an abstract base class?

Suppose you have the following:

  • an abstract base class that implements common functionality;
  • a concrete derived class that serves as the canonical representation.

Now suppose you want any inheritor of the base class to be convertible to the canonical representation. One way of doing this is by having an abstract method in the base class that is meant to return a conversion of the inheritor as an instance of the canonical derived class.

However, it seems to be generally accepted that base classes should not know about any of their derived classes, and in the general case, I agree. However, in this scenario, this seems to be the best solution because it enables any number of derived classes, each with their own implementation we don't need to know anything about, to be interoperable via the conversion to the canonical representation that every derived class has to implement.

Would you do it differently? Why and how?

An example for geometric points:

// an abstract point has no coordinate system information, so the values
// of X and Y are meaningless
public abstract class AbstractPoint {
    public int X;
    public int Y;

    public abstract ScreenPoint ToScreenPoint();
}

// a point in the predefined screen coordinate system; the meaning of X 
// and Y is known
public class ScreenPoint : AbstractPoint {
    public ScreenPoint(int x, int y) {
        X = x;
        Y = y;
    }

    public override ScreenPoint ToScreenPoint()
        => new ScreenPoint(X, Y);
}

// there can be any number of classes like this; we don't know anything
// about their coordinate systems and we don't care as long as we can
// convert them to `ScreenPoint`s
public class ArbitraryPoint : AbstractPoint {
    private int arbitraryTransformation;

    public ArbitraryPoint(int x, int y) {
        X = x;
        Y = y;
    }

    public override ScreenPoint ToScreenPoint()
        => new ScreenPoint(X * arbitraryTransformation, Y * arbitraryTransformation);

    // (other code)
}

How to handle complex object creation correctly, even if objects have similar constructors

What is the best design pattern or method for handling complex object creation? Should this pattern change if some objects will have the same constructor?

I have a factory pattern class that contains the required constants to generate the object required. When creating an object, the developer should pass in the constant of their choice. Some of these objects will simply a parent constructor but others might be more complex.

Would the builder design pattern be better here?

class IbmApiRequestTypeBuilder {

    const INSTRUMENT_REQUEST = array("id" => 0,
        "requestUrl" => "/instrument/requestInstrumentList",
        "requestType" => "post",
        "requestBodyHead"=>"RequestInstrumentList",
        "requestBody" => "requestInstrumentList");

    const CREATE_SESSION_REQUEST = array("id" =>1,
        "requestUrl" => "/instrument/requestSession",
        "requestType" => "post",
        "requestBodyHead"=>"requestSession",
        "requestBody"=>"sessionRequest");


    public static function createApiRequestType($type) {

        $requestObj = null;

        switch($type['id']) {
            case 0:
                $requestObj = new IbmApiRequestInstruments($type['requestUrl'],
                $type['requestType'],
                $type['requestBodyHead'],
                $type['requestBody']);
            break;
        case 1:
            $requestObj = new IbmApiRequestSession($type['requestUrl'],
                $type['requestType'],
                $type['requestBodyHead'],
                $type['requestBody']);
            break;
         }

        return $requestObj;
    }
}

PostgreSQL Query Fields with Specific String Format

I have a PostgreSQL database, inside one of the tables we a string field that is formatted something like the following examples...

Fall 2017 MAT1277 OO4

Yet other fields may be something like this...

Fall 2017 Example Course For Name

I need to perform a query that ONLY searches for courses that are formatted like the first example (Fall 2017 MAT1277 OO4) but here's the catch. The following will remain the same yet the others will be different for each course.

Fall 2017 XXXXXXX OOX - Where X indicates the characters that will be different. Anyway to perform a query that will only return the course name's that are formatted in this fashion?

Thank You!

What design patterns are available for Data Classes in Java?

I have a complex class in Java whose responsibility it to mainly store Data. I was wondering if there are any design patterns available to guide such use cases. To be more specific, the class is something which records the overall performance of a student per semester.

Class StudentReport{
    cgpa = 3.1;
    Set <SubjectReport> perSubjectReportSet;
    overallFeedback = "..."
    ...
}

Class SubjectReport{
   subjectName = "Subject_A";
   gpa = 2.4;

   // Test Details
   test = Pass;
   testQuestionAnsweredCount = 8;
   testQuestionsCount = 10;
   testFeedback = None; // Feedback if FAIL

   // Assignment Details
   assignment = Pass;
   ...

   //Exam Details
   finalExam = Fail;
   examQuestionAnsweredCount = 5;
   examCorrectlyAnsweredQuestionCount = 2;
   examQuestionsCount = 10;
   examFeedback = "Blah Blah OOP" // Feedback if FAIL
}

Django: How to handle duplicate form submission

How to handle second submission duplicate request If a user was trying to refresh the page because of the first submission is not finished yet.

  • client side disabling submit button to avoid multiple submits.
  • and handled Post/Redirect/Get pattern after form submit redirect to success view

I believe both are handled well.

class SomeView(View):
  def post(self, request, *args, **kwargs):
    if form.is_valid()
      if request_exists(request):
        # here I can raise the exception also 
        # But How I redirect the customer to sucess page 
        # If 1st submission got success response.
      else:
        # here I have called internal api to get/post some data.
        # user refreshes before this call has completed.
        ...
        # once getting respose its ALWAYS redirect to new page
        return HttpResponseRedirect('/thanks/') 

But how to handle the case If delay from getting a response from API call. I need to delay until the first submission finishes. Then I have to send the user to the thanks page.

File Deduplication

A deduplication is a specialised form of compression for when the granularity of redundancy is large. one of the simplest implementation of duplication involves the three steps:

1: pick the size of the chunk, which is the granularity at which you want to duplicate a file.
2. inspect every non-overlapping chunk in the file (e. g. 0th KB,1thKB,2thKB….99thKB)and identify the unique ones.
3. for each unique chunk, take note of where they are found in the file (e.g. 0,1,2,3…99).

Task Overview

In this challenge, you’ll implement the following two function. dedup() reduplicates a large input file to a smaller output file. The contents and structure of outfield may vary depending on your implementation .however the size of this file must be smaller than the size of the input file! redup() uses the output file from the dedup() function to reconstruct(or reduplicate) the original file. in addition to the code, we also expect you to write a short design document.It should describe your solution at a high level how your solution works how your output file is structured. Difficulties you have to overcome, kinks you couldn’t iron out, etc.
please include a design document block at the very top of your solution

Requirements & Specifications
use a chunk size of 1KB(1024B) Input file’size is always a multiple of the chunk size.
Assume that each chance contains random bytes as the data. Hence, a file will be binary.
the input file may be too large to fit into memory.
Output file must be portable across programming languages and operating system.

Function prototype

dedup(input_file_path,deduped_file_path );

redup(deduped_file_path ,output_file_path);

please help me on this.This is very important for me.

What is the correct standard to implement MVP Design pattern

What is the correct standard to implement MVP Design pattern in android application development. with proper example.

Why does object's type refer to its interface?

Why does object's type refer to its interface? Why the term type is used here? In terms of C++ I am not able to understand it.

Gamma, Erich. Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series) (Kindle Locations 593-596). Pearson Education. Kindle Edition.

An object’s class defines how the object is implemented. The class defines the object’s internal state and the implementation of its operations. In contrast, an object’s type only refers to its interface—the set of requests to which it can respond. An object can have many types, and objects of different classes can have the same type.

Template method pattern with IDisposable pattern in C#

I see that the common guideline to implement the disposable pattern in C# is to have an abstract base class that implements the Dispose() method from IDisposable interface and provides a protected virtual Disposable(bool) method. Then sub-classes need to override Disposable(bool) and always do something like:

if (!disposed && disposing)
{
    // dispose resources here

    disposed = true;
}

My question is: wouldn't be possible reuse this pattern? I don't like to have to manage this "disposed state" in every subclass. We could have some abstract base class like this:

public abstract class AbstractResource : IDisposable
{
    private bool myDisposed = false;

    protected abstract void ReleaseUnmanagedResources();

    protected virtual void ReleaseManagedResources()
    {
        // optionally override this to explicitly call Dispose() of other IDisposable objects
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (!myDisposed)
        {
            if (disposing)
            {
                ReleaseManagedResources();
            }

            ReleaseUnmanagedResources();

            myDisposed = true;
        }
    }

    ~AbstractResource()
    {
        Dispose(false);
    }
}

Then users of this class only need to implement ReleaseUnmanagedResources and (optionally) ReleaseManagedResources. No need to deal with booleans.

I've found that this article proposes a similar technique. But that is it! Nobody else mentions it. Are there flaws with this approach?

How to wrap function with prefix and suffix in C

I'd like to know how to solve the wrapper problem from the Stroustrup paper but in C. I'm trying to find an efficient way to call

// prefix
GenericFunctionCallThatCouldHaveAnyNumberOfArgs();
// suffix

I've thought about creating a proxy function that takes an input a function pointer but the functions I want to wrap do not all have the same function signature.

My current solution is to create a Macro:

#define CALL(func) prefix; func; suffix;
CALL(myfunction(a, 'b', 1))

It works but it makes the code harder to understand especially when the prefix and suffix are complicated. Also the prefix and suffix are not necessarily calls to functions, they can be enclosures too. Is there a design pattern in C that does this efficiently (in terms of lines of code) while still maintaining readability.

Design my classes

I am learning design patterns and wanted to apply it to my classes in java. In my app, department is interface, there are different departments and have responsibility. Here is my class definitions

public interface department {
    public void responsibility();
}

public class MathsDept implements department {
    @override
    public void responsibility() {
    // have own my implementation.
    }
}

public class EnglishDept implements department {
    @override
    public void responsibility() {
    // have own my implementation.
    }
}

Now, these departments have their expenses, so management decided to give money on daily and monthly basis to run the department activities.

How to apply design patterns to such requirement, what design pattern will fit here.

  • Thanks in advance

Examples or ideas of implementing a queue and processor [on hold]

I'm working on an app which uses a queue to push operations to backend. The queue is necessary because internet might not be available and the queue needs to be run again next time internet is available.

Is there some examples of implementing this? I am looking for something simple, but extensible enough. What I am looking for is how to design components like the queue, queue processor\dispatcher, handling errors (remove operation from the queue when server responds with specific HTTP codes, rescheduling the queue in care of other types of errors, etc.).

At least, I'm looking for some direction to which kind of design pattern I should be using.

Where to store variables that are required at many places inside a program? [on hold]

I have two lists that are queried for data at various places inside my program. Do I have any other options than

- making it static (and possible copying it at the places where it's required)
- passing the lists along the stack

I don't like both options. The second one requires me to pass the lists to almost any function/enzire stack. First one increases the scope and restricts me to one List of each (need one for every socket connection though).
What's my choice here?

jeudi 26 octobre 2017

How to get the entity attributes/enum from child with parent as reference?

The purpose of the design should be that client will be able to call getAttribute() method without knowing if the dynamic object is from parent class or any of its child class.

Code compiled here is in a rudimentary stage.

Attribute Definitions

interface AttributeDefinition{

}

public class AbstractAsset<T extends AttributeDefinition>{
   protected T attribute;
   protected AbstractAsset(T attribute){
      this.attribute = attribute;
   }
   public T getAttribute(){
      return this.attribute;
   }
}
enum AssetAttribute implements AttributeDefinition{
   ASSET_ID,  
   CREATED_TIME
}
enum VehicleAssetAttribute implements AttributeDefinition{
   VIN,
   MAKE
}
enum MobileAssetAttribute implements AttributeDefinition{
   SIM_NO,
   IMEI
}

Entities

class Asset extends AbstractAsset<AssetAttribute>{
   public Asset(AssetAttribute){
     super(AssetAttribute);
   } 
}
class Vehicle extends AbstractAsset<VehicleAssetAttribute>{
  public Vehicle(VehicleAssetAttribute){
     super(VehicleAssetAttribute);
  }
}
class Mobile extends AbstractAsset<MobileAssetAttribute>{
  public Mobile(MobileAssetAttribute){
    super(MobileAssetAttribute);
  }
}

Factory

public class AssetFactory
{
   public Asset constructAsset(String assetType){
    if(assetType.equals("vehicle")){
      return new Vehicle(new VehicleAssetAttribute());
    }else if(assetType.equals("mobile"){
      return new Mobile(new MobileAssetAttribute());
    }
   }
}

This is what I have been trying to arrive at.

  1. A factory that takes in the argument of type, instantiates the child object, and "must" return that through a parent reference

  2. My client will only use the parent entity retrieved from the factory and get the dynamic(child) object's attribute.

  3. Also, require inheritance of attributes - i.e. VehicleAttribute, MobileAttribute would also have AssetAttribute's value.

Client

Row row = new Row();
Asset asset =  AssetFactory.constructAsset("vehicle");
row.set(asset.getAttribute().ASSET_ID, "xyz"); 
row.set(asset.getAttribute().CREATED_TIME, 12345); 
row.set(asset.getAttribute().VIN, TN23);
DO.persist(row);

Couple of points

  1. Not desirable for the client to hard code the attribute, construction of specific asset should be taken care of by the asset factory.
  2. AssetFactory will take multiple parameters - assetType, region for instantiating the specific asset
  3. A similar hierarchy will exist for the region also. (Vehicle - VehicleIN, VehicleCH)

I would appreciate if there is anything we could do to achieve the desired outcome.

What is the best way possible via design patterns to handle MULTIPLE SQL statements.. in a class

i have one scenario, I am getting multiple SQL (Select Queries) from a properties file. which by looping i need to set in prepared statement. post that i need to update '?' in every query in the same handler_class via a Single method.. IMP as you know '?' cannot be constant in all queries.

how to handle this scenario via design patterns. which pattern is most useful in this case. and how solve the problem gracefully? which can be leveraged in future too.

Is storing raw data with the result object bad practice?

I have a class that is already very long and that I'd like to split. At one point I do a lot of calculations (based on two integer and two Lists) and store the results into a result object.
My idea was to pass the integers and Lists to the "result object", do the calculations inside its constructor and assign the results to its instance variables (I would pass the result object in a subsequent step). This way I keep the code that is just a means to an end (needed only once to do the calculations) at the place where the result is stored.
This also keeps methods and data together at one place instead of two, which increases modularity. It leaves me with one class that has it all: the raw data, the algorithms and the results. I just need to assure to pass the parameters to the constructor.

Yet my gut feeling tells me that this is a design flaw. So, is storing raw data with the "result" object bad practice? Should I make the calculations inside the object or outside and simply use it as a DTO?

Instantiate class by passing required parameter depending on which environment you are in

I have a below enum class which has few fields in it stagePoolSize, prodPoolSize and enabled.

  public enum Type {
    process_caty(5, 8, false), process_misc1(5, 8, false), link_entry(5, 12, true);
    private final int stagePoolSize;
    private final int prodPoolSize;
    private final boolean enabled;

    private Type(int stagePoolSize, int prodPoolSize, boolean enabled) {
      this.stagePoolSize = stagePoolSize;
      this.prodPoolSize = prodPoolSize;
      this.enabled = enabled;
    }

    public int getStagePoolSize() {
      return stagePoolSize;
    }

    public int getProdPoolSize() {
      return prodPoolSize;
    }

    public boolean isEnabled() {
      return enabled;
    }

    @Override
    public String toString() {
      return name() + "=" + stagePoolSize + "=" + prodPoolSize + "=" + enabled;
    }
  }

And this is how I am using above enum to initialize my Handler class.

  private final List<Handler> handlers = new ArrayList<>();

  @PostConstruct
  public void postInit() {
    String datacenter = Utils.getDatacenter();

    for (Type consType : Type.values()) {
      if (!consType.isEnabled()) {
        continue;
      }
      int poolSize = Utils.isProd() ? consType.getProdPoolSize() : consType.getStagePoolSize();
      handlers.add(new Handler(consType, poolSize));
    }
  }

If any of the enum is enabled, then depending on which environment (whether Prod or Stage) we are in by checking with this call Utils.isProd(), we get it's poolSize and then use that poolSize to initialize Handler class.

Problem Statement:

Now I need to add few more enums in the same Type class but I need to do something different for them. Below are the enums I need to add:

abc_raw_pho
abc_raw_slq
abc_raw_lvk
abc_raw_pin_pho
abc_raw_pin_slq
abc_raw_pin_lvk

Here is what we need to do for above new enums:

  • It should only be used if the environment is Prod. And they will have some prodPool size value.
  • And also if we are in pho datanceter, then we should use enums that ends with pho. And if we are in slq datacenter then we should use enums that ends with slq. Similarly for lvk.

I can figure out which datacenter we are in by calling this method:

    String datacenter = Utils.getDatacenter();

Now how should I design my Type enum class so that my original enum works as it is which is already there and also my new enum with datacenter in the end works with the above conditions. So below is the requirement overall:

  • process_caty should be use both for Stage and Prod and it should use poolSize accordingly depending on what environment it is in.
  • process_misc1 should be use both for Stage and Prod and it should use poolSize accordingly depending on what environment it is in.
  • link_entry should be use both for Stage and Prod and it should use poolSize accordingly depending on what environment it is in.
  • abc_raw_pho should be use for Prod only but depending on which datacenter we are in and it should use poolSize for Prod only.
  • abc_raw_slq should be use for Prod only but depending on which datacenter we are in and it should use poolSize for Prod only.
  • abc_raw_lvk should be use for Prod only but depending on which datacenter we are in and it should use poolSize for Prod only.
  • abc_raw_pin_pho should be for Prod only but depending on which datacenter we are in and it should use poolSize for Prod only.
  • abc_raw_pin_slq should be for Prod only but depending on which datacenter we are in and it should use poolSize for Prod only.
  • abc_raw_pin_lvk should be for Prod only but depending on which datacenter we are in and it should use poolSize for Prod only.

What are the different patterns used developing a client side web application today?

Mine is not a technical question but I would like to read different opinions in one of the hottest topic of the web development nowadays.

I'm a software frontend engineer and I work with Ember.js (I didn't take this decision, it was already there when I started). In the old versions, it had an MVC approach and, up as it was being updated, the team behind it, left this pattern to embrace "Data down &actions up" (kind of Flux).

Actually, my question is: today, what are the most common patterns of the web development and, for each pattern, what are the frameworks that adopt it? I'm interested in a discussion that compares different patterns with their frameworks, and what should be the best situation to use each of them.

I hope the question is interesting for you as well (sorry if I did a O(n^2) complexity question due to the fact that we have to compare N patterns and N framework...😅 I'm joking 😛) looking forward to read what you think.

Thanks.

c language : how to get a number (n) and print 1 to n*n in form of a square

I want to produce an output like this:

get number n>=2

n=2 :

1 2 4 3 n=3 :

1 2 3 8 9 4 7 6 5

n=4 : 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7

first we go around nn square then (n-2)(n-2) etc...

#include <stdio.h>
int main(int argc, char *argv[]) {
int n;
scanf("%d",&n);
int x = n;

int table[n][n]; 

int i,j;

//initializing array with 0
for(i=0 ; i<n ; i++){
    for(j=0 ; j<n ; j++){
        table[i][j]=0;
    }
}



//printing array
for(i=0 ; i<n ; i++){
    for(j=0 ; j<n ; j++){
        printf("%d\t",table[i][j]);
    }
    printf("\n");
  }
return 0;
}

please help me how to solve this ...

Design pattern for command line software with multiple functionalities

I'm developing a program that is going to be called from the command line. The software will be a sort of 'kit' with differing functionality based on the different flags defined while calling the program. Some of this functionality is wildly differing from others and the only similarity is the type of file that it operates on.

I was wondering what the best design pattern is to implement this kind of functionality? I've read about the facade design pattern which splits each module into a different sub-system. Building each piece of functionality under a different facade would keep it modular and would allow me to build a single class to handle which facade to call.

Is this the best way to go about it, or would you recommend something different?

Thanks, Sam

How to avoid circular reference dependency in Angular4

I have two services.
First one is DataService, which is used to to requests to API.
Second one is AuthService, which does request to identity server and saves access_token.

I need to have DataService inside of AuthService so I can do the request.
I need to have AuthService inside of DataService, to append access_token for authorized access.

How can I resolve this circular dependency, without writing new "data service" class just for AuthService?

.net generic repository with petapoco

I have an N-Layer solution in .Net with PetaPoco as microORM. I get the entities generated from the template generator of PetaPoco. This entities T derive from the base class Record and then I extend them adding more data access facilities and customs Save() and Delete() methods that overrides the Record defaults methods.

Then when I create the generic repository the methods that get called are from the base class Record and not my custom ones from the entities. I need help designing my generic repository class so when I call an entityRepository.Delete() method the Delete() method that gets called is the one from the entity and not the one from the default one from the Record class.

Here is my code. Any suggestion is well received.

The generic repository class

public abstract class GenericRepository<T> : IGenericRepository<T> where T : Record<T>, new()
{
    public void Delete(T entity)
    {
        entity.Delete();
    }
}

The overrided Delete method from the entity (the method I want to get call)

public partial class Document : Record<Document>
{
    public new int Delete()
    {
        int rowsAffected;
        using (var uow = RealityDB.GetInstance().GetTransaction())
        {
            rowsAffected = base.Delete();

            LogSystem("Deleting", "Deleting a document", 0, 0, GUID);

            uow.Complete();
        }

        return rowsAffected;
    }
}

I log in the entity class and think is bad designed, but I don't now if this logic should be in the entities repository or in an unit of work implementation, which I don't know how to do well. Again any help would be appreciated, thanks in advance.

Generation of an array of objects with permutations of array values

I'm building an array of objects out of the permutations of the entries in some arrays. My first stab at the code is below, it should help to illustrate what I'm trying to achieve:

permutationsArray = (array1, array2, array3) => {
  const arrayOfObjects = [];
    for (let i = 0; i < array1.length; i++) {
      for (let j = 0; j < array2.length; j++) {
        for (let k = 0; k < array3.length; k++) {
          arrayOfObjects.push({
            aConstant: 'some constant',
            key1: array1[i],
            key2: array2[j],
            key3: array3[k],
          });
        }
      }
    }
  return arrayOfObjects;
};

I'm really unhappy with having nested for loops to achieve this. Alternatives I have looked at are:

  • Use nested mapping and flatten the tree created
  • Attempt a recursive system similar to this solution here

I'm looking for input as to whether I'm going in the right direction with solving this. Ideally I want to get to the point where I can supply as many arrays as I wanted.

A big problem I'm seeing is how to name the keys with recursion.

mercredi 25 octobre 2017

Access instance of containing class from instance of another class being contained

I'm creating a simple RPG game in C# using WPF, and have a Hero class which contains an instance of my Inventory class and an instance of my Equipment class. When a Hero selects any of their Item instances in their Inventory instance to equip, I want to be able to pass a reference back to the Hero instance to be equipped in their Equipment instance.

Right now I have only one Page where I let Heroes equip anything, but that's soon to change, and I was wondering if there's a way to make it work the way I want it to. I was considering passing the Hero instance as a parameter when instantiating the Equipment and Inventory instances, like so:

internal class Hero
{
    internal Equipment CurrentEquipment { get; set; }
    internal Inventory CurrentInventory { get; set; }

    internal void Equip(Item selectedItem)
    {
         //put in correct spot in Equipment
    }
}

internal class Inventory
{
    internal Hero Owner { get; set; }

    private void Equip()
    { 
        //remove from Inventory, send it to Hero instance to be equipped
    }

    public Inventory(Hero owner) => Owner = owner;
}

with my Equipment class having the same property and constructor, and wherever I instantiate Hero, I pass the reference to the containing Hero, like so:

Hero currentHero = new Hero();
currentHero.Inventory = new Inventory(currentHero);
currentHero.Equipment = new Equipment(currentHero);

so that I don't have to make so many calls to currentHero every time I want to do anything, I can just pass the Inventory instance to whatever Window I'm working on, the Inventory holding a reference to currentHero

_inventory.Equip(selectedItem)

is so much faster than my current method of calling in my actual build:

GameState.CurrentHero.Equipment.Equip(GameState.CurrentHero.Inventory.Items.Find(itm => itm.Name == whateverItem)

So, is there a better way of what I'm trying to do? What is it called when you pass a container object into an object it contains?

Advice on design pattern

I am in a software engineering class and I need to pick a design pattern to use for a 'feature'... I have two features, and one of them is to have a feature where a user can enter a zip code and time span of days (up to 7). A collection with weather ratings for each day is generated (say a vector of ints, with 1 being good and 3 being bad) that my teammates will use in the class to do various calculations with.

I just wanted some advice on a design pattern I can use because we are being forced to use one. I am using a singleton pattern for the GUI of the project, and I gotta think of one for this feature.

My thought process for the flow is as follows:

  • After user enters calculate, the GUI will call a function in this feature sending the zipcode and amount of days (to be stored in the GUI singleton maybe??)
  • My feature will take the Zipcode and # of days and connect to an OpenWeatherAPI, and will need to Parse through a JSON format being returned and for each day rate the weather (something very simple like if temp is over 70 degrees, rating is a 1, between 50-70, ratings is 2, and below 50 rating is 3) and store this into a vector collection and return this.

I just have to choose a pattern and justify why I chose it, create a class diagram, sequence diagram, etc. I was thinking of something that removed implementation from the interface, so maybe bridge? Honestly this 'feature' is small (probably isn't even a feature haha) and I don't know too much about design patterns.

Thank you so much in advance for your help!

Creating triangle sequences given a format...why won't my triangles be displayed

I'm trying to figure out what is wrong with my program. There should be four triangles printed as such:

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

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

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

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

Here is the code I have written so far:

public static String trianglePatterns(int limit) {
      // Triangle One
      for (int x = 1; x <= limit; x++) {
         for (int y = 1; y <= x; y++) {
            System.out.print(y + " ");
         }
         System.out.print("\n");
      }
      System.out.print("\n");
      // Triangle Two
      while (limit > 0) {
         for (int y = 1; y <= limit; y++) {
            System.out.print(y + " ");
         }
         limit--;
         System.out.println("");
      }
      // Triangle Three
      for (int row = 1; row <= limit; row++) {
         for (int space = 7; space >= 0; space--) {
            System.out.print(" ");
         }
         for (int num = 1; row >= 1; num--) {
            System.out.print(" " + num);
         }
      }
      return"";
   }

I haven't even started the fourth one because I have no idea how to. My program will run and display the first two triangles correctly, but just doesn't include the third when I run it. What is causing the problem, and how do I begin the fourth triangle?

Which design pattern should I use for console rasing sim?

I need to make a console racing simulator using gof (or other) design patterns, but I don't know which one to use here.

I already made the game, but it's more like "OOP for the sake of OOP style". It has a Car class which contains drive, control and gameover methods and and Obstacle method, which generates and moves an obstacles.

Which design pattern should I use to make the game? Can I recomposit existing classes or must I start it all from scratch?

Thank you for any help.

How to manage state?

  class Book {
    constructor () {
      this.state = { 'isInitializing': true, 'isFlipping': false, 'isZooming': false, 'isPeeled': false, 'isZoomed': false, 'isFlippable': false }
      this.mode = _viewer.getMatch('(orientation: landscape)') ? 'landscape' : 'portrait'
      this.plotter = { 'origin': JSON.parse(`{ "x": "${parseInt(d.getElementsByTagName('body')[0].getBoundingClientRect().width) / 2}", "y": "${parseInt(d.getElementsByTagName('body')[0].getBoundingClientRect().height) / 2}" }`) }
    }
  ...

I have a Book class with many states. The book uses CSS3 animations to turn over pages or pinch to zoom etc., during which its state changes from isFlipping: false to isFlipping: true, isZoomed: false to isZoomed: true.

There are mutually exclusive situations, for example when isZoomed: true the isFlippable must be false.

And then with event listeners:

  const delegateElement = d.getElementById('plotter')

  const handler = (event) => {
    event.stopPropagation()
    event.preventDefault()

    switch (event.type) {
      case 'mouseover':
        _handleMouseOver(event)
        break
      case 'mouseout':
        _handleMouseOut(event)
        break
      case 'mousemove':
        _handleMouseMove(event)
        break
      case 'mousedown':
        _handleMouseDown(event)
        break
      case 'mouseup':
        _handleMouseUp(event)
        break
      case 'click':
        _handleMouseClicks(event)
        break
      case 'dblclick':
        _handleMouseDoubleClick(event)
        break

And then later on depending on state: do stuff.

  const _handleMouseOver = (event) => {
    if (!event.target) return
    // do stuff depending on state, meaning lot of `if else` or `switch` `case ` statements.

  }    
  const _handleMouseOut = (event) => {
    if (!event.target) return
    // do more stuff.
  }

  const _handleMouseMove = (event) => {
    if (!event.target) return
    // do stuff depending on state.
  }
  …
  // more events as per list above… and so on.

Now this is going to make my code very unwieldy and horrible to read. :-(

I wonder what path should I take to organize logic (pattern) and handle state of the book per events as they are fired and animation completed (transitionend etc.).

What is the best place to call web services in iOS application with MVVMC architecture?

Currently I'm developing an iOS application by using MVVMC architecture. I was getting some idea about MVVMC by reading this article . As a typical MVVM model we know all the major app controllers like web service calls should call in the ViewModel class. But in the MVVMC architecture we can user either Coordinator or ViewModel to call web services. I couldn't figure out what's the best place for this.

I'm currently trying to implement user list page of the application using UITableViewController. Following are the some parts of my UserCoordinator and UserViewModel classes.


UserCoordinator

class UsersCoordinator: Coordinator {

var window: UIWindow
weak var delegate: UsersCoordinatorDelegate?

var  selectedCity: City?

init(window: UIWindow) {
    self.window = window
}

func start() {
    let storyboard = UIStoryboard(name: "Users", bundle: nil)
    if let vc = storyboard.instantiateViewController(withIdentifier: "list") as? UsersListController {
        var viewModel = UsersListViewModel()
        viewModel.delegate = self as UsersListViewModelDelegate
        viewModel.veiwController = vc
        vc.viewModel = viewModel
        vc.coordinationDelegate = self as CoordinationDelegate
        let nav = UINavigationController.init(rootViewController: vc)
        window.rootViewController = nav
    }

}


UserViewModel

 protocol UsersListViewModelDelegate: class  {
    func selectUser(viewController: UIViewController, city: City)
}

struct UsersListViewModel {
    var delegate: UsersListViewModelDelegate?
    weak var veiwController: UsersListController!
    var source = [String]()

    init() {
        for user in users {
            source.append(user.name)
        }
    }

    func selectRow(row: NSInteger) {
        delegate?.selectUser(viewController: veiwController, user: users[row])
    }

    fileprivate var users: [User] {
        get {
            //web service call??
        }

Where should I call the web service here? As I have read theoretically Coordinator is the dedicated place for application routing. So according to that it's better to call web services in ViewModel. But I feel it's better to call web services in the Coordinator because it'll load data very quickly and populate the viewModel. What should I do?

Return NULL in case of success

I just had an intense discussion with a colleague of mine about a question of design, and would appreciate some opinion.

We have a method that takes an argument and that:

  • can fail, returning NULL
  • can succeed in two forms:
    • a solution is not found "immediately" (what's behind this is not important) and the method returns a modified version of the argument
    • a solution is found "immediately" and the argument needs not be modified.

In that last case, I would return the unmodified object. So in case of failure, the method returns NULL, and in case of success, it always returns an object (we have a mean to test if it has been modified or not), that has to be destructed by the caller (we are in C++).

My colleague recommends to return NULL in the case of the method succeeded without modifying the object, to avoid a copy and a useless destruction.

But a method that returns NULL in case of success in some case sounds like a terrible design to me.

What are the recommendations in this case?

Use builder pattern in Spring for rest api

I'm creating rest api in spring boot and I need suggestions on whats the best approach to use builder pattern in Spring because I'm new to Spring.

Product.java (Database entity)

public class Product{
    private String name;
    private String sku;

    //getter-setter
}

ProductBuilder.java

public interface ProductBuilder {
    public ProductBuilder setBasicDetails(String name, String sku)
}

ProductBuilderImpl.java

public class ProductBuilderImpl implements ProductBuilder{

    // issue is with creating new object of `Product`

    @Override
    public ProductBuilder setBasicDetails(String name, String sku) {
        product.setName(name);
        product.setSku(sku);
        return this;
    }
}

Suggestions for creating new object of Product for multiple HTTPRequest in following approaches.


Approach 1: @Autowired ProductBuilder.

@Service
public class xyzServiceImpl implements xyzService{

    @Autowired
    private ProductBuilder productBuilder;

    // business logic
}

xyzServiceImpl is singleton so ProductBuilder will create only one object of Product and its shared between Thread/Request

HTTP Request 1: Product is initialized with id = null > Perform save > id = 123

HTTP Request 2: Got the object[Product.id = 123] updated in HTTP Request 1 but I want new object every time.

So I tried following solution but not working

@Configuration
public class ModelBuilderConfiguration {

    @Bean
    @Scope(value = "prototype")
    public ProductBuilder productBuilder(){
        return new ProductBuilderImpl();
    }
}

and creating initMethod in ProductBuilderImpl to create new object.

@Configuration
public class ModelBuilderConfiguration {

    @Bean(initMethod = "initMethod")
    @Scope(value = "prototype")
    public ProductBuilder productBuilder(){
        return new ProductBuilderImpl();
    }
}

and I used @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) but this is also not working.

And using ThreadLocal works with @Autowired but is it recommended?

public class ProductBuilderImpl implements ProductBuilder{

    private ThreadLocal<Product> product = new ThreadLocal<Product>(){
        @Override
        protected Product initialValue() {
            return new Product();
        }
    };

    @Override
    public ProductBuilder setBasicDetails(String name, String sku) {
        product.get().setName(name);
        product.get().setSku(sku);
        return this;
    }
}

Approach 2: Create new object in constructor.

public class ProductBuilderImpl implements ProductBuilder{

    private Product product;

    public ProductBuilderImpl() {
        product = new Product();
    }

    @Override
    public ProductBuilder setBasicDetails(String name, String sku) {
        product.setName(name);
        product.setSku(sku);
        return this;
    }
}

And use it in xyzServiceImpl like ProductBuilder productBuilder = new ProductBuilderImpl(); so I'll get the new object every time.

So which is best approach considering spring? Or suggest better way for initializing Product object.

Programming dependencies/relationships in python

I am designing a class in python whose properties have a mesh of interdepencies.

Say like it has a property A. When A is set to True then properties B and C can be used. Or else they cant be used. Property B and C may be of any type. May be a boolean or int or string or any custom class.

Also say if B is enabled then we can have either properties D or E or F ( a checkbox like behaviour).

How do i design such dependencies in python class?.

Also i may have similar classes which have such dependencies.. So i am thinking of making a metaclass or baseclass or template like design where user will specify dependencies and code is internally generated.

Any design inputs on how to proceed?

How to set up cron jobs can not run any time?

i set up cron jobs run in :

@Scheduled(cron = "${cron.schedule.pattern}", zone = "Asia/Singapore")

And in file config :

cron.schedule.pattern=*/40 * 7-23 * * *

how to change pattern to @Schedule can not run instead of comment line @Schedule.

Can someone help me to come up with a regular expression to extract the time from following text? [on hold]

using java pattern and matcher want to extract the time

bbc.com : Pakistani blogger says he was tortured (09:16 AM)

mardi 24 octobre 2017

AbstractFactory DP or Builder DP?

I am a beginner in design pattern. I did some practice to improve my skills in this subject, but I am stuck now in this problem.

I cannot figure out which Design pattern suits more for this pattern:

I would create an object that its creation takes many steps. The process is described like that:

  1. The workflow receives a json string data like this {"jws": "some data"}
  2. It derserialize the data and get a value of jws attribute
  3. This value passes a validation process that its output is another json data (extracted from the jws attribute)
  4. This new json data is deserialized as "T" object

Another workflow is described like that:

  1. The workflow receive an object data
  2. It passes a validation process that return a string value
  3. This value is transformed to another type (dict as an example)
  4. Return the new value

I was thinking about AbstractFactory DP and Builder DP but I did not find how to model it.

I am using C# as programming language and ASP.NET Core

The instantiation of the 2 workflow it will be handle by dependency injection later

Abstract Factory for different DB connections

I have a class which establishes connection to DB and queries for some data.

public QueryProcessor queryProcessor;
public ConnectionDataSource dataSource;

public String driver_type;
public String url;
public String username;
public String password;

public DataBaseHelper(){
        driver_type="oracle.jdbc.OracleDriver (DERIVED FROM SUBCLASS)";
        url="DERIVED FROM SUBCLASS";
        username="DERIVED FROM SUBCLASS";
        password="DERIVED FROM SUBCLASS";
        }

private void connect(){
        dataSource=new ConnectionDataSource();
        dataSource.setDriverClassName(driver_type);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        queryProcessor=new QueryProcessor(dataSource);
        }


public <T> Object query(String SQLQuery){

        connect();
        return queryProcessor.queryForObject(SQLQuery);

}

My task is to make Abstract Factory out of this class in order to support few types of DB connections. (e.g Oracle, MySQL , Postgre) so I can execute queries to all types of DB.

I will appreciate if somebody can post an example of Abstract Factory used for multiple DB connection.

Generic interface inheritance castings

Currently, I'm facing up with a generic interfaces inheritance problem:

interface IParent<T> {
    R Accept<R>(IParentVisitor<T, R> visitor);
}

interface IChild<T, TKey> : IParent<T> {
   R Accept<R>(IChildVisitor<T, TKey, R> visitor);
}

I've also created these Visitor interfaces:

interface IParentVisitor<T, R> {
    R Visit(IParent<T> parent);
}

interface IChildVisitor<T, TKey, R> : IParentVisitor<T, R> {
    R Visit(IChild<T, TKey> viz);
}

Implementations:

class ParentVisitor<T> : IParentVisitor<T, MyResultClass> {
    MyResultClass Visit(IParent<T> parent) {
      return //...;
    }
}

class ChildVisitor<T, TKey> : IChildVisitor<T, TKey, MyAnotherResultClass> {
    MyAnotherResultClass Visit(IChild<T, TKey> child) {
      return //...;
    }
}

Up to now, everything seems to be right. However, guess this situation:

static void Main() {
    IList<IParent<MyT>> interfaces = new List<IParent<MyT>>();
    interfaces.add(new Parent<MyT>());
    interfaces.add(new Child<MyT, string>());
    interfaces.add(new Child<MyT, int>());
    interfaces.add(new Child<MyT, TimeSpan>());
    //...

    //(!!*!!)
    foreach (IChild<MyT, string> stringChild in interfaces.OfType<IChild<MyT, string>()) {
      ChildVisitor stringChildVisitor = new ChildVisitor<MyT, string>();
      var result = stringChild.Accept(stringChildVisitor);
      //...
    }

    //(!!*!!)
    foreach (IChild<MyT, int> intChild in interfaces.OfType<IChild<MyT, int>()) {
      ChildVisitor intChildVisitor = new ChildVisitor<MyT, int>();
      var result = stringChild.Accept(intChildVisitor);
      //...
    }

    //and so on up to infitiny types in C#...
}

I think it's a non-viable way to get what I want.

What I want to get is to use a ChildVisitor on whichever IChild<T, *>, where * is whichever type. I don't know if I've explained so well.

Something like that:

//(!!*!!)
foreach (IChild<MyT, *> asterisckChild in interfaces.OfType<IChild<MyT, *>()) {
  ChildVisitor asterisckChildVisitor = new ChildVisitor<MyT, *>();
  var result = asterisckChild.Accept(asterisckChildVisitor);
  //...
}

Any ideas?

I want subobjects in JavaScript

I want to organize my JavaScript-Object in something like "submodules" and I wrote this:

'use strict';

var APS = (function () {

    var dashboard = (function () {
        var onReady = function () {
          alert(2);
        };

        return {
            onReady: onReady
        }
    });

    var onReady = function () {
        alert(1);
        dashboard.onReady(); // does not work
    };


    return {
        onReady: onReady,
    }
})();

$(document).ready(APS.onReady);

alert(1) does work, dashboard.onReady() does not work and I receive this error message:

Uncaught TypeError: dashboard.onReady is not a function

I want to organize my code in different "subpackages" below APS to have a kind of hierachy. How can I achieve that?

lundi 23 octobre 2017

Adapter Pattern with different abilities for each adaptee

I am writing a program that will make use of the adapter pattern for a handful of APIs. The goal is to be able to combine and aggregate data from each API. The problem is, not every API has the same functionality. For example:

API A

  • List all markets
  • List specific market price
  • List orders

API B

  • List specific market price
  • List market 24hr high/low

Notice how API B is able to get the 24hr price highs and lows, but API A cannot. Meanwhile, API A can list all markets available, while API B cannot.

What is the ideal way to approach a scenario like this?

  • I have thought about having a FLAGS enum that lists each API's functionalities, but that feels like a roundabout way of doing things and requires a lot of additional code for checking and whatnot.
  • I have considered separate adapters for each ability that the API can handle, but that could require a great deal of inheritance to the point where each API was using 5+ interfaces for the actions alone.

My goal is to make the program easily extendable to other APIs in the future. If this is my goal, how should I approach this? (I am using C# if that matters)

Static methods and inheritance

So i'm using an MVC design pattern to manage my scenes in my game.

I have an object named GameLoop with a method called "LoadView" which accepts an object called GameView. When LoadView is called, it stores the scene in a member variable, and subscribes event handlers to a GLFW window object.

both LoadView and ViewController are abstract classes which will be inherited by individual views and controller objects. The controller contains all the necessary event call backs for the Window, however GLFW only accepts static methods as event handlers.

My question is this; If I load an object which inherits GameController from a method that takes in an abstract GameController class, and I try to access its overloaded on_keypress_event, will it call the on_keypress_event defined by the parent or the abstract object?

I'm basically trying to figure out how to overload a static method.

Should I use a function pointer to grab the handler and subscribe it to the window?

JAVA obtain ResultSet from DB, segregate them in different files, send these files to different email ID's

I am struggling with one problem. The problem statement is to start Multiple Threads simultaneously. Every thread responsibility is to fetch records from DB. every records will have groupID. meaning if we get 100000 records with 10 distinct GroupID's... 10 files will be created with respective number of records in every file. Now we need to send all these 10 files to 10 different sources.

How to configure the same in Springs..? Which design pattern should be used.? if you have any example please let me know.

I am using properties file to provide SQL statements, which will return Result set and then to store them in temporary files. These files i send via email. but i am unable to segregate via groupID's and different mails.

How to determine which object to create in a factory pattern

I'm creating an autocomplete functionality from scratch using Angular 2. I need to listen for different keystrokes and perform a different action depending on what keystroke is pressed. There are four types of keystrokes I must listen for: an enter press, a down arrow press, an up arrow press, and a key press that would fire a new autocomplete query (ex: backspace, alphanumeric keys, delete, something that changes the value of the string in the input text box).

My project lead wants me to implement a design pattern for creating the keystroke handlers, and recommended the factory pattern (most likely as practice with design patterns). So the theoretical factory would create a different object for each of my four types of keystrokes. The listener gives back a string that I can use to determine which key was pressed (ex "ArrowUp, "ArrowDown", "Enter"). So the enter handler would select the highlighted option and populate it into the text box. A down handler would deselect the current option and select the option below it.

What is the best way for the factory to determine which object to create. For example I could do something like:

createHandler(keystroke) {
  //or alternatively use a case statement
  if(keystroke === "Enter") {
    return new EnterHandler();
  } else if(keystroke === "ArrowDown") {
    return new ArrowDownHandler();
  } else if(...)
}

But after reading up on this pattern, this is a "naive" implementation. What is the best way to know which object to create based on a string passed in then for my particular case? Or is there another better pattern for the functionality I am looking for?

Factory design pattern : jar breakup

I would like to know how would I break a project into multiple jar files if I have many factory classes as below:

class Reconciler {
      public void process() {
AbstractOperatorX opX = OperatorXFactory.getInstance(reconcilerName);
opX.perform();
  .....
AbstractOperatorY opY = OperatorYFactory.getInstance(reconcilerName);
opY.perform();
......
AbstractOperatorZ opZ = OperatorZFactory.getInstance(reconcilerName);
opZ.perform();
....
}

Let us assume there are

  1. Two implementations of AbstractOperatorX viz. DeviceOperatorX and CardOperatorX, to returned by OperatorXFactory.
  2. Two implementations of AbstractOperatorY viz. DeviceOperatorY and CardOperatorY, to returned by OperatorYFactory.
  3. Two implementations of AbstractOperatorZ viz. DeviceOperatorZ and CardOperatorZ, to returned by OperatorZFactory.

Now if I have to deploy this project in the best modular way, I think I can decompose it into following jars:

  1. reconciler-framework.jar which has class Reconciler
  2. reconciler-operation-utils.jar which has classes AbstractOperatorX, AbstractOperatorY, AbstractOperatorZ
  3. device-reconciler.jar which contains DeviceOperatorX, DeviceOperatorY, DeviceOperatorZ
  4. card-reconciler.jar which contains CardOperatorX, CardOperatorY, CardOperatorZ
  5. factory.jar which contains OperatorXFactory, OperatorYFactory, OperatorZFactory

Thus tomorrow, if a Port Reconciler comes up, I need to change only factory.jar and NO OTHER jar. Is this the right way to modularize the jar files or is there a better way. Or am I modularizing it too much.

Design patterns for Unreal Engine like graph editor

I would like to implement my own Graph Editor on C++ with basic math operations on numbers and vectors. Many game engines and modeling tools already have similiar instruments such as Unreal Engine or Houdini, but the question is what design patterns are used there. enter image description here enter image description here enter image description here

what is the difference between Decorator and mediator patterns in JavaScript

Recently I started learning the JavaScript patterns. When I am comparing Angular 4 from Angular 1.x. I have seen some new patterns in the Angular 4.

What patterns are used in the Angular 4 ?

Can we have chance to implement Decorator Pattern in the Angular 1.x?

Is Angular using $broadcasts or $emits for standard Mediator Pattern implementation?

Which Design Patterns is suitable for an inventory application?

  1. Which design pattern is suitable for an inventory application.
  2. Which design pattern is suitable for handling database transactions.

In java,Why we need Observer Design Pattern If we can use Transcation updated by Database?

When I read Observer Design Pattern,I understood is that whenever there is update to an object that has one to many relationship,we can send update message to other objects by using Observer Design Pattern.But I think is that we can use Database transaction to update table that has one to many relationships and its related tables whenever we need to update that table.So Why we need to use Observer Design Pattern if we can use DataBase.If my question is stupid enough,Please pardon me.

I will wait your explanation eagerly.Have a nice day!

dimanche 22 octobre 2017

regex C# pattern

I'm having some problems. I have a string : "My wife is pregnant, she can't eat anything, please give me some help ? "; Now: I want to compare this with input from use, who can type freely, i need to compare my string with their string, i must be match to show out their input is wrong or right. Here are some answers from users: " My wife is (1) pregnant, she can't eat anything,(2)please give me some help ?";

1, (1) they have 2 space while i have one, if i compare them together, they are wrong, but the answer is right. 2,(2) i have a space after comma ',' but they don't have it, one more time, if i try to compare,it's wrong Could you guys please give me a standard pattern for my string, and i will replace the input of users to be like my string, and compare them. Here are the right input can be accepted: 1, "My wife is pregnant , she can't eat anything , please give me some help ? "(TRUE) 2," My wife is pregnant , she can't eat anything , please give me some help ? "; (true) then i will use a pattern to format the input to be "My wife is pregnant, she can't eat anything, please give me some help ? ";(my string)

Thanks in advance!