samedi 24 décembre 2016

Rails pattern for destroying relationship between two ActiveRecord objects

Say I have two models, A and B, where each has a has_and_belongs_to_many relationship with the other. That is, some A objects and B objects are "connected".

What would be the proper way to offer a route to destroy this relationship? It doesn't really make sense to be a destroy action on A or B's controller since we aren't destroying A or B. Is there some sort of standard way to do this?

Thanks :)

Angular good design pattern for implementing utility functions

I searched for a lot of design patterns, but found nothing on how to implement functions that are going to be used both in some controllers and in html markup. I really want to escape copy-pasting functionality, so here goes the problem.

I have some items stored in localStorage as an Array of entitites, each of which has a price, quantity and discount. Call that array a cart of items. In a certain page I need to interpolate the sum of the prices as an "overall price". That is the 'cart displaying page', which is basically a list of items from the cart. On the other hand, I have an 'order page' with a form, in which the overall price should also be shown. Say this pages are manipulated with two different controllers: OrderController and CartController, in both of which I have a function called calculatePrice, which returns the overall sum, which is then interpolated inside the html in both order.html and cart.html.

So it happens I already did some copy-pasting. And if (which is possible in the nearest future) I have another controller/view which needs this function, I'll end up copy-pasting again.

My thoughts on this:

1) Create a $rootScope function calculatePrice and just use it as is, both inside controllers and the view. Undesired, don't want to insert too much imperative code inside the 'run' cycle of my app

2) Create a service for utility functions, inject it inside the controllers and only declarative style like '$scope.someFunction = service.someFunction'

3) Create a service, inject it inside the app.run function and connect it to rootScope

But I don't think any of this is right. I want to find the most possible clean solution.

Whats a good design pattern for class that wraps shader parameter values

I am trying to design a class that would wrap shader parameter in such way that it would enable the user to easily set and get its value without a need to write a tone of validation code outside of this class implementation.

The problem is that obviously the shader parameter values can be of different types, and weather I use templates or method overloading it results in a lot of messy code that if one was to use this class it would probably not be a very pleasant experience.

Is there some clever design pattern that once implemented would render the usage of said class to be more straight forward ? I wouldn't mind if the mechanism was more complex as long as its implementation is not exposed to the user of this class.

Also just to be more clear, this shader parameter class is somewhat abstract in that its purpose is only to store the parameter for easier editing and handling across my code base. It does not interact or have any knowledge about the actual shader.

vendredi 23 décembre 2016

User roles in Java

I am building POS system. The think is that I don't know what roles are going to be with what functionality. Here is what I have till now:

  • I imagined that I have one main class for javafx primary stage, scene and tabpane. Also, there is each class which extends Tab class for tabPane, and all needed code for that functionality. So each tab is separate.
  • On other hand. There is User class which is abstract with basic attributes and abstract method tasks(), and in each concrete user role ( Administrator ) class which extends this abstract class implement this method. In tasks() method I would add in List all tabs class which are needed for that user role.

I want to know if this method for users role is good or bad. Acctualy I am not satisfied. The reason is open-closed OOP principle. I am not sure which users role are going to be, so I want to make it dynamic.

  • Now, what I have in mind, is that I have only one user for start, and that is Administrator. Then, he and only he can make other user roles and save to database. User role tabs he need, administrator would add while creating user role. This way, you can return and add some new functionality to user role. There is no need to go back to code, and adding new to tasks() method.

My concerne is how to implement this. What should I put in database for tasks, should I put Strings and then in some concrete class to add tasks based on string ( With lots of if statement ), or should I serialize arraylist of tasks and then save to database?

Count number of occurrences in file. conditional pattern matching

Sorry if the title doesn't make it clear.

I have a file to be read every 15 mins and find a particular pattern in it (e.g. timeout). File does not have any fixed update frequency.

Outcome expected:- 1. if pattern is found 3 times in 15 mins, run command1. 2. if pattern is found 5 times in 15 mins, run command2.

File to be read from last read position for each check.

Thanks, GRV

How do I call a function to run in a graph window in a specific pattern?

I have a function with objects that has to run at specific points in the graph window.

Each line represents the function (100x100) in what it is supposed to be a 500x500 window.

-----
 ---
  -
 ---
-----

I know how to make it run like this:

-----
-----
-----
-----
-----

by using nested loops.

def AssortmentOfObjects(size):
    win =GraphWin("Object assortment", size,size)
    ypoint = 0
    for y in range(5):
        xpoint = 0
        for x in range(5):
            Objects(win, xpoint, ypoint)
            xpoint = xpoint + 100
        ypoint = ypoint + 100

Apparently you can use if statements to make them run in a tessellation.
I just have no idea how.

Thank you for any help! Much appreciated.

How to validate each process object from its own validator?

I have two process and for each process, I will get different Record object and I need to validate those Record object. This means I cannot use single validator as I have to validate different fields for both the process.

  • For processA, I am using ValidatorA class to validate its Record object.
  • For processB, I am using ValidatorB class to validate its Record object.

If they are valid, then I will move forward otherwise I won't move forward. Below is my process code both for A and B.

public class ProcessConsumer implements Runnable {
  private static final Logger logger = Logger.getInstance(ProcessConsumer.class);
  private final String processName;
  private final Validator validator;
  private final RecordProcessor<byte[], byte[]> process;

  public ProcessConsumer(String processName, Validator validator) {
    this.processName = processName;
    this.validator = validator;
    this.process = new RecordProcessor<>();
  }

