dimanche 31 décembre 2017

How to store attribute-matching rule objects that match entities as they flow through a system?

I need help figuring out a good way of storing (and later retrieving / matching) dynamic rules that can be used to match objects as they flow through a workflow system.

In this scenario I am building a system that will have a series of steps operate on objects that are posted to it before the objects are finally ready to be stored for later consumption in another API. Those steps need to be configurable by an administrator; the system should allow them to say "if an object passes through with attributes ABC, then perform operation XYZ on it". Here's a very basic idea of the flow of the system:

+-------+  +-----------+ +-----------+ +-----------+ +-----------+ +-------+
|       |  |           | |           | |           | |           | |       |
|       +--> Ruleset 1 +-> Ruleset 2 +-> Ruleset 3 +->   Object  +->       |
|       |  |           | |           | |           | |  Storage  | |       |
| Input |  +-----+-----+ +------+----+ +-----+-----+ +-----------+ | Final |
|  API  |        ^              ^            ^                     |  API  |
|       |  +-----+--------------+------------+-----+               |       |
|       |  |                 Rule                  |               |       |
|       |  |              Management               |               |       |
+-------+  +---------------------------------------+               +-------+

The matching of objects to configuration rules needs to be attribute based (shown in the example below). That is, the person administering the rules needs to be able to give one or more attribute names, along with the value for that attribute, and the system will need to run that rule any time an object with that attribute name/value combination passes through it. Also, any time a rule is created or edited, we will need to be able to find all already-persisted objects that match the new/edited rule.

For example, consider that the following rules have been configured:

Rule 1 {
   priority: 10,
   $match: {
      type: "gadget",
   },
   $set: {
      priceIncrease: 1.2,
   }
}

Rule 2 {
   priority: 10,
   $match: {
      type: "widget",
   },
   $set: {
      priceIncrease: 1.1,
   }
}

Rule 3 {
   priority: 100,
   $match: {
      type: "widget",
      category: "kitchen",
   },
   $set: {
      priceIncrease: 1.15,
   }
}

Then, the following three entities pass through the system:

Entity 1 {
   type: "widget",
   category: "toys",
   manufacturer: "Acme",
   price: 5,
}

Entity 2 {
   type: "widget",
   category: "kitchen",
   manufacturer: "Acme",
   price: 6,
}

Entity 3 {
   type: "gadget",
   category: "tools",
   manufacturer: "XYZ Co",
   price: 10,
}

As each entity flows through the system, here are the matches:

  1. Entity one (a toy widget) matches only rule two because it is a widget.
  2. Entity two (a kitchen widget) matches rules two and three because it is a kitchen widget.
  3. Entity three (a tool gadget) matches rule one because it is a gadget.

I'm not too concerned about how to store the actual operations that need to take place - you can ignore that part; operations stored in the data store will be tied to code that knows how to understand the data structure of the operation once the rules are matched.

The main concern is: what kind of data store to use, and what kind of data model to use, to store the rules and entities so that I can:

  1. Find rules that match an entity as entities pass through the system, and
  2. Find entities (from the already-persisted entities) that match a rule when a rule is changed or added to the system.

Since we use AWS for everything we do, and try to do as much as possible serverless, it would be a great benefit if the data store could be something that AWS offers as a managed service. For example, are there existing patterns for doing this with:

  • Relational databases (Aurora)
  • NoSQL key/value (DynamoDB / Redis)
  • Graph databases (Neptune)

The dataset won't be huge, but won't be trivial either; millions of entities will pass through the system, and there will be hundreds of rules, so no full table scans for either of the types of operation.

Also, what's the correct terminology for a system as described above? Surely there's already design patterns / terms for this, but I'm struggling to find the right ones.

Thanks!

ECS - Generic Component or Casting Component

I am building an Entity Component System for a game from scratch in Java. I understand the theory behind the system, but I cannot quite wrap my head around how to implement it in practice. In theory there are two ways to design components.

  1. as a raw data container i.e.

    Component as raw data container
    public class Component{
        public float[] rawdata;
    
        public Component(float... rawdata){
            this.rawdata = rawdata;
        }
    }
    
    //An example "definition" to interpret raw data
    public class VectorDefinition{
        public final static int
                            X = 0,
                            Y = 1;
    
        public static void setX(Component component, float x){
            component.rawdata[X] = x;
        }
    
        public static void setY(Component component, float y){
            component.rawdata[Y] = y;
        }
    
        public static  float getX(Component component){
            return component.rawdata[X];
        }
    
        public static float getY(Component component){
            return component.rawdata[Y];
        }
    
        public static Component createVectorComponent(float x, float y){
            return new Component(x, y);
        }
    
    }
    
    
  2. or by implementing a common interface, casting when necessary i.e.

    //Component as interface
    public interface Component{
    }
    
    //An example implementation of the component interface
    public class Vector implements Component{
        public float
            X,
            Y;
    
        public Vector(float x, float y){
            X = x;
            Y = y;
        }
    }
    
    

I find that both options are not without their issues. The problem I have with components as raw data containers is the lack of control over available types of data inside of the component (e.g. In order to store String data I would have to include a String[] array in the Component class). I would prefer to just implement a common interface, but I am not sure how to best tackle casting in this manner (e.g. when type erasure inevitably screws me because I am using generic lists/maps to store components).

My questions specifically are:

  1. are any of these methods objectively better, why?
  2. how would I implement either solution properly?

I have been trying to build this for about a month now and I feel that I have read almost everything free that I can find on ECS. Can anyone point me in the right direction? Like I said before, I feel that I have a solid understanding of the theory, I would just like to see some concrete implementation at this point.

Implementing multiple interfaces in a class

I have two interface, interface i1 and interface i2. Both of them have different methods. class c1 is extending interface i1 and interface i2.
I am using dependency injection and want to inject the c1 dependency. Also as a good programming practice we should also code to interface. But if i declare a reference variable using i1 then i cant use i2 methods and vice versa.

Also i want that i1 and i2 to be separate interfaces because i1 is being implemented by other classes as well and those classes don't need i2 methods.

What is the best way to solve this problem?

Is this Simple Factory violating the Open Closed Principle?

Is this Simple Factory violating the Open Closed Principle?

The SimpleProductFactory needs to change every time a new concrete product needs to be created but it adheres to the single responsibility principle because that is the only reason it will ever change. Its sole purpose is so that the Client does not violate the open closed principle so I imagine it can't be a violation itself since obviously this code is needed somewhere.

I am not interested in changing the factory but whether this specific example is a violation or not.

Product

interface Product{
  public int getPrice();
}

Milk

class Milk implements Product{
  public int getPrice(){ return 5; }
}

Chips

class Chips implements Product{
  public int getPrice(){ return 3; }
}

SimpleProductFactory

class SimpleProductFactory{

  public Product createProduct(String productName){

    if(productName.equals("milk")){
      return new Milk();
    }
    else if(productName.equals("chips")){
      return new Chips();
    }
    return null;
  }
}

Client

class Client{
  public static void main(String[] args) {
    SimpleProductFactory productFactory = new SimpleProductFactory();
    Product prod = productFactory.createProduct("milk");
    System.out.println(prod.getPrice());

  }
}

Is it OK to do many database round trips in one controller action

I am writing a web app that has an admin dashboard and that has a summary of all the data in the db.

Is there a way to get all these data from different tables in one round call ?

I am also concerned about my repository design. I return an IQueryable since it's by no way gonna be efficient to get all the data as IEnumerable in the memory and to perform more filtering/pagin in the middle using extension methods.

Is there a better way to make my repository?

Here is my ViewComponent action (which can be a controller action as well):

public async Task<IViewComponentResult> InvokeAsync()
    {
        var agents = _repository.AgentData.GetAll();
        var applications = _repository.ApplicationData.GetAll();
        var paymentRequests = _repository.PaymentRequestData.GetAll();

        var universityCommissionCalcuator = new CommissionUniversityCalculator(0);
        var commissionCalcuator = new CommissionReferralCalculator(universityCommissionCalcuator);
        var commission = await _repository.AgentData.GetTotalCommissions(applications, commissionCalcuator);

        var result = AdminSummaryMapper.ToViewModel(agents, applications, paymentRequests, commission);

        return View(result);
    }

AdminSummaryMapper:

public static class AdminSummaryMapper
{
    public static AdminSummaryViewModel ToViewModel(IQueryable<Agent> agents, 
                                                    IQueryable<Application> applications, 
                                                    IQueryable<PaymentRequest> paymentRequests,
                                                    Commission commission)
    {
        var result = new AdminSummaryViewModel()
        {
            TotalStudents = applications.Count(),
            ConfirmedStudents = applications.Count(app => app.ApplicationStatus == ApplicationStatus.Confirmed),
            UnderEvaluationStudents = applications.Count(app => app.ApplicationStatus == ApplicationStatus.UnderEvaluation),
            TotalAgents = agents.Count(),
            PaymentRequests = paymentRequests.Count(),
            TotalCommission = commission.TotalComission,
            NetCommission = commission.NetComission,
        };

        return result;
    }
}

what design pattern is behind Entity Framework's IEntityWrapper interface?

I was examining EF6 code. I encountered IEntityWrapper interface, BaseEntityWrapper class and EntityWrapper.

What is the design pattern implemented here?

About AbstractDocumentPattern

Hi I'm junior Java developer and I am studying design pattern.

In AbstractDocumentPattern, Document interface has 3 methods like below.

public interface Document {    
  Void put(String key, Object value);    
  Object get(String key);    
  <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor);
}

My question is that why children method needed?

Just Can't I add implementation like HasT?

I know AbstractDocumentPattern can have all type properties like String, number even subDocument. so I guess, children is specific method for subDocuments property. is it right?

How replace inheritance with delegation

i have a code. How replace inheritance with delegation:

 abstract class Dog {
void bark();
void eat();
}

class Shpitz extends Dog {
void bark();
void eat();
}

class DauchSpitz extends Dog {
void bark();
void eat();}

samedi 30 décembre 2017

Layered Architecture for MVC, WebAPI, Angular JS, EF

I am new to ASP.NET MVC. Previously i worked with webform, the solution structure will be UI Layer, Service Layer, Business Layer, Data Access Layer.

Now i am venturing into ASP.NET MVC, ANgular JS, WEBAPI to develop enterprise application

So i need your help. Can you point me to Layered architecture in which i can use MVC5, WebAPI, Angular JS, EF. if there is proper document it will be very useful for my learning.

Layers should use Dependency Injection, UnitOfWork and any patters ( am not sure of repository pattern how it works with EF)

if the same thing available for MVC6, can you point me the relevant links.

OOP Abstraction: multiple, yet rather distinct, contexts?

I've been doing some research on OOP concepts and am having a bit of an issue in trying to understand what exactly Abstraction is. I've gone over numerous Stack Overflow posts on the topic but haven't really been able to pinpoint a satisfying answer.

I've seen a lot of discussions on the differences between Abstraction and Encapsulation, and naturally started started thinking about Abstraction in terms of hiding how a particular class works and providing abstraction through the class API. Here are some posts that steered me in this direction:

However, as I read through more posts, I noticed answers portraying Abstraction in an Inheritance context, specifically using interfaces and abstract classes to provide an Abstraction of a certain entity (class). I assumed Abstraction given in this manner would allow developers to extend new objects appropriately according to the "guidelines" outlined by this Abstraction. Here are some posts that lead me in this direction:

I'm not sure if I'm just completely missing the point here, but it's getting pretty confusing because every answer seems to add a slight variation to the mix. I definitely see why both contexts are crucial in Object Oriented Programming, but I really wanted a clear-cut definition of what Abstraction is.

Which brings me to my point: does Abstraction work in multiple contexts? Does Abstraction portray both of these concepts?

  1. Hiding away "unnecessary details" as done through interfaces and abstract classes

    • Providing an abstraction on an class to be created through interfaces and abstract classes. We can provide an interface of IPet which would act as an abstraction of a Dog class. Additionally, maybe providing an Animal base class as an abstract class to provide an additional abstraction?
  2. Abstracting the implementation of a class by exposing it through the class API

    • given a Dog class, we just need to know that it has a feed() function as part of its API, and call that function to feed it without knowing how the feeding is actually done. This provides abstraction on the Dog class and lets us easily interact with the class

One of the links I've included above contains the following quote by Matthew Watson that says:

"The problem is that there are no precise definitions for these concepts, and the words themselves have multiple meanings even within the context of object orientation."

Is it just that Abstraction is so abstract, even the definition is abstract :P? Thanks for any guidance in advance!

Replace string comparison with pattern

I have in my code a nasty(or maybe not nasty?) method that contains multiple (9 to be exact) nr of if-statements. See below example. I'm trying to find a good pattern(perhaps?) to make the code more nice. Maybe 9 if-statements is ok but I see a potential risk that these statements can increase in the future. I've been looking at the strategy-pattern but don't really see it to be a good candidate. What pattern could be a good replacement for multiple if-statements?

if (text.Contains("aaa")) {
   doA();
}

if (text.Contains("bbb")) {
   doB();
}

... an so on.

When creating a function to run only one time, should the redefinition happen before or after the function?

I want a function to only run one time. I found this question here on SO and the highest voted examples redefine the function and then execute the code that is supposed to run once. I'm sure there is a good reason for doing that instead of running the code and then redefining the function but I can't figure out what that would be. My first instinct would be to only redefine the function after the code is run since that seems "safer" because the code would have to have run before being redefined.

Can someone explain why convention seems to be to redefine first?

Implementation of abstract factory in c++ 17

I have seen a lot of implementations of abstract factory pattern in C++. It seems like Alexandrescu's implementation is the most flexible for C++ 98. I'am interesting in the most flexible implementation of this pattern in C++ 17. I want to know what (and why) I should change in implementation since C++ 11, 14, 17.

vendredi 29 décembre 2017

Design for supporting two version of web pages in java page object model

I am working on page object model. Here is the simplified pseudo code for a test

  • Go to home page
  • Navigate to my account page
  • Login
  • Do something
  • Logout
  • Verify something

Right now I have two versions of account page. And I have two classes for it. One for original account page and another new account page. Above mentioned test was written for original account page. What do I do so that I only create new home page (both pages with almost same methods, but with different locators) but can use the existing tests? There will be two version of other pages gradually.

What would be a good design pattern for passing in a type, going through some conditionals, and returning an object

const someFailedAction = (caseIds, growlMessages) => {

    if (caseIds.length > 1) {
        toastr.error(growlMessages[0], errorToastrOptions);
    } else if (isCaseDetailsDisplayed) {
        toastr.error(growlMessages[1], errorToastrOptions);
    } else if (errorParts.fieldIds.length === 0) {
        toastr.error(growlMessages[2], errorToastrOptions);
    } else {
        toastr.error(growlMessages[3], errorToastrOptions);
    }
}

I have a bunch of conditional statements like the one above which are executed on failures of different case actions. Most of the actions have the same if/elseIf structure, but some have an additional elseIf or a subtraction of one or more.

const SomeOtherFailedAction = (caseIds, growlMessages) => {

    if (caseIds.length > 1) {
        toastr.error(growlMessages[0], errorToastrOptions);
    } else if (isCaseDetailsDisplayed) {
        toastr.error(growlMessages[1], errorToastrOptions);
    } else {
        toastr.error(growlMessages[2], errorToastrOptions);
    }

}

I was wondering if there was a good design pattern for which I could just pass in the type and array of messages without having a long, nested, repetitious switch statement.

Process Multiple files by group the files and spanning a thread

I am looking for a suggestion on design approach for processing multiple files(around 100, 500KB file each).

Basically need to update the old ID with new ID and corresponding update the new ID in dependent files(which has a reference of old ID).My thoughts were

  1. Group the files based on dependency and span a new thread to process the files for ID replacement.

  2. Having StreamReader against the original file and a StreamWriter against the destination file. Then, loop over all the rows returned by the StreamReader, use .Replace on each row, and write it to the StreamWriter.

Any better approach to achieve better performance.

thanks AR

Syncing file system changes: Diffing vs replaying file operations

Looking for general input from an architectural point of view.

Problem:

  • I have a virtual file system (think DropBox) in the cloud.
  • I need a logical representation of it on the client.
  • My clients may need to sync up their local representation upon changes.
  • I don't expect the repositories to be too big - there may be bigger ones in some cases though.

Common Solutions:

  • Brute force: Just get the whole model of the file system on every refresh and discard the old one. That's ok for a minimum viable product, but not a solution long-term.
  • Diffing: Compare two representations and find changes. That's the typical approach as far as I can see searching the web. I think it's rather complex to get all the cases though and I didn't see a simple solution to just take over (C# server-side, JavaScript clients), which may be an indicator for this to be non-trivial, too. Happy for inputs/links though!

Alternative solution: replay log

I'm toying with the idea of just keeping a list of commands that represent file operations along with a timestamp. That means that if a client needs to sync up, it just gets the commands since the last sync and executes them on the existing repository, e.g.

  1. Create directory D1 in root
  2. Add file F1 to directory D1
  3. Add directory D2 to directory D1
  4. Move file F1 to directory D2
  5. Delete directory D1

Pros:

  • Greatly reduced complexity
  • Stable
  • Works both ways (offline operations on the client)
  • No need to keep two models and compare them

Cons:

  • Need to keep the replay log
  • An unnoticed syncing bug by cause clients to get out of sync

I'm currently leaning towards the replay log, but would be happy to hear your thoughts about the pattern and potential alternatives. Thanks!

C# Replace "Whole words only" useing RegEx and dictionary

I would like to create code, witch are replacing words contained in one file, using another text file as dictionary (struct.: Key sep.:tab Value).

Current code:

                    var fileDictionary = new Dictionary<string, string>(File.ReadLines(dictionaryPath, Encoding.Default).Select(line => line.Split('    ')).ToDictionary(data => data[0], data => data[1]), StringComparer.InvariantCultureIgnoreCase);//create dictionary based on text file



                    for (int i = 0; i < rowNumber; i++)
                    {
                        var output = fileString[i].ToString();// current row, taked from other file
                        var replaced = Regex.Replace(output, String.Join("|", fileDictionary.Keys.Select(Regex.Escape)), m => fileDictionary[m.Value], RegexOptions.IgnoreCase);
                        var result = replaced.ToString();
                        outputFile += result.ToString();
                        outputFile += "\r\n";
                    }

For now everything works fine, I using RegEx to replace words collected in dictionary, but I have problem with replacing type "whole words only".

Decided to use pattern like @"\bsomeword\b" but when I implement it f.eg.:

                        var replaced = Regex.Replace(output, String.Join("|", String.Format(@"\b{0}\b", fileDictionary.Keys.Select(Regex.Escape))), m => fileDictionary[m.Value], RegexOptions.IgnoreCase);

code doesnt return any results. Final text file, looks like original file. Nothing happens. As I realize, problem is in dictionary key, when I am using pattern I actually change key and new one, does not exist in current dictionary. So if key does not occur, value is not replaced.

Have anybody any suggestions how to fix that? Or maybe somebody know some different way to replace whole words only, using RegEx and dictionary?

jeudi 28 décembre 2017

HTML5 Pattern numbers seperated by commas

I want to be able to put a textbox that has a pattern that allows numbers to be separated by commas, such as in the example below.

4567,4568,4569

Thanks!

Design pattern for executing logic blocks that feeds each other