  @Override
  public void run() {
    try {
      process.subscribe(getTopicsBasedOnProcessName(processName));
      ....

      while (true) {
        ConsumerRecords<byte[], byte[]> crs = process.poll(2000);
        for (ConsumerRecord<byte[], byte[]> cr : crs) {
          // record object will be different for my both the processes.
          Record record = decoder.decode(cr.value());
          Optional<DataHolder> validatedHolder = validator.getDataHolder(processName, record);
          if (!validatedHolder.isPresent()) {
            logger.logError("records dropped. payload= ", record);
            continue;
          }
          // send validatedHolder to processor class
          Processor.getInstance().execute(validatedHolder);
        }
      }
    } catch (Exception ex) {
      logger.logError("error= ", ExceptionUtils.getStackTrace(ex));
    }
  }
}

Below is my ValidatorA class in which I am validating few fields on record object and if it is valid, then I am returning DataHolder.

public class ValidatorA extends Validator {
  private static final Logger logger = Logger.getInstance(ValidatorA.class);

  @Override
  public static Optional<DataHolder> getDataHolder(String processName, Record record) {
    Optional<DataHolder> dataHolder = Optional.absent();
    if (isValid(processName, record))
      dataHolder = Optional.of(buildDataHolder(processName, record));
    return dataHolder;
  }

  private DataHolder isValid(String processName, Record record) {
    return isValidClientIdDeviceId(processName, record) && isValidPayId(processName, record)
        && isValidHolder(processName, record)
  }  

  private DataHolder buildDataHolder(String processName, Record record) {
    Map<String, String> holder = (Map<String, String>) DataUtils.extract(record, "holder");
    String deviceId = (String) DataUtils.extract(record, "deviceId");
    Integer payId = (Integer) DataUtils.extract(record, "payId");
    String clientId = (String) DataUtils.extract(record, "clientId");

    // add mandatory fields in the holder map after getting other fields
    holder.put("isClientId", (clientId == null) ? "false" : "true");
    holder.put("isDeviceId", (clientId == null) ? "true" : "false");
    holder.put("abc", (clientId == null) ? deviceId : clientId);

    return new DataHolder.Builder(record).setClientId(clientId).setDeviceId(deviceId)
        .setPayId(String.valueOf(payId)).setHolder(holder).build();
  }

  private boolean isValidHolder(String processName, Record record) {
    Map<String, String> holder = (Map<String, String>) DataUtils.extract(record, "holder");
    if (MapUtils.isEmpty(holder)) {
      logger.logError("invalid holder is coming.");
      return false;
    }
    return true;
  }

  private boolean isValidpayId(String processName, Record record) {
    Integer payId = (Integer) DataUtils.extract(record, "payId");
    if (payId == null) {
      logger.logError("invalid payId is coming.");
      return false;
    }
    return true;
  }

  private boolean isValidClientIdDeviceId(String processName, Record record) {
    String deviceId = (String) DataUtils.extract(record, "deviceId");
    String clientId = (String) DataUtils.extract(record, "clientId");
    if (Strings.isNullOrEmpty(clientId) && Strings.isNullOrEmpty(deviceId)) {
      logger.logError("invalid clientId and deviceId is coming.");
      return false;
    }
    return true;
  }
}

And below is my ValidatorB class in which I am validating few different fields as compared to ValidatorA on record object and if it is valid, then I am returning DataHolder.

public class ValidatorB extends Validator {
  private static final Logger logger = Logger.getInstance(ValidatorB.class);

  @Override
  public static Optional<DataHolder> getDataHolder(String processName, Record record) {
    Optional<DataHolder> dataHolder = Optional.absent();
    if (isValid(processName, record))
      dataHolder = Optional.of(buildDataHolder(processName, record));
    return dataHolder;
  }

  private DataHolder isValid(String processName, Record record) {
    return isValidType(processName, record) && isValidDatumId(processName, record) && isValidItemId(processName, record);
  }  

  private DataHolder buildDataHolder(String processName, Record record) {
    String type = (String) DataUtils.extract(record, "type");
    String datumId = (String) DataUtils.extract(record, "datumId");
    String itemId = (String) DataUtils.extract(record, "itemId");

    return new DataHolder.Builder(record).setType(type).setDatumId(datumId)
        .setItemId(itemId).setHolder(holder).build();
  }


  private boolean isValidType(String processName, Record record) {
    String type = (String) DataUtils.extract(record, "type");
    if (Strings.isNullOrEmpty(type)) {
      logger.logError("invalid type is coming.");
      return false;
    }
    return true;
  }  

  private boolean isValidDatumId(String processName, Record record) {
    String datumId = (String) DataUtils.extract(record, "datumId");
    if (Strings.isNullOrEmpty(datumId)) {
      logger.logError("invalid datumId is coming.");
      return false;
    }
    return true;
  }   

  private boolean isValidItemId(String processName, Record record) {
    String itemId = (String) DataUtils.extract(record, "itemId");
    if (Strings.isNullOrEmpty(itemId)) {
      logger.logError("invalid itemId is coming.");
      return false;
    }
    return true;
  }
}

And below is my abstract class:

public abstract class Validator {
  public abstract Optional<DataHolder> getDataHolder(String processName, Record record);
}

Question:

This is how I am calling for both of my process. As you can see, I am passing processName and its particular validator in the constructor argumnets.

ProcessConsumer processA = new ProcessConsumer("processA", new ValidatorA());
ProcessConsumer processB = new ProcessConsumer("processB", new ValidatorB());

  • Is this a good design where for each of my process, pass its validator along with?
  • Is there any way we can avoid passing that? And internally figure out what validators to use basis on the processName? I already have an enum with all my processName. I need to make this design extensible so that if I add new process in future, it should be scalable.
  • Also the way I have my abstract class Validator is right? It is not doing any useful things at all looks like.

Each of my Validator is basically trying to validate whether the record object is valid or not. If they are valid, then they make DataHolder builder and return it, otherwise it returns Optional.absent();