I have an app that have logic units (each unit is a class and all implements the same interface).

I'm looking for a design pattern that you can build a chain of logic units that each unit's output is the input to the next unit and when finish iterating the units you get the final result.

Is there something that fits this description?

Release a socket back depending on whether they are live or dead in its own pool?

I am using below class to send data to our messaging queue by using socket either in a synchronous way or asynchronous way as shown below. It depends on requirement whether I want to call synchronous or asynchronous method to send data on a socket. Most of the times we will send data through aysnc way but sometimes I may need to send data through sync way.

  • sendAsync - It sends data asynchronously without any timeout. If acknowledgment is not received then it will retry again from the background thread which is started in SendToQueue constructor only.
  • send - It sends data synchronously on a socket. It internally calls doSendAsync method and then sleep for a particular timeout period and if acknowledgment is not received then it removes from cache bucket so that we don't retry again.

So the only difference between those two above methods is - For async case, I need to retry at all cost if acknowledgment is not received but for sync I don't need to retry at all and that's why I am storing more state in a PendingMessage class.

ResponsePoller is a class which receives the acknowledgment for the data that was sent to our messaging queue on a particular socket and then calls handleAckReceived method below to remove the address so that we don't retry after receiving the acknowledgment. If acknowledgment is received then socket is live otherwise it is dead.

public class SendToQueue {
  private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
  private final Cache<Long, PendingMessage> cache = CacheBuilder.newBuilder()
          .maximumSize(1000000)
          .concurrencyLevel(100)
          .build();

  private static class PendingMessage {
    private final long _address;
    private final byte[] _encodedRecords;
    private final Socket _socket;
    private final boolean _retryEnabled;
    private final Object _monitor = new Object();
    private long _sendTimeMillis;
    private volatile boolean _acknowledged;

    public PendingMessage(long address, byte[] encodedRecords, Socket socket, boolean retryEnabled) {
      _address = address;
      _sendTimeMillis = System.currentTimeMillis();
      _encodedRecords = encodedRecords;
      _socket = socket;
      _retryEnabled = retryEnabled;
    }

    public synchronized boolean hasExpired() {
      return System.currentTimeMillis() - _sendTimeMillis > 500L;
    }

    public synchronized void markResent() {
      _sendTimeMillis = System.currentTimeMillis();
    }

    public boolean shouldRetry() {
      return _retryEnabled && !_acknowledged;
    }

    public boolean waitForAck() {
      try {
        synchronized (_monitor) {
          _monitor.wait(500L);
        }
        return _acknowledged;
      } catch (InterruptedException ie) {
        return false;
      }
    }

    public void ackReceived() {
      _acknowledged = true;
      synchronized (_monitor) {
        _monitor.notifyAll();
      }
    }

    public long getAddress() {
      return _address;
    }

    public byte[] getEncodedRecords() {
      return _encodedRecords;
    }

    public Socket getSocket() {
      return _socket;
    }
  }

  private static class Holder {
    private static final SendToQueue INSTANCE = new SendToQueue();
  }

  public static SendToQueue getInstance() {
    return Holder.INSTANCE;
  }

  private void handleRetries() {
    List<PendingMessage> messages = new ArrayList<>(cache.asMap().values());
    for (PendingMessage m : messages) {
      if (m.hasExpired()) {
        if (m.shouldRetry()) {
          m.markResent();
          doSendAsync(m, m.getSocket());
        } else {
          cache.invalidate(m.getAddress());
        }
      }
    }
  }

  private SendToQueue() {
    executorService.submit(new ResponsePoller()); // another thread which receives acknowledgment
                                                  // and then delete entry from the cache
                                                  // accordingly.
    executorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        handleRetries();
      }
    }, 0, 1, TimeUnit.SECONDS);
  }

  public boolean sendAsync(final long address, final byte[] encodedRecords, final Socket socket) {
    PendingMessage m = new PendingMessage(address, encodedRecords, socket, true);
    cache.put(address, m);
    return doSendAsync(m, socket);
  }

  private boolean doSendAsync(final PendingMessage pendingMessage, final Socket socket) {
    ZMsg msg = new ZMsg();
    msg.add(pendingMessage.getEncodedRecords());
    try {
      return msg.send(socket);
    } finally {
      msg.destroy();
    }
  }

  public boolean send(final long address, final byte[] encodedRecords, final Socket socket) {
    PendingMessage m = new PendingMessage(address, encodedRecords, socket, false);
    cache.put(address, m);
    try {
      if (doSendAsync(m, socket)) {
        return m.waitForAck();
      }
      return false;
    } finally {
      cache.invalidate(address);
    }
  }

  // called by acknowledgment thread which is in ResponsePoller class
  public void handleAckReceived(final long address) {
    PendingMessage m = cache.getIfPresent(address);
    if (m != null) {
      m.ackReceived();
      cache.invalidate(address);
    }
  }
}

As I am sending data on a socket and if I get the acknowledgment back for the same data then it means Socket is alive but if data is not acknowledge back then it means socket is dead (but I will keep retrying to send the data). So with my above design (or if there is any better way), how can I figure out whether any socket is dead or live because either acknowledgment was not received or it was received from that socket and basis on that I need to release the socket back into its pool (whether it is alive or dead) by calling below method depending on whether acknowledgment is received or not either for sync or async case.

I also need to configure count that if acknowledgment is not received on a particular socket for x (where x is a number > 0) times then only mark a socket dead. What is the best and efficient way to do this thing?

SocketManager.getInstance().releaseSocket(socket, SocketState.LIVE);
SocketManager.getInstance().releaseSocket(socket, SocketState.DEAD);

Reading a tree from a file in Composite design pattern

C++ composite design pattern, how to read a tree from file and in what way should it be stored? The task is about catalog of items.

What should i select Static class or concrete class?

I need to create a mapper which will map DataTable into an Object of a class(Just set every property into class by DataTable column)

I am thinking below possiblities..

1) Create a Static class and Static method signature like Map(DataTable obj).

2) Create a Concrete class and Static method signature like Map(DataTable obj).

3) Create a Concrete class and Non Static metho signature like Map(DataTable obj).

please suggest what should i do?

What is the need of passing additional arguments to browserify's prelude.js?

I am just checking how browserify creates a bundle code. This is the IIFE that is executed with arguments of the format:

({
    id_one: [function(require, module, exports) {
        // Module Code
    }, {
        dependency_one: id_two,
        dependency_two: id_three
    }],

}, {}, [entryid])

However, I just couldn't understand why do we need to pass these four extra arguments outer, modules, cache, entry to the function that is equivalent to the module code? The signature of the function that it executes is of the format require, module, exports. I tried without this and it works as well.

An example is:

// modules are defined as an array
// [ module function, map of requireuires ]
//
// map of requireuires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the requireuire for previous bundles

(function outer(modules, cache, entry) {
    // Save the require from previous bundle to this closure if any
    var previousRequire = typeof require === "function" && require;

    function newRequire(name, jumped) {
        if (!cache[name]) {
            if (!modules[name]) {
                // If we cannot find the module within our internal map or
                // cache, jump to the current global require ie. the last bundle
                // that was added to the page.
                var currentRequire = typeof require == "function" && require;
                if (!jumped && currentRequire) {
                    return currentRequire(name, true);
                }

                // If there are other bundles on this page the require from the
                // previous one is saved to 'previousRequire'. Repeat this as
                // many times as there are bundles until the module is found or
                // we exhaust the require chain.
                if (previousRequire) {
                    return previousRequire(name, true);
                }
                var err = new Error('Cannot find module \'' + name + '\'');
                err.code = 'MODULE_NOT_FOUND';
                throw err;
            }
            var m = cache[name] = {exports:{}};
            modules[name][0].call(m.exports, function(x){
                var id = modules[name][1][x];
                return newRequire(id ? id : x);
            },m,m.exports,outer,modules,cache,entry);
        }
        return cache[name].exports;
    }
    for(var i=0;i<entry.length;i++) newRequire(entry[i]);

    // Override the current require with this new one
    return newRequire;
})({
    1: [function(require, module, exports) {
        modulea = require("./modulea.js");
        moduleb = require("./moduleb.js");

        logger = function() {
            console.log(modulea + modulea);
        };

        console.log("Main executed.")
    }, {
        "./modulea.js": 2,
        "./moduleb.js": 3
    }],
    2: [function(require, module, exports) {
        module.exports.name = "Module A";

    }, {}],
    3: [function(require, module, exports) {
        module.exports.name = "Module B";


    }, {}]
}, {}, [1]);

C# Chaining with Partial Repository Class

I have classes in my program like

class QueryUtil1{
 getByID(int id){
   //open connection
   //create query
  // map to dataset and return
 }
}
class QueryUtil2{
 getByID(int id){
   //open connection
   //create query
  // map to dataset and return
 }
}

so these methods calls from multiple classes creates multiple round trips to database like hundreds in some cases what I am trying to do is merge all those queries and return it in single dataset bu method chaining like

QueryUtil utill = new QueryUtil()l
Dataset ds = utill
._queryUtil1.getByID(id)
._queryUtil2.getByID(id)
.execute();

whose implementation is

class QueryUtil {
 StringBuilder query = new StringBuilder();
 QueryUtil1 _queryUtil1 = new QueryUtil1();
 QueryUtil2 _queryUtil2 = new QueryUtil2();

 execute(){
  string sql = query.ToString();
  //execute command and return dataset
 }
class QueryUtil1 : QueryUtil{
     QueryUtil getByID(int id){
       query.append("select * from table where id = " + id);
       return this;
     }
    }
}

but the problem is it throws stackoverflowexeption because child class initiates parent class and parent class initiate child class and so on... I want to achieve chaining any idea how to?

mercredi 27 décembre 2017

In what scenario, you will choose Facade pattern and DI?

Please tell the real time scenario of Facade pattern and DI. Can I replace DI with Facade Pattern.

Flyweight design pattern with Swift SceneKit. Object-reuse

I'm building an augmented-reality iPhone application, and it will require a large amount of SceneKit nodes to be rendered. I want to integrate the Flyweight design pattern described in Design Patterns by Gamma, Helm, Johnson, and Vlissides. Also tutorial here Flyweight Design Pattern However, I'm running into issues with the implementation and how Swift handles objects.

TL;DR: Is there a way in Swift where I can add the same SCNNode to a ARSCNView more than once and have it be displayed in different positions?

I have a class called Box which builds SCNBoxs which I want to leverage Flyweight on; the intrinsic state of a Box is the dimensions. The extrinsic state is its color and position.

Box Class

class Box {
    var size:CGFloat
    var position:(Float, Float, Float)
    var color:UIColor
    var node:SCNNode!

    init(color:UIColor){
        self.color = color
        /*Set the following below as default values*/
        self.size = CGFloat(0.05) //Side length
        self.position = (0,0,0)
        self.createBox()
    }

    private func createBox() -> Void {
        /*Creating box and setting its color*/
        self.node = SCNNode(geometry: SCNBox(width: size, height: size, length: size, chamferRadius: 0))
        self.node.geometry?.firstMaterial?.diffuse.contents = self.color
    }

    func draw(sceneView: ARSCNView) -> Void {
        sceneView.scene.rootNode.addChildNode(self.node)
    }
}

I have a factory class which implements the design with a dictionary checking if previous objects of the same color, if so reuse the object, else create a new one.

Factory Class

class BoxFactory{
    var hash:[UIColor:Box] = [UIColor:Box]()
    func getBox(color c:UIColor) -> Box {
        /*Check if box of color c already exists*/
        if(self.hash[c] != nil){
            return self.hash[c]!
        }
        /*Create a new box if it does not*/
        let b:Box = Box(color: c)
        self.hash[c] = b
        return b
    }
}

And some view controller which hold an ARSCNView object to display the boxes.

let factory:BoxFactory = BoxFactory()

/*Create two boxes of same color. One on the left and on the right*/
let leftBox:Box = factory.getBox(color: UIColor.green)
leftBox.position = (-0.1,0,0)
leftBox.draw(sceneView: self.sceneView)

let rightBox:Box = factory.getBox(color: UIColor.green)
rightBox.position = (0.1,0,0)
rightBox.draw(sceneView: self.sceneView)

However, this only produces one green box; the right one. The second getBox() call overrides the first's position Image below. Does anyone have any advice, for the implementation of this pattern, or Swift, that can help achieve this pattern of object reuse?

*Side Note: I don't necessary want to hash the object's position along with its color. Being that I'll have many Boxes of different color and position, it'll defeat the whole idea of reusing the same object.

Only one green box

How to keep track of no of objects created in a java application?

Recently faced this question in an interview:

You have a java application, and it uses a connection object to connect to the different clients. The connection object is of type ClientConnection. I want to know how many live connection objects are present at a particular moment in this application?

Answer given by me:

  1. I will make a static variable connectionCount in ClientConnection class.
  2. Every time ClientConnection constructor is called, I will increment the static variable count by 1.
  3. I will override the finalize() method in ClientConnection and decrements the variable count by 1, every time it is called.

But Interviewer doesn't look satisfied by this answer.
Do we have any other approach for this question?

Advanced Java books

I already know all the basics concerning core programming concepts, exceptions, OOP concepts, etc. I'd say I'm an intermediate developer (working with Java for two years now, and C before that).

I want learn deeply the Java language with more advanced concepts (go deep with threads, lambda expressions, etc) and design patterns.

I'm also interested to learn about how to optimize my Java code in terms of performance and good practices - is there a book for that?

I googled this question and found some blogs and questions, but recommendations seemed very basic (Java core concepts to learn such as conditionals/loops/inheritance) and I'm looking not as much for superficial/basic stuff but more deep/advanced.

Thank you.

How can I nicely propagate changes through persisted data?

If I have a large set of relational (MySQL) tables structured hierarchically, is there a design pattern, good practice, tool/framework, or even way of storing data like graph database that helps me propagate changes through the relation?

For example (a bad one but I hope it get's to the point), say, I modified a table [manager]:

  • that means that I need to update it's descendant tables [officer] and [officer_assistant]
  • that means that I need to update it's ancestor tables [director] and [board_of_directors]
  • also, touching the [officer] table means that I need to update the table [scrum_master]
  • also, touching the [officer_assistant] table means that I need to update the table [scrum_master] but in a slightly different way than the officer

And the complexity keeps growing. For the moment I am handling this within the Java code, and whenever possible I want to avoid MySQL triggers.

regular expression pattern [#[#hello]#] match in javascript

var str1 = "hello hello [#[#hello]#] [#[#hi]#] [#[#welcome]#]"

var arr = textToPost.match(/#^[a-zA-Z0-9]/g)

i want to extract string which matches this pattren [#[# * ]#] .

difference between facade pattern and Dependency Injection with real time example?

could u please tell about the difference between facade pattern and dI. Tell me the adavantage of Facade over DI. Which is best to apply in the project. I have gone through the following link for facade design pattern, well explained. http://ift.tt/2DYsfYZ

based on the above example in the link, I want to know the difference between them, advantages and disadvantages. Thanks a lot

Find a row in a dataframe using regex R?

I have a translation table (trans_df):

rs1065852 rs201377835 rs28371706 rs5030655 rs5030865 rs3892097 rs35742686
1          G           C          G         A         C         C          T
2          G           C          G         A         C         C        del
3          A           C          G         A         C         T          T
4        del         del        del       del       del       del        del
5          G           C          G       del         C         C          T
6          G           C          G         A         C         C          T
7          G           C          G         A         C         C          T
8          A           C          G         A         C         C          T
9          G           C          A         A         C         C          T
10         G           C          G         A         C         C          T
11         G           C          G         A         C         C          T
   rs5030656 rs5030867 rs28371725 rs59421388
1        CTT         T          C          C
2        CTT         T          C          C
3        CTT         T          C          C
4        del       del        del        del
5        CTT         T          C          C
6        CTT         G          C          C
7        del         T          C          C
8        CTT         T          C          C
9        CTT         T          C          C
10       CTT         T          C          T
11       CTT         T          T          C

and input :

rs1065852 rs201377835 rs28371706 rs5030655 rs5030865 rs3892097 rs35742686
1       G|A           C        G|A         A         C       T|C          T
  rs5030656 rs5030867 rs28371725 rs59421388
1       CTT         T        C|T          C

I want to find the input row in the trans_df using regular expression. I have achieved it by position:

Reduce(intersect,lapply(seq(1, ncol(trans_df)), 
                          function(i) {grep(pattern = input[, i], 
                          trans_df[, i])}))

Is there any way to do this where pattern = input? Please advise.

Avoid repetitive try/except in python

I have several functions (f, g, o) that have arg1 as input.

arg1 is positif, mandatory and located in different position:

def f(a, b, arg1):
    print(arg1)

def g(c, arg1):
    print(arg1)

def o(arg1, d, 2):
    print(arg1)

In case arg1 is negatif I raise an exception:

def is_positif(a):
    if a < 0:
        raise ValueError('arg1 should be positif)

To avoid repeat the try/except statements on all functions:

def f(a, b, arg1):
    try:
        is_positif(arg1)
        print(arg1)
    except ValueError as err:
        print(err)

I investigated the idea of creating a decorator.

from functools import wraps

def valid_arg(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            is_positif(kwargs['arg1'])
            func(*args, **kwargs)
        except ValueError as err:
            print(err)
    return wrapper

def is_positif(x):
    if x < 0:
        raise ValueError("arg1 should be positif")

@valid_arg
def f(a, b, arg1):
    print(arg1)

if __name__ == '__main__':
    f(1, 2, arg1=3)

However, this solution force me to use arg1 as a keyword argument (arg1=3) and seems overkilling.

I have noticed a few response in previous post with the usage of the contextmanager.

However, the contextmanager from what I read will re-raise the exception so it does not solve my problem.

Could you please tell me what is the righ approach ?

Regards,

mardi 26 décembre 2017

Fallback vs High Availability

Do we need Fallback when HA is guaranteed?
HA can be guaranteed by different components like Relational DB, Cache; also Availability of services guaranteed by the PaaS Platform etc. Is such scenarios, the consumers of the components still need to have fallback defined?

How can I use android pathPattern in intent filter?

I trying to figure out about simple glob to satisfy my needs but no success.

I want pass "https://mydomain/users/123" but not pass "https://mydomain/users/user_identity/123"

Any of pathPattern I use cannot satisfy my requirement.

val mPatternMatcher = PatternMatcher("http://ift.tt/2DW6Hfy", PatternMatcher.PATTERN_SIMPLE_GLOB)
        Log.e("====", mPatternMatcher.match("http://ift.tt/2pFWSzm").toString())
        Log.e("====", mPatternMatcher.match("http://ift.tt/2DUmZWi").toString())

Any one can help?

what is the most elegant way of returning a lot of std::map<,>::iterator?

I am working on a car fleet program that has a container that contains a lot of cars

std::map<CarKey, Car> _cars;

I need to write a function/class that operate on a subset of the car objects in the _cars

Naively I can just iterate through _cars with a filter function

for(auto& p : _cars){
    //please note: I cannot get things done with one iteration, I have to iterate many times to get things done
    if (isOfInterest(p.second)){
        // do some thing
    }
}

the downside of such a solution is that is I am interested only in 10% of the cars, I will have to waste a lot time iterating

I am trying to find an elegant way to return all the iterators that I am interested

std::vector<std::map<CarKey, Car> :: iterator > getAllIntereted(_cars)

then I can simply iterate through the vector

I am not sure if this is a good approach. Maybe there is some design pattern that can be helpful?

Can anyone give any insights?

Thanks

Java PatternSyntaxException

My problem is: I want to enter a number and my method should remove symbols like "+","/","-","." with the help of regex (pattern & matcher). My method looks like this:

"String eingabe" is the entered number:

String bindestrich = "-";
        String plus = "+";
        String slash = "/";
        String punkt = ".";
        String leer = "";

        Pattern bindestrichP = Pattern.compile(bindestrich);
        Matcher matchBindestrich = bindestrichP.matcher(eingabe);
        eingabe = matchBindestrich.replaceAll(leer);

        Pattern plusP = Pattern.compile(plus);
        Matcher matchPlus = plusP.matcher(eingabe);
        eingabe = matchPlus.replaceAll(leer);

        Pattern slashP = Pattern.compile(slash);
        Matcher matchSlash = slashP.matcher(eingabe);
        eingabe = matchSlash.replaceAll(leer);

        Pattern punktP = Pattern.compile(punkt);
        Matcher matchPunkt = punktP.matcher(eingabe);
        eingabe = matchPunkt.replaceAll(leer);

However it throws a PatternSyntaxException already at the Pattern-making point. What do I do wrong? Is there any simpler method to remove exact these symbols?

What can I call classes that are managing entities?

I have some classes around my domain entities that provide some service over entity to entity and other classes, such as managing association instances (loading and querying), Copying entity, Tracking changes, Serialization, and the like.

I maintain references to instances of these classes in entity. I want to know what kind of pattern match this design and what should I call these classes (service, manager or controller, ...)?

Chain of methods in rails ( call methods by step)

I try to find how to best way implement chain of methods in Ruby( Rails application) like this

class Foo
  attr_accessor :errors
  attr_accessor :shared_params

  def initialize(..)
    ..
  end

  def call 
    check_params
    calc_smthing
    write_in_db
  end

  prviate

  def check_params
    ..
  end

  def calc_smthing
    ..
  end

  def write_in_db
    ..
  end
end

main ideas:

  • if something fail( or not fail but return false) in some step others steps doesnt call, of course I dont want to add multiple ifs to check state and think about how implement it in one place

  • I need to save errors

  • It would be great to find way to share params between methods.

I can write in simple( ugly) way with ifs but I try to find more elegant way or pattern because problem not so specific I think.

Thanks in advance.

lundi 25 décembre 2017

Laravel Repository without adding in the providers

I loved the repository design pattern to keep data abstraction and controller separate. But in Laravel we need to add the repository in the service provider in the config file which is a very bad thing. My question is how we can use repositories without adding in the config file?

Best design pattern for update field by field in different tables?

My problem is that, i have a form which include multiple forms. For instance you can think like there is a person has personal information, education information, work experince etc. All sections have different sql table for example education information is a section and, its include highscooltable, and universitytable. I will write an api with C# language that handle every request from clients side. I found a solution like that;

  1. I will keep all fields names and table names in a dictionary
  2. Client will send to api changed fields names
  3. Check changed fields names are they in my dictionary
  4. If yes add or update the field.

Actually i am not believe in its very good method. Thats why i am writing here. Is there any design pattern or any different way to implement this?

Thank you,

Communication with relational databases (MySQL) on NodeJs. Best practices

I am working on REST API, based on NodeJs.

My app get data from Mysql and return to clients. I try to organize my code wich works with Mysql.

Can I use repository + unit of work patterns?

Is "Patterns of Enterprise Application Architecture" of Martin Fowler still actual for NodeJs development? (can I read this book and use all of them, in depends of situations of course?).

Is this project a goot exemple of how I should do? http://ift.tt/2C50fot

Or maybe exists another patterns for NodeJs development? Could you recomend good sources of information?

dimanche 24 décembre 2017

Factory pattern along with DI using Unity container

I am learning design patterns,Below is my sample code where I have implemented Factory pattern and instance creation I have delegated to Unity container Framework(DI) to build the loosely coupled system. Below is my sample code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;

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

            iPaymentGateway gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.SHIFT4);
            gateway.CreatePaymentGateway();
            gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.WELLSFARGO);
            gateway.CreatePaymentGateway();
            gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.PROTOBASE);
            gateway.CreatePaymentGateway();
            Console.ReadLine();
        }

        enum GateWay
        {
            PROTOBASE = 1,
            SHIFT4 = 2,
            WELLSFARGO = 3
        }

         //Factory class
        class PaymentGatwayFactory
        {
            public static iPaymentGateway NewPaymentGatway(GateWay GateWayType)
            {
                 //Dependency injection using unity container
                var container = new UnityContainer();
                iPaymentGateway result = null;
                switch (GateWayType)
                {
                    case GateWay.SHIFT4:
                        container.RegisterType<iPaymentGateway, SHIFT4Gateway>();
                        result = container.Resolve<SHIFT4Gateway>();
                        break;
                    case GateWay.WELLSFARGO:
                        container.RegisterType<iPaymentGateway, WellsFargoGateway>();
                        result = container.Resolve<WellsFargoGateway>();
                        break;
                    default:
                        container.RegisterType<iPaymentGateway, ProtobaseGateway>();
                        result = container.Resolve<ProtobaseGateway>();
                        break;
                }

                return result;
            }
        }

        class WellsFargoGateway : iPaymentGateway
        {
            public void CreatePaymentGateway()
            {
                Console.WriteLine("Implement Wells Fargo logic");
            }
        }

        class SHIFT4Gateway : iPaymentGateway
        {
            public void CreatePaymentGateway()
            {
                Console.WriteLine("Implement SHIFT4 logic");
            }
        }

        class ProtobaseGateway : iPaymentGateway
        {
            public void CreatePaymentGateway()
            {
                Console.WriteLine("Implement Protobase logic");
            }
        }

        interface iPaymentGateway
        {
            void CreatePaymentGateway();
        }
    }
}

Is this is the right way of implementing Factory pattern and using unity framework?

Create one SQLAlchemy instance per blueprint and call create_all multiple times

My application has a blueprint which is intended to be modular and uses its own database models. I use an app-factory pattern.

Two problems that I face often with such a project structure are:

  • Cyclical imports.
  • The inability to pass around the db object to the blueprints in a clean manner such that they can create their own database models.

To avoid passing the db object around I have now started to create a new database object (db = SQLAlchemy()) within the blueprints itself.

It works! And also avoids some issues with cyclical imports as well since the blueprint now uses its own instance of db. My questions is, what kind of problems will this design lead to? I use gunicorn with a gevent worker.

Here's some sample code to show how my models and factory are structured:

blueprints.status.models.py

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class Status(db.Model):
    __tablename__ = 'states'
    id = db.Column(db.Integer, primary_key=True)
    job_id = db.Column(db.Integer)
    status = db.Column(db.String(120))

models.py

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class Job(db.Model):
    __tablename__ = 'states'
    id = db.Column(db.Integer, primary_key=True)
    state = db.Column(db.String(120)

factory.py

from .blueprints.status.models import db as status_db  # blueprint db
from .blueprints.status.routes import status_handler   # blueprint handler
from .models import db as root_db                      # root db
from flask import Flask

def create_app():
    app = Flask(__name__)

    # Create database resources.
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////path/to/app.db'
    root_db.init_app(app)
    status_db.init_app(app)
    with app.app_context():
        root_db.create_all()
        status_db.create_all()  # <--- What problems will this lead to?

    # Register blueprint routes.
    app.register_blueprint(status_handler, url_prefix="/status")

    return app

Observer pattern for store management application

I am willing to take advantage of the Observer pattern in making a retail store management system. I have made a separate library project that has the classes of Store, Product, Vendor, Cart.

The program should be able to update each vendor account balance when any of his products is added to the cart. The store also must update it's contents , ie the products that are available or those that are now sold out and not show them for the customer. The cart itself must update it's value upon the addition or removal of products from it while the purchase is still not confirmed ( paid ).

The product in turn may be a subject to a price change.

As I see it, using the Observer pattern is in order in this project, isn't it?

Can anyone point me to the starting point from which I can take advantage of the pattern.

According to my understanding of the pattern , hope I understand it correctly, I made the following designation ...

In the Cart Class

public class Cart : ObservableCollection<Product> , IObservable<Product>

.....

In the Store Class

public class Store : ObservableCollection<Product>

.....

In the Vendor Class

public class Vendor : IObserver<Product>

....

And the product class is a standard class with product properties...

..... Is this the prober implementation of the pattern in my case or I am missing something in the structure?

Is there a better way to do the Store management operations than using this pattern?

Thanks in advance.

Multiton design pattern in ES6

I want to create Multiton Design Pattern as part of my user module in my node.js application. And I need good examples of it.

calculating cheapest price using oops concepts

Problem is to calculate cheapest hotel based on given data and input.

Hotel         Weekend_price                         Weekday_price
         regular_cust    priviledge_cust     regular_cust       priviledge_cust

hotel_1      100               90               80                 70


hotel_2      120               100              70                 50


hotel_3      150               120              120                80

Input is regular customer & list of days.

So output is to find out cheapest hotel based on above data. I calculated it with this way.

public class Hotel {

    String name;
    Integer rating;
    List<Price> prices = new ArrayList<Price>();
// getter, setter

public class Price {

    DayType dayType;
    CustomerType customerType;
    Integer price;
// getter, setter

all the above data is preloaded during start of application which is in 
    static List<Hotel> hotels = new ArrayList<Hotel>();


Step is to iterate through each hotel 


        String cheapestHotel = "";
        Integer totalCost = 0;

        for (final Hotel hotel : hotels) {
            Integer hotelCost = 0;
            final List<Date> dates = input.getDates();

            for (final Date date : dates) {
                if (DayType.isWeekend(date) && input.customerType.equals(CustomerType.Regular)) {

                    hotelCost += hotel.getWeekendPriceForRegular();
                } else if (DayType.isWeekend(date) && input.customerType.equals(CustomerType.Priviledge)) {
                    hotelCost += hotel.getWeekendPriceForPriviledge();
                }(!DayType.isWeekend(date) && input.customerType.equals(CustomerType.Regular)) {
                    hotelCost += hotel.getWeekdayPriceForRegular();
                }(DayType.isWeekend(date) && input.customerType.equals(CustomerType.Priviledge)) {
                    hotelCost += hotel.getWeekdayPriceForPriviledge();
                }
            }
            if (hotelCost < totalCost) {
                cheapestHotel = hotel.getName();
                totalCost = hotelCost;
            }
        }

This is working but I feel there could be better way of adding design pattern instead of if else loop but the problem is that price is based on both DayType & customer type so can't think of any better solution of applying oops concepts here.

Can you help with the design for this application?

'which' function in R returns row = 1 while the matched value is in row 2?

I have a translation table where I am using do.call(paste, input) %in% do.call(paste, big_translation_table).

It returns TRUE or FALSE.

Then I am using which function to find the index, but it always returns 1.

Please advise.

Here is a small example:

test1 <- data.frame(a = 1, b=2, c = "r", stringsAsFactors = FALSE)
test2 <- data.frame(a = c(1,2), b=c(2,10), c = c("r","p"), stringsAsFactors = FALSE)

which(do.call(paste, test1) %in% do.call(paste, test2))

returns 1 and it's ok, now let's test with:

test1 <- data.frame(a = 2, b=10, c = "p", stringsAsFactors = FALSE)
which(do.call(paste, test1) %in% do.call(paste, test2))

returns 1 too. I think it should return 2.

Please advise.

C# Is this circular dependency, is a good design (Data Access Layer with Filter Provider)?

Hi I'm learning a lot about design patterns and SOLID Principles, but right now I need to apply that knowledge to an app.

I'm working on a data access layer, it has CRUD methods, but I need to APPLY FILTERS based on certain conditions before running those methods against the database and here is my design, I think I have a circular dependency, and wanted some guidance or help how to keep it SOLID.

Note: Filters need to be dinamically stored and loaded somehow from some storage.

IRepository.cs

public interface IRepository<TEntity>
  where TEntity : IEntity
  {
    void Add(TEntity entity);
    TEntity Get(int id);
    //more actions ....
  }

IFiltersProvider.cs

  public interface IFiltersProvider
  {
    IQueryable<TEntity> ApplyFilters<TEntity>(IQueryable<TEntity> query)
      where TEntity : IEntity;
  }

BaseRepository.cs

  public abstract class BaseRepository<TEntity> : IRepository<TEntity>
   where TEntity : IEntity
  {
    protected IFiltersProvider filtersProvider;

    public void SetFiltersProvider(IFiltersProvider filtersProvider)
    {
      this.filtersProvider = filtersProvider;
    }

    public void Add(TEntity entity)
    {
      // Add to database without filters ....
    }

    public TEntity Get(int id)
    {
      var query = ;//get here a IQueryable;
      filtersProvider?.ApplyFilters(query);

      return query.FirstOrDefault();
    }
  }

Note: I have a SetFiltersProvider in this abstract class because not every repository will apply filters, I think I need a Interface for that.

Everything works if I have a InMemoryFiltersProvider.

Trying to provide filters from Database I believe here I'm breaking SOLID Principles, because I depend from a BaseRepository implementation.

FilterRepository.cs

public class FilterRepository : BaseRepository<Filter>, IRepository<Filter>
  {
  }

DBFiltersProvider.cs

public class DBFiltersProvider: IFiltersProvider
  {
    protected readonly FilterRepository filterRepository;

    public DBFiltersProvider(FilterRepository filterRepository)
    {
      filterRepository.SetFiltersProvider(this);
      this.filterRepository = filterRepository;
    }

    public IQueryable<TEntity> ApplyFilters<TEntity>(IQueryable<TEntity> query)
      where TEntity : IEntity
    {
      var filters = filterRepository.GetFiltersByEntity<TEntity>();

      foreach (var filter in filters)
      {
        // logic to apply filter to query
      }

      return query;
    }
  }

Even when I'm working with interfaces I don't know if the Design it's clean, or circular dependecy problem.

Thanks so much.

send string parameter to regular expression

I have k model class that have a property with regular expression and mobile number pattern.

[Required(ErrorMessageResourceType = pattern, ErrorMessageResourceName = "PhoneNumberRequired")]
    [RegularExpression(new Delta.Common.Utility.Regex().pattern, ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "PhoneNumberNotRegular")]
    public string TelNumber { get; set; }

I have a Regex class that have a string property contains phone number pattern(the pattern in RegularExpression).but RegularExpression doesn't accept the "pattern". How can define a pattern and use it everywhere I want?

if (a) { lock (b) { if (a) { ... } } } - any sense in this?

In my multi-threading paranoia I came to the following pattern:

if (c > iCycle)
{
    lock (loadStatusLock)
    {
        if (c > iCycle)
        {
            c = 0;
            p = i.GetRatio(l);
            output.AppendLine("Done: " + p.ToString("P2"));
        }
    }
}

The reasoning behind: The outer if is there so I don't lose performance with lock when the criterion is not met anyway. The inner if is there to prevent other threads that might be waiting there, inside the outer if while the first thread done the inner code.

My question is: does this makes any sense?

Is the reasoning right or I got the mechanics of this wrong. The code above is just example, I started to use this pattern for many situations (I mean: don't look at the particular code, but rather pattern of the nested if/lock/ifs).

Usually I would use lock/if approach as the safest - but then I read so many performance warnings about excessive locking - and, not this code example but other procedure, I have to run about 9 million times so the performance issue comes forward. Later I used if/lock pattern but it is messy because I was getting (or at least I tripped that) threads inside the if scope, waiting for lock and then things gone wild.

What do you guys say on this?

Thanks.

samedi 23 décembre 2017

what is the difference between Task based asynchronous pattern and Event based asynchronous pattern?

Both the patterns seem similar to me. In both the patterns, a persistence mechanism is involved which stores the events in case of Event-based asynchronous pattern and tasks in case of Task-Based asynchronous pattern. Secondly, both the patterns involve a manager which keeps track of what is happening with each event or tasks. I couldn't find any differences between the two. Help explain.

What should one pass to sys.exit

I'm not sure if this is an appropriate question for stack overflow... If not please guide me in the right direction.

My question is this:
If a programe expects a user to press ctrl-c to close/interrupt said program and return the user to there shell and the programe does this by handling the KeyboardInterupt by calling sys.exit(code) what should code be. I think said program should call sys.exit(0) because it was antisapatin the user of said programme to eventually mash ctrl-c to close the programe, not because of it hanging or crashing but because its know longer needed.

How can I represent key with list of values for each environment type in an Enum?

I have two environment PROD and STAGING. In prod environment we have three datacenters ABC, DEF and PQR and staging has one datacenter CORP. Each datacenter has few machines and I have constant defined for them as shown below:

// NOTE: I can have more machines in each dc in future
public static final ImmutableList<String> ABC_SERVERS = ImmutableList.of("tcp://machineA:8081", "tcp://machineA:8082");
public static final ImmutableList<String> DEF_SERVERS = ImmutableList.of("tcp://machineB:8081", "tcp://machineB:8082");
public static final ImmutableList<String> PQR_SERVERS = ImmutableList.of("tcp://machineC:8081", "tcp://machineC:8082");

public static final ImmutableList<String> STAGING_SERVERS = ImmutableList.of("tcp://machineJ:8087","tcp://machineJ:8088");

Now I have another constant defined in the same class which groups by DC to List of machines for each environment type.

public static final ImmutableMap<Datacenter, ImmutableList<String>> PROD_SERVERS_BY_DC =
  ImmutableMap.<Datacenter, ImmutableList<String>>builder()
      .put(Datacenter.ABC, ABC_SERVERS).put(Datacenter.DEF, DEF_SERVERS)
      .put(Datacenter.PQR, PQR_SERVERS).build();

public static final ImmutableMap<Datacenter, ImmutableList<String>> STAGING_SERVERS_BY_DC =
  ImmutableMap.<Datacenter, ImmutableList<String>>builder()
      .put(Datacenter.CORP, STAGING_SERVERS).build();

Now in some other class, basis on what environment I am in (Utils.isProd()), I get either PROD_SERVERS_BY_DC or STAGING_SERVERS_BY_DC.

Map<Datacenter, ImmutableList<String>> machinesByDC = Utils.isProd() ? Utils.PROD_SERVERS_BY_DC : Utils.STAGING_SERVERS_BY_DC;

Now I think this can be represented in much better way in some sort of Enum instead of having constants defined like I have above but I am not able to figure out how can I do that? I started off with this but got confuse on how can I have single key for each DC and then multiple values as List of machines for that DC and then I need to group them by environment as well.

// got confuse on how can I make key (DC) and list of values (machines) for each environment type.
public enum DCoMachines {
  abc(tcp://machineA:8081", "tcp://machineA:8082"), 

  private final String machines;


}

regex to match whatever between

Please, i need some help to create the right regex

<script type="text/javascript">Decode("2%65%66%_WHATEVER_8%74%74")</script>

I want to detect whatever between Decode(" ") to give me this output 2%65%66%_WHATEVER_8%74%74

I tried a lot, but nothing work correctly to give me the exact output that i want.

Alternatives to Model-View-Controller Pattern

Almost everyone talks about MVC(Model-View-Controller Pattern) when it comes to application design, and it is accepted as best solution available.

But what are the alternatives to MVC to actually do a comparative study?

vendredi 22 décembre 2017

Pattern stop service

I have service that process files all the day, and I catch every exception (log it) in order to do not stop the service and just skip this file. But I would like to stop the service if there are 10 errors occured in a row. I don't want just have an variable that increment when errors occured and set to zero when everything was success because I have a lot of catches and places where I have to set the variable to zero. (see code example)

I've heard that there is exist pattern on how to stop my service in case of several exception occured. But I don't know details.

Question: how would you handle this case?

E.g.:

try 
{
  switch(switchVariable) 
    {
      case "1":
        Method1();
        Method2();
        Method3();
        //If we are here than everything OK.
        break;
      case "2":
        Method1();
        Method2();
        Method3();
        //If we are here than everything OK.
        break;
      ...
}
catch(SpecificException1 ex)
{
  DoSomething1();
}
catch(SpecificException2 ex)
{
  DoSomething2();
}
catch(SpecificException3 ex)
{
  DoSomething3();
}
catch(Exception ex)
{
}

Which approach is recommended for common layout in angular js

My angular application is very large. I have many screens.It has similar functionalities in almost all screens.so i decided to write a framework so that all the screen can make use of this framework to avoid repetition of code.

As I am using ui router i thought to create a parent state which is the base and it is inherited by child.so parent controller will have all the common code and actions.

Is this approach correct?

Java design pattern - How to apply offers on product and shopping cart

I am working on a shopping cart application which will output price of cart. I have 3 classes for this Cart, Purchase, Product

public class Product {

    private int id;
    private String name;
    private double price;
    Offer offer;
// getter setter

    public double getPrice(int quantity) {
        return offer.getPrice....
    }

}

public class Purchase {

    Product product;
    int quantity;
// getter setter

    public double getPrice() {
        return product.getPrice(quantity);
    }

}

public class Cart {

    List<Purchase> purchase = new ArrayList<Purchase>();
    Offer offer;
    Integer loyalityPoints;
//getter setter

    public double getTotal(){
        double total = 0;
        for (Purchase purchase : purchase) {
            total += purchase.getPrice();
        }

        double finalPrice = offer.getPrice(total,....;
        return finalPrice;
    }


}

As shown above individual product can have offer and cart can also have offer.

Initially I thought of having offer factory. OfferPrice can be abstract class & its child could be buyonegetoneprice, buytwogetoneprice, 50precentoffprice but then input for buyonegetoneprice will be qunatity and price and input for 50precentoffprice is only price.

This means 2 different method but implementor of OfferPrice is concerned with only one implementation.

Also how could offer on cart look like? offer on cart can be based on customer loyalityPoints or 50percentoff or something else.

How to design these offers for cart and individual product in a way that could be extensible?

Application - design pattern usage

I work on application which task is to create customized car. I got real data of cars parts etc saved in database. In every scene car will got, model, engine, wheel etc and price of it will be updated. At the end i need full info about car parts so I need to add every part in next scenes.

And now the question is which design pattern should I use.

Builder or decorator? Maybe both?

Default Value for Hystrix fallback

What can be possible fallback (failover) option(s) for a microservice? How can we determine a sensible default when the microservice itself consumes some downstream system API(s)? For Read-Only operations, providing the last response for same request, can be considered? What should be fallback value for a new request?

Angular Modules vs Modular Website Design

Angular is a framework for building Modular client applications. Does those Angular modules has anything in common with modules used in Modular Website design (which I get from the designer).

I mean, when I'm getting the modular website design (created by an designer), may I build an Angular modules according to the modules from the website design? Or, I need to take a step back and to design my own Angular modules according to the website design?

I'm currently working as an web developer. But,from time to time, before starting the development, I also have to create an website mockup design. So, the question is, do I have to learn Modular Website design concepts to ease on myself afterwards while implementing the designing an Angular framework.

Make a simple mail box using design pattern in Android Studio

I want to code a very simple mail box using design patterns.In that box :

-One user can send a mail to more than one user

-User can see his received messages

I have user class but i am not sure what kind of design pattern i should use. Could you give me any advice or is there any specific structure for it in Android Studio?

minimize the code duplication in a class?

I am using below class to send data to our messaging queue by using socket either in a synchronous way or asynchronous way as shown below.

As of now I am duplicating lot of code in my below class. I have 5 method below which is use to send data either synchronously or asynchronously and I believe there might be better way to rewrite those method.

public class SendRecord {
  private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
  private final Cache<Long, PendingMessage> cache =
      CacheBuilder
          .newBuilder()
          .maximumSize(2000000)
          .concurrencyLevel(100).build();

  private static class Holder {
    private static final SendRecord INSTANCE = new SendRecord();
  }

  public static SendRecord getInstance() {
    return Holder.INSTANCE;
  }

  private SendRecord() {
    executorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        handleRetry();
      }
    }, 0, 1, TimeUnit.SECONDS);
  }  

  private void handleRetry() {
    List<PendingMessage> messages = new ArrayList<>(cache.asMap().values());
    for (PendingMessage message : messages) {
      if (message.hasExpired()) {
        if (message.shouldRetry()) {
          message.markResent();
          doSendAsync(message);
        } else {
          cache.invalidate(message.getAddress());
        }
      }
    }
  }

  // called by multiple threads concurrently
  public boolean sendAsync(final long address, final byte[] encodedRecords) {
    PendingMessage m = new PendingMessage(address, encodedRecords, true);
    cache.put(address, m);
    return doSendAsync(m);
  }

  // called by above method and also by handleRetry method
  private boolean doSendAsync(final PendingMessage pendingMessage) {
    Optional<SocketHolder> liveSocket = SocketManager.getInstance().getNextSocket();
    ZMsg msg = new ZMsg();
    msg.add(pendingMessage.getEncodedRecords());
    try {
      // this returns instantly
      return msg.send(liveSocket.get().getSocket());
    } finally {
      msg.destroy();
    }
  }

  // called by send method below
  private boolean doSendAsync(final PendingMessage pendingMessage, final Socket socket) {
    ZMsg msg = new ZMsg();
    msg.add(pendingMessage.getEncodedRecords());
    try {
      // this returns instantly
      return msg.send(socket);
    } finally {
      msg.destroy();
    }
  }

  // called by multiple threads to send data synchronously without passing socket
  public boolean send(final long address, final byte[] encodedRecords) {
    PendingMessage m = new PendingMessage(address, encodedRecords, false);
    cache.put(address, m);
    try {
      if (doSendAsync(m)) {
        return m.waitForAck();
      }
      return false;
    } finally {
      cache.invalidate(address);
    }
  }

  // called by a threads to send data synchronously but with socket as the parameter
  public boolean send(final long address, final byte[] encodedRecords, final Socket socket) {
    PendingMessage m = new PendingMessage(address, encodedRecords, false);
    cache.put(address, m);
    try {
      if (doSendAsync(m, socket)) {
        return m.waitForAck();
      }
      return false;
    } finally {
      cache.invalidate(address);
    }
  }

  public void handleAckReceived(final long address) {
    PendingMessage record = cache.getIfPresent(address);
    if (record != null) {
      record.ackReceived();
      cache.invalidate(address);
    }
  }
}

Is there any better way to rewrite those above methods?

Advantage of factory method pattern

From wiki,

The Factory Method design pattern solves problems like:

  1. How can an object be created so that subclasses can redefine which class to instantiate?

  2. How can a class defer instantiation to subclasses?

For example, MazeGame provides the instantiation capability to subclass like MagicMazeGame.

enter image description here

where,

public abstract class MazeGame {
    private final List<Room> rooms = new ArrayList<>();

    public MazeGame() {
        Room room1 = makeRoom();
        Room room2 = makeRoom();
        room1.connect(room2);
        rooms.add(room1);
        rooms.add(room2);
    }

    abstract protected Room makeRoom();
}


Read answer.

Of course, this is a creational pattern, so solution should be around simplifying instantiation.

My question is,

What is the advantage of factory method pattern, that recommends a template method(public MazeGame(){..}) and defer instantiation to subclass MagicMazeGame or OrdinaryMazeGame?

Is it to abstract the intricacies of constructor details? in every class like MagicMazeGame or OrdinaryMazeGame

Design pattern to add special handling for external lib class

I'm using Foo class from external library. Foo contains several methods and all of them return FooResult enum.

I need to do two things:

  • provide mock implementation of Foo
  • add special handling (some logging, alert via mail) depends on FooResult returned from each Foo method
  • be able to easly switch between mock and real implementation

Foo do not extends any interface that I can use already to provide mock implementation. My current implementation provide solution for point 1 and 3 but I find it pretty ugly. What I have done is: I have extended Foo like FooMock extends Foo and @Override each method, then I can just use Foo anywhere and switch implementation by providing different bean (using SpringBoot and ConditionalOnProperty). But I'm missing a special handling for both implementations.

I could just add some kind of handler for each method where I'm using Foo but this would be ugly as hell and break the DRY rule.

So I'm looking for some pretty design pattern to solve this problem. I thought about proxy - however in proxy Foo should implement the same interface as FooProxy right? Any other ideas?

My current implementation:

Foo class:

public class Foo {
    //fields
    //constructor
    FooResult methodA(){
        //impl
    }

    FooResult methodB(){
        //impl
    }
}

FooMock class:

public class FooMock extends Foo {
    //fields
    //constructor
    @Override
    FooResult methodA(){
        //mock impl
    }
    @Override
    FooResult methodB(){
        //mock impl
    }
}

ClassWhereImUsingFoo class:

public class ClassWhereImUsingFoo{

     private Foo foo;

     //other fields
     @Autowired
     public ClassWhereImUsingFoo(Foo foo){
         this.foo = foo;
     }

     public void sampleMethodUsingFoo(){
         FooResult res = foo.methodA();
         //special handling
         if(res == A){
               //send some alert
         } else if (res == B) {
               //do logging
         } else {
               //do something else
         }
     } 

     //other methods using foo
 }

Whats best practice for loading keys in a Go web app?

I usually worry about memory corruption with leaving my public and private keys in memory for access throughout my applications. I'm very new to Go and I'm wondering what the best practice is for making these keys available.

Is Go safe enough that I should be able to store these in memory, no problem. Or should I only keep my public key in memory for validation and load my private key every time I need to sign a token?

jeudi 21 décembre 2017

Regex Detect Double Space

I am trying to get a regex that will detect if there is a double space in a string. But if it does detect a double space it will return as false. So essentially anything else in the string is valid except for two spaces side by side. In the examples below the underscores (_) are spaces.

'Hello_World' ==> Valid

'Hello__World' ==> Invalid

'Hello___World' ==> Invalid

'1_2_3_4_5' ===> Valid

'1_2_3__4_5' ==> Invalid

This is my current regex

/^([^/s/s]*)$/

Clean for loop for matching elements

I find that a lot of code I write in general is following a pattern of "loop through this container and do X to elements that match some criteria".

which often looks like this:

std::vector<int> theList(10);
std::iota(theList.begin(), theList.end(), 0);

for (auto i : theList)
{
    if ((i % 2) == 0)
    {
        //Do something with i
    }
}

I don't like the if statements in these cases - they're ugly and detract from what is really happening in the logic of the loop.

What I'd like is a better way of doing this so the heart of the problem is expressed nicely.

My best attempt so far isn't all that nice:

std::vector<int> theList(10);
std::iota(theList.begin(), theList.end(), 0);

auto criteria = [](const int& i) -> bool { return (i % 2) == 0; };

for (auto it = std::find_if(theList.begin(), theList.end(), criteria);
     it != theList.end();
     it = std::find_if(++it, theList.end(), criteria)
     )
{
    std::cout << *it << ", ";
}

It feels like this pattern should make its way in to std::algorithm in a cleaner way.

Is there a better way of doing this?

Common or Core where put my file?

I have been reading this post Common vs Core - difference

But I can not understand, what is understood as a conceptually central code?

Really, what should I put in Core and what in common?

I have a file js as a library with some functions, example of my archive

const getType = v =>
      v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
const arrayMin = arr => Math.min(...arr);

Where should put my file, Common or Core and why?

What is the difference between Service and Repository pattern?

So far I saw some projects using AspNet WebApi and MVC that use this patterns but I can't understand the difference. They look and do the same, they encapsulate all this data and abstract it so the controllers are just responsible to call this services or repository classes. My question is what is the difference? When to use one or other or both?

Java: Bank account transatcion limit -> How to represent that there is no limit for some accounts?

I have a quick question about representing single transaction limits for bank accounts. I have different types of bank accounts where each one has a certain single transaction limit. However, some of these account types have no transaction limit. I could come up with a pretty simple solution which just uses a constant to indicate that (see example below).

      private static final double NO_TRANSACTION_LIMIT = -1;  
      public enum BankAccountType {
                GIRO_MINOR(0, 20, "Minor Account"),
                GIRO_STUDENT(0, 200, "Student Account"),
                GIRO_NORMAL(-2000, 4000, "Normal Account"),
                SAVING(0, NO_TRANSACTION_LIMIT, "Saving Account");
                // ...
                private double transactionLimit;
                // ...
                public boolean hasTransactionLimit() {
                    return transactionLimit == NO_TRANSACTION_LIMIT;
                }
}

After some thinking, I thought there must be a better solution to that problem. Because if for some reason the method hasTransactionLimit() is not checked before a transaction limit, this might cause unwanted behavior.
So my question: what is a good strategy to implement behavior like that. Somehow I thought of the Null-Object pattern, but I am pretty unsure.

Thanks!

Which Design Pattern I need to Use Java Application

Currently I have 3 classes in which most of the variables are same. All the variables have getter and setter. I need to create the object of the class based on the datatype variable Year provided and pass that object in the more than ten methods. Lets Take a Example.

We have three Classes ClassA,ClassB,ClassC. If we pass the year 2017 then i need the object of ClassA. If we pass the year 2016 then i need the object of ClassB and for all other year we need the object of ClassC.

Then after we need to pass that object in the all 10 Methods. Let take an exmaple of 2 methods.

public void method1(int a, int b, object of classA/B/C).

public void method2(int a, int b, object of classA/B/C).

Both the methods working on the object and setting some variable in object.

But one problem is that i don't want to extend class or implement interface in the ClassA,ClassB,ClassC.

Please let me know the Design Pattern that perfect for my requirement.

Thanks in advance.

Regex character repeats n or more times in line with grep

I need to find the regex expression to find a character that repeats 4 or more times with grep.

I know that the expression is {n,}, so if I need to find lines, for example, when the character "g" repeats 4 or more times, in theory with grep man page is:

grep "g{4,}" textsamplefile

But doesn't work. Any help?

mercredi 20 décembre 2017

Microservice architecture - carry message through services when order doesn't matter

Tl;dr: "How can I push a message through a bunch of asynchronous, unordered microservices and know when that message has made it through each of them?"

I'm struggling to find the right messaging system/protocol for a specific microservices architecture. This isn't a "which is best" question, but a question about what my options are for a design pattern/protocol.

Diagram

  • I have a message on the beginning queue. Let's say a RabbitMQ message with serialized JSON
  • I need that message to go through an arbitrary number of microservices
  • Each of those microservices are long running, must be independent, and may be implemented in a variety of languages
  • The order of services the message goes through does not matter. In fact, it should not be synchronous.
  • Each service can append data to the original message, but that data is ignored by the other services. There should be no merge conflicts (each service writes a unique key). No service will change or destroy data.
  • Once all the services have had their turn, the message should be published to a second RabbitMQ queue with the original data and the new data.
  • The microservices will have no other side-effects. If this were all in one monolithic application (and in the same language), functional programming would be perfect.

So, the question is, what is an appropriate way to manage that message through the various services? I don't want to have to do one at a time, and the order isn't important. But, if that's the case, how can the system know when all the services have had their whack and the final message can be written onto the ending queue (to have the next batch of services have their go).

The only, semi-elegant solution I could come up with was

  1. to have the first service that encounters a message write that message to common storage (say mongodb)
  2. Have each service do its thing, mark that it has completed for that message, and then check to see if all the services have had their turn
  3. If so, that last service would publish the message

But that still requires each service to be aware of all the other services and requires each service to leave its mark. Neither of those is desired.

I am open to a "Shepherd" service of some kind.

I would appreciate any options that I have missed, and am willing to concede that their may be a better, fundamental design.

Thank you.

REST API that calls another REST API

Is it proper programming practice/ software design to have a REST API call another REST API? If not what would be the recommended way of handling this scenario?

what pattern or process to notify multiple systems about changes in another system

Imagine a system X with an http api with a lot of data from a (mysql) database. Imagine multiple systems being dependent on this data but doing very different tasks. Some work on one data-set others work on a huge bunch of data-sets. The data changes to an unknown number of sets in system X do not have a periodic rhythm. There can be a large number of changes in a very short time.

The other systems must somehow be aware of those data changes and react accordingly. What pattern or process is advisable to keep bottlenecks in all system at the lowest level. So that you prevent that either system X won't be able to handle to notify all other systems or handle all other systems trying to fetch changes. And prevent other systems to slow down because they need to fetch large datasets or wait for system X being overloaded.

Also ideally all systems should not need to know about the other systems. Especially system X shouldn't need to implement specific notification methods for each system.

Would the observer pattern be applicable in this situation?

do java enums are singleton?

do java enums are singleton?

for example :

public enum State {

ACTIVE(0),
PENDING(1),
DELETED(2),
}


State s = State.ACTIVE;
State s2 = State.PENDING;
State s3 = State.PENDING;

is java create new instances every time we use State.FOO ??

What is Memoization exactly?

Could memoization be considered as a design pattern or is simply a method for caching?

http://ift.tt/28MPV5P

Design patterns - abstract factory and composite

i would like (and i must) to implement bank transfer as abstract factory, but i don't know what component should be in transfer. I know that there must be a recipient there, but i have no idea for other components. What should i put there?

Also i want implement a group of (or one) transfers as composite but i must have business reason why i must use it instead of list of transfers. Any idea?

Implementation of my composite: enter image description here

IoC + Layered Architecture + static class

If application uses inversion of control and its structure is:

  • Controllers
  • Core
  • Services

Controllers can reference only Core (Interfaces) and Services contain classes that implement those Interfaces.

When I want to create a new service that is static I am not sure how to call that service in my controller. Interfaces can't be static. Is there some design pattern that would fit my needs?

mardi 19 décembre 2017

module pattern angularjs 1.5 not registering the components

Am trying to use modulePattern in angularjs appication. (1.5) but had to do the 2nd approach as per the code given below to make it work. seems I can't get the component s properly isolated. What Am I missing here?

my index.js entry point to the app

import registerFooterTemplate from './footerBar/footerBar';

const app = angular.module('app', [uirouter])

registerFooterTemplate(app);

MY COMPONENT footerBar.js

import footerTemplate from './footer.html';

// ********** TRYING TO USE MODULE PATTERN HERE **************
// -- This doesn't work---------------
// const mod = angular.module('budgetTracker.footerBar', [

// ]);

// mod.component('footerBar',{
//   template: footerTemplate,
//   bindings: {},
//   controllerAs: 'vm',
//   controller: function($state) {}
// });

// export default mod.name;

// **************************************************************


// THIS Works -----
export default ngModule => {
  ngModule.component('footerBar', {
    template: footerTemplate,
    controllerAs: 'vm',
    controller: function($state) {}
  });
}