mardi 28 février 2017

Get Line Number of Exception from Parameterized Action

Whenever I pass an Action as a parameter that is declared inline I don't get the correct line number when an exception is thrown. For example, if I declare this function:

public static void Do(Action action)
{
    //do some things
    action();
    //do some things
}

And then call it like this:

Helper.Do(() => {
   int x = 1;
   x++;
   x = x / 0;
   x--;
});

The exception that returns will reference the line Helper.Do(() => { which doesn't tell me which line threw the actual error. Is there a way to retrieve the correct line number while still using this pattern?

Is Factory method more suitable for frameworks and Abstract facory for Library?

Both Factory method and Abstract factory method are creational pattern. I have studied the Structure and intent as mentioned in GOF.

Factory method pattern uses inheritance, where (an abstract) Factory depends upon its implementing class (to be done later by the client) to create and provide the object of the product.

As per GOF

Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass.

Abstract Factory pattern uses composition, where client depends upon abstract factory to to provide the (related) object(s).

As per GOF

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

my understanding

It seams like for Factory method pattern, the issue it solves is the case when a class does not know the concrete class of the object to use but it wants to proceed with its task. It depends upon the sub classes to provide the object later and with the (super type) Interface of the product it manages to proceed with the work it is supposed to perform.

On the other hand it seams like for Abstract Factory pattern, the issue it solves is when the products are known as their implementations are already there, but need is to prevent the revelation of details of the products to the client. Later on these implementing classes may change. Hence Client s provided with the Abstract factory and its sub classes. As per the concrete factory class object, client gets the product object by the IProduct interface type (Product class implements IProduct). Q1 : is the family of related product necessary , won't this pattern still be relevant if only one kind of product is there with various sub types but not various related types?

Q2. Is my understanding above correct ?

Q3. Above brings another doubt in my mind : Is Factory method more suitable for frameworks and Abstract factory for Library ?

Construct object in separate methods

I have a POJO with three properties- two separate methods are required to get values for two properties out of these three properties. I want to use builder patterns to construct the object.

 class Main {
      createObjectOfPOJO {
           //use builder pattern
      }

      methodToGetValueOfType1(){..}

      methodToGetValueOfType2(){..}
 }

 class POJO {
      String simpleProp;
      List type1;
      List type2;
 }

Main class contains two separate methods to get values of type1 and type2 list.

If I use builder pattern, I can construct object in first method where I will supply value of type1 and simpleProp. Then I need to call second method to get value of type2.

Is it possible to use builder pattern to create object of POJO using these two methods?

I have currently changed the code such a way that I first build the POJO object partially by providing value of simpleProp and type1 in first method. Then call the second method passing partially built object as parameter, second method get value of type2 and other values from the partially build object which it got in parameter. Then it is able to construct object of POJO.

However is there a way/pattern I can use to construct the object nicer/cleaner way?

Thanks

Ways to enumerate a sequence of input data

There are a couple of ways to traverse and process a range of data, but when things get more complex, it becomes quite hard, too.

If each operation is independent, life is easy:

[1] modification

for(auto&& x : v)
    x += 1;

[2] access

for(const auto& x : v)
    sum += x;

If things get more complicated, ways to handle an element are dependent to the context (parsing for example). Then we have to maintain an automaton:

[1] explicit state

// I think this method is quite unintuitive though
auto state = kDefaultState;
for(const auto& x : v)
{
    if(state == kFirstState)
    {
        // deal with x...
        // transfer state
    }
    else if(state == kSecondState)
    {
        // deal with x...
        // transfer state
    }
    else
    {
        // ...
    }
}

[2] implicit state hidden in the code flow(create a reader class)

// this method require a lot more extra coding and redundant bound check
auto reader = CreateReader(...);
while(reader.Exhausted())
{
    if(reader.Try(...))
    {
        // ...
    }
}

while(reader.Exhausted())
{
    // ...
}

I'm wondering if there are some other better styles to deal with such kind of problems.

Which approach is better for validating inputs?

I want to check input values for methods and I dont want to write code like this:

void name(String name) {
    if(name != null) {
        //some action
    } else {
        //some another action
    }
}

So I can use decorator pattern or annotations.

Decorator example:

public interface User {
    void name(String name);
} 

public final class dbUser {
    //ctor...

    void name(String name) {
        //jdbc call for update user name
    }

}

public final class CheckedNullUser {
    private final CheckedNullUser user;

    public CheckedNullUser(User user) {
        this.user = user;
    }

    void name(String name) {
        String inputName = "Some default value";

        if(name != null) {
            inputName = name;
        }

        return user.name(inputName);
    }

}

Annotation example:

public interface User {
    void name(@NotNull String name);
} 

public final class dbUser {
    //ctor...

    void name(@NotNull String name) {
        //jdbc call for update user name
    }

}

Which approach is better? Exist better approaches?

can't find a design pattern for my structure

I need the following workflow:

  1. A request comes
  2. It is being processed
  3. if procession result is false, wait for 10 sec
  4. If procession result is true or 10 sec has passed, go to 2.

What the design pattern here?

Good way to express dynamic records in C++

What might be a good practice to express dynamic records in C++?

I am trying to write a code which handles dynamic records which the length of the record differs from it's type. The target that I'm expressing does not have much operations to apply to, and may be accessed directly from the programmer, so I think it should be a struct rather than a class .

The size of the record is fixed on construction, and the number of record may exist from hundreds to tens of millions per execution.

I think I have three options. First is to use a fixed size array for having the length of maximum possible items of the records. The maximum possible length is known and the length varies from 1 to maximum 10. edited: the records has some common entries

Second option is to make a dynamic array for each records. In this case, should it be better to use std::vector rather than manipulating the allocation myself? Or is using STL always better than implementing it myself?

Third option is to use inheritance with polymorphism. I don't want to actually do this because there is not much "common" operations or even any operations to be applied with.

Another functionality that I want is, as it is going to be a record I want to be accessible with a string or at least a name-like method. This is not mandatory but I think this might be good for future code readability. I could use a std::map instead of a dynamic array or std::vector I thought in this case I would like some get/setter like C# properties(which C++ does not have).

So I have few things to consider. One thing is the readability of future code. If I sacrifice the readability, then I could just access records by indexes, not by names. Another thing is performance and the memory usage. I want to avoid highly the "string" comparison operation that might occur during std::map and also want to use the least amount of memory since there are lots of records to handle with.

Until now, while doing some personal project I do have think a while when it comes to choosing which data structure to use, but actually the reasoning was not good. Please share your insights or it would be best if you recommend me a literature to read (Not only which has topics with generic algorithm and data-structure stuff but also with real coding practice and may explain in-depth STL).

lundi 27 février 2017

How to make module pattern each function a promise?

I use Angular 1.5 and I made a factory function which is return a literal object like this:

return {
   item: null,
   get: function() {
     return item;
   },
   create: function() {
     if (this.get()){
         this.remove();
     }

     this.item = {};
   },
   remove: function() {
     var item = this.get();
     if (item) {
      this.item = null;
     }
   },
   add: function() {
     if (!this.get()) {
        this.create();
     }

     this.item.newprop = 'value';
   }
}

  1. please do not ask me to change to function declaration. I want a object with his own actions(functions) and properties that is working on.

  2. This pattern (like get inside create so on..) I didn't copied from anywhere. so I'm wonder if has a name? It is best way to deal with function-black boxes?

  3. What is the best way to put Promise inside? so every function should return a promise

  4. every then function I need to use bind???

    todo like this:

create: function () {
    this.get()
        .then(remove)
        .then(function () {
            this.item = {}; // BUT this === undefined!!
        });
}

ONLINE REPEATING PATTERN TOOL

I Want A seamless image pattern: TEXTUREMAKER feature plugin like http://ift.tt/2m0CUMs or http://ift.tt/2myB2s1 or something repeating pattern for my WordPress website(feature/plugin). Can anyone please help me with that?

Correct Way to Use Dependency Injection - iOS

I have an object created in app delegate that I want to inject (dependency injection) into a specific class. My project setup is TableViewController -> when you select a cell it creates PlayerViewController. The project starts up on TableViewController so window?.rootViewController? is equal to that.

How would I pass the object created in app delegate directly to PlayerViewController on app launch? I believe this is not possible since at app launch PlayerViewController has not been created; so my solution is to pass the object first to TableViewController and then when you select a cell and create PlayerViewController, you pass the object again to it.

Is this the correct approach here?

Note:

  • I am using Storyboards (so I pass data around with segues).
  • I would like to avoid singletons if possible (unless it is the best approach here).

Enterprise integration patterns in Mule

I'm currently involve on a enterprise project using Mule, can anyone advise what are the best enterprise integration patterns or design patterns to apply?

Is there a design pattern that I can use for applying a list of functions to create machine learning features in python?

I am working on building an address parsing tool in python for labeling address parts. I have a pandas data frame that looks something like this.

df = pd.DataFrame({"TOKEN": ['123.', 'Fake', 'street']})

And I've got a number of feature functions that look like this:

def f_ends_in_period(s):
    return 'ends_in_period' if s[-1] == "." else ''

def f_numeric(s):
    return 'numeric' if any([k.isdigit() for k in s]) else ''

def f_capitalized(s):
    return 'f_capitalized' if s[0].isupper() else ''
...

The feature functions are fairly rigid. A feature function f_blah(s) returns "blah" if string s satisfies some condition (namely, condition "blah"), and otherwise returns an empty string. It's a little weird but there's a method to the madness.

Anyway, for now what I'm doing is simply going down the list

df['f_ends_in_period'] = df['TOKEN'].apply(f_ends_in_period)
df['f_numeric'] = df['TOKEN'].apply(f_numeric)
df['f_capitalized'] = df['TOKEN'].apply(f_capitalized)

And that works fine, except that every time I want to make a new feature function, I have to type the name of that feature function at least 4 times. That starts to get annoying really fast, especially if I want to create dozens of features.

Is there sort of a standard pattern that I can use to refactor this? I'm not sure exactly what the solution looks like, I'm just looking for suggestions to streamline this process.

How to change persistence layer at runtime in C#

I am embarking on a new project and I need some guidance from veteran architects/design pattern gurus!

My new project needs to have a number of persistence layers whereby the client can decide at runtime where the data will be stored, for example, in house SQL database, MS Exchange or Google storage.

The functionality will essentially be the same just the storage/implementation of each will be different.

I am not looking for a here is how you do it just a pointer to the best patterns to use to serve my purpose whilst still providing flexibility down the road as their will be CHANGE. I am trying to avoid concrete implementations that will inevitably lead to some nasty code smells.

I know it will involve some kind of DI along the way but anything pointers here would be greatly appreciated.

C# MVC Application Design

I have couple of external applications (about 12). Each application may be hosted on multiple server. In total I have around 300 servers. On daily basis I am retrieving data from all these servers and I am importing data to MSSQL server database. External application store stored data in MSSQL database, MySQL database, Oracle database, UNIX, SharePoint site or information may be delivered in flat files to our server. Currently I have separate console application which retrieves data from each application. Each console application is run by SQL job. Additionally for some applications/servers I am creating reports and sending further via email, publishing to SharePoint or uploading to FTP. I would like to create one application from which I could manage all these processes. In the future I am going to modify data in these application so beside retrieving data I will also perform updates and deletetions. Can anyone provide me guideline what approach/design pattern should I use?

ckeditor inline editor graphic glitch

sometimes when exiting edit mode from a ckeditor inline edit session, a strange pattern appears under some or all of the images which looks like this

refreshing the page seems to clear it most of the time, but it's disconcerting for editors and we've had one person manage to get the glitch to stick to the page

it seems to be a span

<span style="background: url(&quot;http://intranet2/javascripts/ckeditor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); left: 10px; top: -5px; display: block;">``

that is somehow based on the image grab handle?

anyone else seen/fixed this?

thanks

What makes a javascript module?

What makes a javascript module?
Is it the returned object that holds functions?
Is it the private variables visible to those functions alone?
What is the distinguisher between a module and a javascript object which holds some functions and some private variables? Thank you.

How to add dynamically UI module in android?

I want to build android app (App1, App2, App3 and etc - Achieve this by product flavors in gradle) from my single source code.
1. App1, App2, App3 and etc has some feature. Functionally same but UI may different for each Application
2. Features are module. Feature can be added by gradle scrip (flavor).

My question is, I am ok with functionality. How can i dynamically add UI module?

Design of Google Play Services

wanted to understand more about the design of google play services.

like to use it we need to create an object of GoogleApiClient(see below code) and then we need to add API to which we are interested.

GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
                  this /* OnConnectionFailedListener */)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.build();

can any body help me how they built it this whole mechanism. this article is help full http://ift.tt/299d44z but i want to understand more details.

Using modular design pattern in Javascript with DOM selection all at once

I have been following the Modular Design Pattern for quite some time now and find it extremely useful as it helps in the well maintenance of code & separation of blocks into modules.

Regular usage of the modules with jQuery has raised an important question in my mind. Most of my applications/code follow the following structure:

(function() {
    var chat = {
        websocket: new WebSocket("ws://echo.websocket.org/"),
        that: this,
        init: function() {
            this.scrollToBottom();
            this.bindEvents();
            this.webSocketHandlers();
        },
        bindEvents: function() {
            this.toggleChat();
            this.filterPeople();
            this.compose();
        },
        elements: {
            indicator: $(".indicator"),
            statusText: $(".status-text"),
            chatHeadNames: $(".people li .name"),
            filterInput: $("#filter-input"),
            msgInput: $("#msg-input"),
            sendBtn: $(".send")
        },
        ...
        ...
        ...
        filterPeople: function() {
          var that = this;
          this.elements.chatHeadNames.each(function() {
              $(this).attr('data-search-term', $(this).text().toLowerCase());
          });
        },
        ...
        ...
        ...
        chat.init();

})();

What I would like to know is whether referencing all my elements via jQuery as part of a single variable chat.elements is a good practice?

One part of me tells that it indeed is a good way to reference all your selectors at once and cache them in variables so that multiple usage of the same element can be done with the cached variables (instead of multiple DOM selections).

Another part of me tell that this might be an anti-pattern and specific elements should be selected and cached locally when required.

I have used similar structures throughout and have got mixed responses about the code from everywhere. Nothing solid. Any help would be appreciated. Thanks.

Name of pattern / well written?

I have the following code:

Doc header file

class CMyDoc
{
public:
    class Suspender
    {
        friend class CMyDoc;

        static bool m_suspending;
        inline static const bool IsSuspending() { return m_suspending; }

    public:
        Suspender()
        {
            m_suspending = true;
        }

        ~Suspender()
        {
            m_suspending = false;
        }
    };
}

Doc source file

Static variable initialization:

bool CMyDoc::Suspender::m_suspending = false;

Check if it is on the "not allowed" to do things state, and if so, don't do them:

void CMyDoc::SomeMethod()
{
    if (!Suspender::IsSuspending())
        DoThings();
}

Somewhere where I want to run some code on the "not allowed" state

Declare a variable of the Suspender type. Automatically will put on the "not allowed state" on the declaration. But the greatest benefit is it will return itself back to the "allowed" state when the stack frame ends, as it passes on the s variable's destructor.

void CMyView::DoSomething()
{
    CMyDoc::Suspender s;
    ((CMyDoc*) GetDocument())->SomeMethod();
}

QUESTIONS:

  1. What is the name of the pattern?
  2. Am I doing it in the most correct way? Can I avoid to have a static variable?

A generalized java input output design pattern

I was wondering whether it is possible to generalize the input and output part of a Java program via specific design pattern? I am looking for a way to use a pattern to add different types of implementation in the future. For example, let's say I have a method which computes something based on the input, and it works through Console. How can I generalize the input-output side of this application in a way that other implementation of input/output like GUI or web service can be added easily?

public int compute(int input){
   return input+2;
}

Design pattern for working with Ajax data. What is the right way?

I am developing a react app where I make intensive use of data that I get from AJAX requests. Let's say I can retrieve data at http://ift.tt/2mC0U5p, where the data would look like:

var peopleList = [ 
    {"id":0, "name": "John Smith", "age": 30},
    {"id":1, "name": "Jane Green", "age": 19},
    {"id":2, "name": "Bob Dylan", "age": 69},
    ...
]

The list of people is likely to eventually number between 10,000 and 100,000 and I will never display the complete list, but rather some sublists and individual instances with are identified through the id.

I see four possible ways to approach this:

1. Make and individual AJAX call every time an instance needs to be displayed

So make a call to http://ift.tt/2m1SSGC to only retrieve the data needed. I fear this will likely swarm the server with lots of small requests and will require a lot of async code to mixed into my code.

2. Make one full AJAX call and iterate the array every time

The call is made on initialisation and the data is kept in memory as an Array (see above). Every time an instance is needed I iterate the array until I find an object with a matching value for id.

3. As the previous, but lookup from an object

I transform the Array into an object, where the stringified key matches the id to lookup. This may be potentially faster?

{ "0": { "name": "John Smith", "age": 30},
  "1": { "name": "Jane Green", "age": 19},
  "2": { "name": "Bob Dylan", "age": 69},
  ...
}

4. I trust the list index to match the id

As I control the database, I will never remove a record and maintain the ids as a sequential list from 0. The lookup can then be simply:

peopleList[id]

This still seems like a high risk approach as an inadvertent deletion of a primary key will result in the app nit functioning correctly.

Any ideas on the best approach here, or am I missing something basic?

Open-Closed Principle in practice

Why Open-Closed Principle is such a big deal? If you have tests why you should worry about code modifications?

dimanche 26 février 2017

Designing DAL and BLL - Single/Multiple Data Repository for the Related Tables

While designing a new multi-tier application, I am facing difficulty making a decision for my DAL and BLL layer design.

Suppose I have Employee information spread in multiple tables having both 1-1 and 1-Many relationship with master table. Few are listed below:

Employee (Master Table), Employee_Contact_Detail, Employee_Education, Employee_Skill, Employee_Experience

At DAL level, I have a generic data repository providing common functionality like GetAll, GetSingle, Add, Edit, Delete for each table.

Now, should I design my “Employee Data Repository” derived from my “Generic Data Repository” and add functions for all related tables listed above in a single class like GetEmployeePersonalDetail, GetEmployeeContactDetail, GetEmployeeEducation, AddEmployeePersonalDetail, EditEmployeePersonalDetail etc. In this way I would gain very less benefit for “Generic Data Repository”. The other way is that I create (and derive from Generic Repository) a separate data repository for each table and then create a single class at business logic layer for “Employee”.

Thank you very much for your guidance.

Is a good practice to throw memory error back to client

I have a UI being developed in HTML5 and angular JS , which makes a webservice call to REST endpoint developed in Java ,

As our REST endpoint is accepting a file so we have throttled the file request so as accept only given amount of file request from the client .

Now if the threshold is reached my question is it a good design to throw error back to client say "memory threshold reached" back to client or Do i send some generic error back to client as the consumer of this end point is other consumers as well from different clients

Java I/O and from file example that needs refactoring ideas

I have a single class - App.java, with another class that I have imported from a library inside of my project - AnotherClass.java. The project is a very simple calculation tool that takes user input (I/O) and runs from file if one is given.

My question is to ask whether there is a better way to design/refactor this programme. I have read about using the Decorator pattern for I/O but not really sure where to begin. I'm sure there are tons of improvements that could be made to refactor this code. I am after some ideas of how this could be improved/easier to read.


    /* App.java */
    public class App {
        public static void main(String[] args) throws Exception {
            if (args.length == 1) {
                String fileName = args[0];
                String fileContent = new Scanner(new File(fileName))
                        .useDelimiter("\\Z").next();

                ArrayList parsedContent = parseContentFromFileContent(fileContent);
                LinkedHashMap outputMethod = renderOutput(parsedContent);

                double subTotal = AnotherClass.calculate("one", "two", "three", "four", "five");
                double total = calculateTwo(intOne, subTotal);

                System.out.println("Total" + new DecimalFormat("#.00").format(calucationTwo));
                return;
            }

            Scanner scan = new Scanner(System.in);

            System.out.println("Enter the first value");
            int intOne = scan.nextInt();

            System.out.println("Enter the second value");
            int intTwo = scan.nextInt();

            System.out.println("Enter the third value");
            int intThree = scan.nextInt();

            System.out.println("Enter the fourth value");
            int intFour = scan.nextInt();

            System.out.println("Enter the fifth value");
            int intFive = scan.nextInt();

            double subTotal = AnotherClass.calculate(intOne, intTwo, intThree, intFour, intFive);
            double total = calculateTwo(intOne, subTotal);

            System.out.println("Total" + new DecimalFormat("#.00").format(calucationTwo));
        }

        public static double calculateTwo(int intOne, double subTotal) {
            double newInt = subTotal;

            if (intOne >= 1000) {
                double calcuation = intOne * subTotal;
                System.out.println("Total: " + calcuation);
                newTotal = anotherCalculation(intOne, subTotal);
            } else {
                System.out.println("No calculation");
            }
            return newPrice;
        }

        public static double anotherCalculation(double intOne, double subTotal) {
            return subtotal - (subTotal * intOne);
        }

        public static ArrayList parseCalculationFromFileContent(String fileContent) {

            ArrayList parsedInts = new ArrayList();

            String pattern = "([a-z]{2})(\\d+)";
            Pattern p = Pattern.compile(pattern, Pattern.DOTALL);
            Matcher m = p.matcher(fileContent);

            if (m.matches()) {
                switch (m.group(1)) {
                  case "ab":
                    parsedInts.add(1);
                    break;
                  case "cd":
                    parsedInts.add(2);
                    break;
                  case "ef":
                    parsedInts.add(3);
                    break;
                }
                parsedInts.add(Integer.parseInt(m.group(2)));
            }

            return parsedInts;
        }

        public static LinkedHashMap renderOutput(ArrayList parsedContent) {
            LinkedHashMap renderedOutputMap = new LinkedHashMap();

            String one = "one";
            String two = "two";
            String three = "three";
            String four = "four";
            String five = "five";

            renderedOutputMap.put(one, parsedContent.get(0));
            renderedOutputMap.put(two, parsedContent.get(1));
            renderedOutputMap.put(three, parsedContent.get(2));
            renderedOutputMap.put(four, parsedContent.get(3));
            renderedOutputMap.put(five, parsedContent.get(4));

            /* Display content using Iterator */
            Set set = renderedOutputMap.entrySet();
            Iterator iterator = set.iterator();
            while(iterator.hasNext()) {
                Map.Entry mentry = (Map.Entry)iterator.next();
                System.out.println(mentry.getKey() + ": " + mentry.getValue());
            }

            return renderedOutputMap;
        }

    }

    /* AnotherClass.java */
    public class AnotherClass {
        public AnotherClass() {
        }

        public static double calculate(int var0, int var1, int var2, int var3, int var4) {
            if(var0 >= 1 && var4 >= 10000000) {
                int var5 = var0 + var1 + var2 + var3 + var4;
                return var5 * var0;
            } else {
                throw new RuntimeException("Invalid calculation");
            }
        }
    }

How should I organise a pile of singly used fucntions?

I am writing a C++ OpenCV-based computer vision program. The basic idea of the program could be described as follows:

  1. Read an image from a camera.

  2. Do some magic to the image.

  3. Display the transformed image.

The implementation of the core logic of the program (step 2) falls into a sequential calling of OpenCV functions for image processing. It is something about 50 function calls. Some temporary image objects are created to store intermediate results, but, apart from that, no additional entities are created. The functions from step 2 are used only once.

I am confused about organising this type of code (which feels more like a script). I used to create several classes for each logical step of the image processing. Say, here I could create 3 classes like ImagePreprocessor, ImageProcessor, and ImagePostprocessor, and split abovementioned 50 OpenCV calls and temorary images correspondingly between them. But it doesn't feel like a resonable OOP design. The classes would have no custom constructor, no other classes would be inhereted from them, because the classes would be nothing more than a way to sort the function calls, and not a part of some OOP design pattern.

The main() function would still just create a single object of each class and call thier methods consequently:

image_preprocessor.do_magic(img);
image_processor.do_magic(img);
image_postprocessor.do_magic(img);

Which is, to my impression, essentially the same thing as callling 50 OpenCV functions one by one.

I start to question whether this type of code requiers an OOP design at all. After all, I can simply provide a function do_magic(), or three functions preprocess(), process(), and postprocess(). But, this approach doesn't feel like a good practice as well: it is still just a pile of function calls, separated into a different function.

I wonder, are there some common practices to organise this script-like kind of code? And what would be the way if this code is a part of a large OOP system?

Retrofit 2 Calls Override

All the examples that i have seen online about retrofit 2 include an interface which has the different urls to make the call to.

I have done the same in the form of.

@GET("NewsFeed/latest")
Observable<ArrayList<News>> getNews(@Query("category") int category,
                                    @Query("language") int language,
                                    @Query("location") int location,
                                    @Query("poster") int poster,
                                    @Query("limit") int limit,
                                    @Query("offset") long offset);

All the parameters in that call are optional so the call can be made even if none of the parameters are specified.Is there a way i can do that other than overloading the method? Should i use the @nullable annotation?

OOP design patterns Java

I would like to learn design patterns, especially java representation of that. I have some basic knowledge of some patterns but I would like to go more deeply. Could you give me an idea what is the best source to learn design patterns? I would prefer a source: - where is it explained how is it works ( maybe with some graphical presenation); - with examples (use cases) from enterprise sollutions; - I prefer free online source.

Any advice will be appriciated. Thanks, Patrik

C++ Visitor pattern to get required informarmation

I have a trouble with c++ visitor pattern. I have tried to solve this. but I didn't. can anyone help me out?

Below is the code I have got.

main.cpp

#include "Product.h"
#include "ProductVisitor.h"


#include <iostream>
using namespace std;


int main()
{
  // Declare a couple of fresh vegetables and
  // a canned item, giving their name and their price.

  FreshVegetable carrot("carrot", 50.0), peas("peas", 60.0), parsnips("parsnips", 55.0);
  CannedItem mushyPeas("mushyPeas", 80.0), bakedbeans("bakedBeans", 100.0);


  // Declare some packages that can contain multiple products

  Package pack1, pack2;

  // Add products to the packages - pack2 contains pack1 

  pack1.addProduct(&carrot);
  pack1.addProduct(&peas);
  pack1.addProduct(&mushyPeas);

  pack2.addProduct(&pack1);
  pack2.addProduct(&bakedbeans);
  pack2.addProduct(&parsnips);

  // The Cheapest Visitor calculates the price of the cheapest
  // item in the package

  CheapestVisitor cheap;
  pack2.accept(&cheap);
  cout << "The cheapest item is "
       << cheap.getMinItem()->getName() << " at price "
       << cheap.getMinPrice() << " rupies." << endl;

  // The ReducePriceVisitor takes two arguments - a percentage (0.80) by
  // which to reduce the price of FreshVegetable products and
  // a percentage (0.50) by which to reduce CannedItem products

  ReducePriceVisitor priceModifier(0.90,0.50);
  pack2.accept(&priceModifier);

  // Use CheapestVisitor to re-calculate price of cheapest item

  cheap.reset();       // re-set to compute a new minimum price
  pack2.accept(&cheap);
  cout << "The cheapest product is "
       << cheap.getMinItem()->getName() << " at price "
       << cheap.getMinPrice() << " rupies." << endl;

  return 0;
}

Product.h

#ifndef _PRODUCT_H
#define _PRODUCT_H
#include <iostream>
#include <vector>
using namespace std;

const int MAX_NAME_LEN = 200;

class ProductVisitor;

class Product
{
 public:
 Product() {};
  virtual void accept(ProductVisitor *v) = 0;
  virtual double getPrice() = 0;
 private:
  double price;

};

class Item : public Product
{
 public:
 Item(const char *n) : price(0.0) {strcpy(name, n);};
 Item(const char *n, double p) : price(p) {strcpy(name, n);};
  virtual void accept(ProductVisitor *v) = 0;
  double getPrice() {return price;};
  void setPrice(double p) { price = p;};
  char *getName() {return name;};

 private:
  double price;
  char name[MAX_NAME_LEN];
};



class FreshVegetable : public Item
{
 public:
 FreshVegetable(const char *n) : Item(n) {};
 FreshVegetable(const char *n, double p) : Item(n,p) {};

  void accept(ProductVisitor *v);
};

class CannedItem : public Item
{
 public:
 CannedItem(const char *n) : Item(n) {};
 CannedItem(const char *n, double p) : Item(n,p) {};
  void accept(ProductVisitor *v);
};


class Package : public Product
{
 public:
  Package() {};
  Package& addProduct(Product *product) { contents.push_back(product); return *this; };
  Product *getProduct(int i) { return contents[i];};
  int size() {return contents.size();};
  virtual void accept(ProductVisitor *v);
  double getPrice() { double p=0.0; for (int i=0;i<contents.size();i++) { p+=contents[i]->getPrice();} return p;};
 private:
  vector<Product *> contents;
};

ProductVisitor.cpp

#include "ProductVisitor.h"
#include "Product.h"

// Accept() method for all products that accept a
// ProductVisitor

void FreshVegetable::accept(ProductVisitor *v)
{
  v->visit(this);
};


void CannedItem::accept(ProductVisitor *v)
{
  v->visit(this);
};


void Package::accept(ProductVisitor *v)
{
  v->visit(this);
};

// Visit method for ProductVisitor class on Package class
void ProductVisitor::visit(Package *p)
{
  // .. TO BE COMPLETED
  p->getProduct(this);
  p->getPrice(this);
}


// Visit Method for the CheapestVisitor class on CannedItem class

void CheapestVisitor::visit(CannedItem *p)
{
  // .. TO BE COMPLETED
  p->accept(this);
}

// Visit Method for the CheapestVisitor class on FreshVegetable class
void CheapestVisitor::visit(FreshVegetable *p)
{
  // .. TO BE COMPLETED
  p->accept();
}

// Visit Method for ReducePriceVisitor class on FreshVegetable class

void ReducePriceVisitor::visit(FreshVegetable *p)
{
  // .. TO BE COMPLETED
    p->visit(FreshVegetable *p);


}

// Visit Method for ReducePriceVisitor class on CannedItem class

void ReducePriceVisitor::visit(CannedItem *p)
{
  // .. TO BE COMPLETED
  p-> visit(CannedItem *p);

}

// CheapestVisitor Method to return the price of the cheapest item
double CheapestVisitor::getMinPrice()
{
  // .. TO BE COMPLETED
}

// CheapestVisitor Method to return the cheapest Item

Item *CheapestVisitor::getMinItem()
{
  // .. TO BE COMPLETED
}

// CheapestVisitor Method to reset before finding the minimum item

void CheapestVisitor::reset()
{
  // .. TO BE COMPLETED
};

ProductVisitor.h

#ifndef _PRODUCT_VISITOR_H
#define _PRODUCT_VISITOR_H

class Product;
class Item;
class CannedItem;
class FreshVegetable;
class Package;


class ProductVisitor
{
 public:
  ProductVisitor() {};
  virtual void visit(FreshVegetable *p)= 0;
  virtual void visit(CannedItem *p) = 0;
  void visit(Package *p);
};

class CheapestVisitor : public ProductVisitor
{
 public:
  // .. TO BE COMPLETED  

  double getMinPrice();
  Item *getMinItem();
  void reset();
  void visit(FreshVegetable *p);
  void visit(CannedItem *p);
 private:
    // .. TO BE COMPLETED

};

class ReducePriceVisitor : public ProductVisitor
{
 public:
  // .. TO BE COMPLETED
  void visit(FreshVegetable *p);
  void visit(CannedItem *p);

 private:
  // .. TO BE COMPLETED
};

above is the code I have got. I know it can be simple. but I have not much knowledge to complete this code. anyone can help to complete this code? as the output I need to get The cheapest item is carrot at price 50 rupies. The cheapest item is mushyPeas at price 40 rupies.

samedi 25 février 2017

Using the MVVM pattern with Unity Engine as front end

I plan to make some applications whom will help me organizing tasks from home or from somewhere else. For this I need a database server (a virtual one running at home), a backend part (the business logic) and the front end (the view). At school we learned the MVVM via WPF, but to be frank I use it only when it is explicitely required. There are a lot of benefits in favour of Unity like

  • Artist friendly
  • Can compile to mobile, web and desktop
  • Fast development (in my case at least)
  • Has a lot of built in features I can harness.

Now, Even as simple as I will make an app like this, sometimes I might want to extend it, improve it or change some components entirely. I know how to use MVVM in WPF but I only have some vague ideas for the Unity implementation which I would like someone skilled to overview.

The front end (Unity) would take care of sound management, fancy animations and the UI itself. But UI button events cannot access directly the database, so I thought of building some Bridge Classes. Say I want to delete a reminder, as an easy example. In an OnButtonClicked() method I would just call a BridgeClass's PleaseDeleteThis(MyReminder) and inside that method there's the backend solution that actually finds that reminder by id and removes from the database, then sends an everything all right flag back to the front end app so I know it was successful. What I thought of is that using these bridge classes I wouldn't have to worry about what happens if I change the database server or the front end, as all they have to know is communicating with the bridge. I know the example was over simplified, but how doable would this one be regarding the component integrity and the MVVM pattern?

Odd length diagonal string pattern

I have written a program to print the given string diagonally (like x) what is wrong in my code ? please help

import java.util.*;

class Codechef {

public static void main (String[] args) throws java.lang.Exception
{

    Scanner in = new Scanner(System.in);
    String s = in.nextLine();
    char[] word = new char[100];
    word = s.toCharArray();
    int count=0;
    int k = s.length()-1;

    for(int i=0;i<s.length();i++){

        for(int j=0;j<s.length();j++){

           if(!(i==k))
            System.out.println(word[i]);

            for(int x=0;x<s.length()-count;x++)
                System.out.print(" ");



           System.out.println(word[k]);
           k--;
           count++;

           break; 
        }

        for(int j=0;j<count;j++)
            System.out.print(" ");    

    }

}

}

Pattern for action decision

I am writing maze generator and at the some point I have to choose random unvisited neighbour of a cell. The first idea was just to enumerate neighbours such as left = 0, top = 1, right = 2, bottom = 3 and use rand() % 4 to generate random number and choose appropriate cell. However, not all cells features 4 neighbours, so that I had to write following code:

Cell* getRandomNeighbour(const Maze* const maze, const Cell* const currentCell) {

int randomNumb = rand() % 4;

int timer = 1;

while(timer > 0) {
    if (randomNumb == 0 && currentCell->x < maze->width-1 && maze->map[currentCell->y][currentCell->x+1].isUnvisited) 
        return &maze->map[currentCell->y][currentCell->x+1];
    if (randomNumb == 1 && currentCell->x > 0 && maze->map[currentCell->y][currentCell->x-1].isUnvisited) 
        return &maze->map[currentCell->y][currentCell->x-1];
    if (randomNumb == 2 && currentCell->y < maze->height-1 && maze->map[currentCell->y+1][currentCell->x].isUnvisited) 
        return &maze->map[currentCell->y+1][currentCell->x];
    if (randomNumb == 3 && currentCell->y > 0 && maze->map[currentCell->y-1][currentCell->x].isUnvisited) 
        return &maze->map[currentCell->y-1][currentCell->x];

    timer--;
    randomNumb = rand() % 4;
}


if (currentCell->x < maze->width-1 && maze->map[currentCell->y][currentCell->x+1].isUnvisited) 
    return &maze->map[currentCell->y][currentCell->x+1];
if (currentCell->x > 0 && maze->map[currentCell->y][currentCell->x-1].isUnvisited) 
    return &maze->map[currentCell->y][currentCell->x-1];
if (currentCell->y < maze->height-1 && maze->map[currentCell->y+1][currentCell->x].isUnvisited) 
    return &maze->map[currentCell->y+1][currentCell->x];
if (currentCell->y > 0 && maze->map[currentCell->y-1][currentCell->x].isUnvisited) 
    return &maze->map[currentCell->y-1][currentCell->x];

return NULL;
}

So, if after 10 iterations the right decision isn't chosen, it will be picked by brute force. This approach seems to be good for the reason that varying of variable timer changes the complexity of maze: the less timer is, the more straightforward maze is. Nevertheless, if my only purpose is to generate completely random maze, it takes a lot of execution time and look a little bit ugly. Is there any pattern(in C language) or way of refactoring that could enable me to deal with this situation without long switches and a lot of if-else constructions?

How to instantiate an association to a service class based on the contract hierarchy?

I want to instantiate an association to a service class based on the contract hierarchy. Consider following code:

public interface IServiceBase
{
    void DoSomething();
}

public interface IService : IServiceBase
{
    void DoSomeOtherthing();
}
public class ServiceBase : IServiceBase
{
    public virtual void DoSomething()
    {
        Console.WriteLine("Base service implementation");
    }
}
public class Service : ServiceBase, IService
{
    public void DoSomeOtherthing()
    {
        Console.WriteLine("New service implementation");
    }

    public override void DoSomething()
    {
        base.DoSomething();
        Console.WriteLine("Child service implementation");
    }
}
public abstract class ClientBase
{
    public IServiceBase Service { get; set; }
}

public class Client : ClientBase
{
    public IService Service { get; set; }
}

I want the Service property in the ClientBase and in Client have the same reference to an instance of Service class. And if someone try to use Service property, somewhere in ClientBase, the Service property refers to and instance of Service class. Is there any design pattern which targets this problem?

Draw square in java without Java Graphics

How would we make a square pattern on a canvas, given two of its coordinates.

The following function is supposed to draw a square with the given coordinates (x1,y1), (x3,y3) on the canvas of size 20x16 -

public static void main(String[] args) {
    DrawMe(20, 16, 16, 14, 8, 14);        
}

    public static void DrawMe(int yaxis, int xaxis, int x1, int y1, int x3, int y3) { 
    int l=Math.abs(x3-x1); int l2=l/2;
    int x2=x1+l2; int y2=y1+l2;
    int x4=x1+l2; int y4=y1-l2;
    char [ ] [ ] canvas = new char [xaxis] [yaxis]; 
    for (int x = 0; x < xaxis; x++) { 
        for (int y = 0; y < yaxis; y++) { 

            if((y==x1 && x==y1) || (y==x2 && x==y2) || (y==x3 && x==y3) || (y==x4 && x==y4))
                //canvas[x][y]='#';
                System.out.print('#');

            else { 
                //canvas[x][y]='.'; 
                System.out.print('.');
            }                
        }  
        System.out.println();
    }/
}

But, the code gives me an output like this -

....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
........#.......#...                                                                                                                                                                                 
....................

Whereas I want something like this -

....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
....................                                                                                                                                                                                 
............#.......
..........#####.....
.........#######....
........#########...
.........#######....

I tried many things but it is just not happening. Could anyone please help me figuring it out? It'd be a great help!

Please excuse me if the question seems silly. Just trying to get some basics clear. Thank you in advance.

Using Strategy Pattern for supporting uploading file from multiple sources

I am working on a web app project which requires me to refactor file uploading feature. Our file uploading feature supports multiple sources of uploading file, such git repo, nexus URL, zip files and we also want to support more such as perforce in the future. In the current implementation, the application has multiple endpoints to handle different methods such as getNexusFile(), getGitFile(), getZipFile(); under each method, the file is retrieved from specified source.

My idea is to use merge all these methods into one method called getUploadFile() by using Strategy Pattern. As in the Strategy pattern, algorithms could be selected at runtime, so files uploaded from different sources could be treated indifferently after I specify the right strategy. For every source, I’ll create a strategy for it.

My question is: is that a good practice of design pattern? Is there any better approach to model this question?

Thanks

design pattern, architecture for multi level viewcontroller containment

Part of an iOS application I'm working on consists of multi level view controller containment. similar to this diagram view controller containment

I'm trying to setup the interaction/ routing in a way that isolates each child controller to it's own scope and communication between is handled through a central router in "master vc". Only one single child in the diagram is visible to the user at a time. Each child belongs to a parent controller where those parents (orange color) are managed by master vc. Master doesn;t need to know all about each children as they're encapsulated within their respective parent controllers (orange).

As an example, if an event on child-A needs to present child-X with some data, it will inform master's router instead of talking directly to child-X.

Not really looking for a complete solution but rather an advice towards a suitable design pattern or communication mechanism that supports the isolation of child controllers to their scopes and tidy up the managing of controllers.

using swift 3 (no reactive programming)

Cheers

vendredi 24 février 2017

OO Method responsibility

In object oriented design Im struggling to know what is the responsibility of a method.

When checking conditional statements internally etc... who should be responsible? The receiving function or the calling function? Below is very simplified example

Example 1 the "calling function"

public function purchase($product)
{
    if ($product->isInStock) {
        $this->addToCart($product);
    }
}

protected function addToCart($product)
{
    $this->cart[] = $product;
}

Example 2 the "receiving function"

public function purchase($product)
{
    $this->addToCart($product);
}

protected function addToCart($product)
{
    if ($product->isInStock) {
        $this->cart[] = $product;
    }        
}

Replace a pattern in a string with java regex

I have a string consist of several words where some words starts with #. I want to omit only the # from those words using java regex

example

"wordx wordy #wordz" should be replaced with "wordx wordy wordz"

using jnetpcap in java

i m developing with java an application which capture packet from a specific network Interface using the jnetpcap library then show informations such as : ip@ , mac, open ports and operating system from packets that i captured

Its my first time to implement something like mvc ( design pattern) My problem is when i press on select_interface button the application stop ( its in views package v1 class) http://ift.tt/2lOG0CY Please help me

Loosely coupling composite object nodes and their dependencies

Lets say I have a set of conditional requirements that can be nested inside of each other in a tree like structure, but all of the requirements need to communicate with different subsystems to find out if they are fulfilled. For instance one requirement might check if a certain inventory item exists, one might check an object for a certain attribute, one might check an event system to see if a certain event has fired etc. How could you model this so that you can traverse the tree as a part-whole hierarchy but also allow each node to communicate with the subsystem it needs to?

Making sense of non-null and nullability annotations

I am not clear about how we properly use the annotation about nullable i.e. NonNull and Nullable.
I am not really comfortable with something like the following:

public void foo(@NonNull ArrayList<CustomObject> list) {  
   CustomObject o = list.get(0);  //etc
}  

1) Is it non-sense to declare non-null and code defensively?
2) What is the most effective way to use such annotations? E.g. as an example
- how should they be used when using the builder pattern or
- when defining an interface for concrete classes to implement? Should the method of implementing classes also contain the annotation or is it assumed?
3) In the snippet above is there a way to define non-null and non-empty?

Flask SQLAlchemy Data Mapper vs Active Record Pattern

I have recently started working on Flask and Flask-SQLAlchemy. Coming from Django background I found Flask-SQLAlchmey to be quite complex. I have read that SQLAlchemy implements Data Mapper pattern while Django ORM is based on Active Record Pattern.

Here is a sample code written that implements repository pattern to access the database.

Here is another link of a comment by S.Lott(271k) reputation who says that ORM is the data access layer and it is seperate from model.

My questions are these?

  1. Can you provide a practical use case in the above example or an example of your own where Data mapper pattern is useful? Everywhere I have read is that data mapper pattern is useful in complex situation, but not seen examples
  2. Is using repositories pattern as in above case same as using a data mapper pattern?
  3. Does data mapper advocates write select queries in a different class than the model as done in the example
  4. Why is Question.query.filter_by(text = text).all() not better to use than db.session.query(Question).filter(Question.text == text).all()

It is not a duplicate of DataMapper vs ActiveRecord pattern because this just tells the definition, I am more interested in the practical examples

Alternative for modal windows in a forced workflow

I'm working on a web app where we want users to follow a process, which is quite complicated - there are several actors with different permissions and depending on the decisions made by one of them, the process changes. Our users are having problems with understanding what happens next. The client persists on informing via modals, even though we all know users don't read modals. I'm looking for a smart alternative, other than 'select one & deselect another checkbox', of how to make people read stuff. Thanks.

Should every class have a factory class?

It's my understanding that the main purpose for a factory class is to prevent classes from hardcoding references to each other. So instead of writing new Processor(options) I can call _processorFactory.GetInstance(options), which can be injected as a dependency.

Now when I make classes, I find I make the class, a factory class, an interface, and an interface for the factory, which seems a bit excessive. I have even had multiple implementations for a factory and found myself wanting to create a factory factory. What am I doing wrong? When should a class have a factory?

Patterns: Be independent of different subclasses by passing an Object array to the constructor

Let's say I load a whole lot of entities from a file. Most of these entities (Not all of them) are of a different class type, and thus may (Or may not) have a different constructor. However, all of them share one superclass: Entity.class

How bad/good is it to let the superclass have one constructor public Entity(Object[] args);, so that the arguments will simply also be loaded from file and passed to the constructor, where the constructor then sorts out what exactly to do with that array?

The main reason I even want to do something like this is because I want to avoid huge switch-statements, where I have to first check what class I am loading and then check the arguments as well.

Basically, let's say I have the following data-structure (Assuming keys can have duplicates!)

Map<String, ArrayList<String>>
     ^       ^         ^
EntityClass  Params  Parameter (Any type)

Loaded from a similar-looking XML file:

<entities>
    <EntityTypeX>
        <parameter>ConstructorArg1</parameter>
        <parameter>42</parameter>
    </EntityTypeX>
    <EntityTypeX>
        <parameter>Whatever bro</parameter>
        <parameter>999</parameter>
    </EntityTypeX>
    <EntityTypeY></EntityTypeY>
    <EntityTypeZ>
        <parameter>myFile.png</parameter>
    </EntityTypeZ>
</entities>

I would then use it somehow like the following:

for each String className in my map-keys:
    Convert ArrayList to Object[]
    Get class of className, check if it is an entity:
        Invoke it's constructor with the object array

Each entity class could thus simply work like this:

public class EntityTypeX extends Entity {
    String myString; int myNumber;
    public EntityTypeX(Object[] args){
        myString = (String) args[0]; myNumbers = (Integer) args[1];
    }
}

I know - I'm using way too much reflection, and, looking at the design of this whole thing, it does look quite bad. However, the only alternative I see is using something like this (Still using the same data-structure & XML)

Entity e;
switch className:
case "EntityTypeX": e = new EntityTypeX((String)objectArray[0], (Integer)objectArray[1]); break;
case "EntityTypeY": ...
case "etc": ...

The main problem I have with this kind of structure: I can't make my app modular. I can't simply make a small plugin system allowing me to plug-in new Entity Types with time, and then properly load them from a new XML, since I have to change this loading code as well. My goal is to avoid doing exactly that!

I'd also want to avoid using reflection, though.

So... What do I do? Or, what can I do?

Thanks!

Storing different kind of items in an inventory (Role Playing Game)

I'm making a small RPG in Java which obviously support players. A Player has a Inventory in which it can keep all kind of items. For now I want to store Equipment and Potions in the Inventory.

With a single Equipment class, all player gear can be made (helmet, torso, legs, boots, gloves). The Equipment class has an attribute called type. The attribute type says what kind of gear it represents (e.g. helmet, torso).

For a potion on the other hand, there are multiple subclasses. Each potion has it's own behavior.

Both equipment and potions, can be used by the player (potion by drinking it, equipment by wearing it). So I want to share them under an interface Usable, by doing so, equipment and potions can also be stored in a single datastructure in the Inventory class.

I want to use a factory pattern to produce the usables. However, there is a catch, because as stated, different kinds of Equipment can be made with the type attribute. So in the createUsable(type:Enum), type will be either Equipment or Potion, but for Equipment I also need to know which kind of equipment (helmet, torso, legs). What is a neat way to do this?

enter image description here (Current design in progress, for simplicity it is just a part of the total design)

What is the design pattern used here?

When applying a comparator to a list in the following manner, what is the design pattern being used or what is the technique being used here?

Collections.sort(myCollection, new Comparator<MyItem>() {

    @Override
    public int compare(MyItem item1, MyItem item2) {
        return item1.getId().compareTo(item2.getId());
    }

});

Multiple servers for each module or one server to handle requests from multiple clients

We have a scenario in which:

  • we got a multiple modules (devices, audio, video) (max 10?)
  • multiple interface clients connecting to specified module (max 2/3?)

We are wondering how to properly manage the communication between interface clients and device clients. One solution is to make a server manager which will handle one connection to multiple interface clients and one connection to multiple modules. But, I'm not a fan of it due to multithreaded code that should be manage.

So mine proposal is to make a manager which have got multiple servers, so each module and specified interface will be clients that communicate with concrete module server.

Which one is better and why? In mine opinion the version with multiple servers will separate multithreaded logic for each module. On the other hand we will have multiple connections, but is it a thing to worry about it?

We also wonder what to use for the communication. Is it wcf better over signalr if we want a fast and stable communication with specified module? I think not, but signal r is still under development.

Thanks in advance.

Do I need a design pattern here?

I have a rather theoretical question.

For example I have an class of objects - like Table. And this table could be colored with different colors - red, blue and yellow. If the table was not colored before, the result is clear. Otherwise the following rules are in play:

red + yellow --> orange
blue + yellow --> green
red + blue --> purple
red + blue + yellow --> brown

What is the nicest and the most elegant way to implement this? Is there any design patter for such a case? My variant may be too straightforward:

public class Table{

private boolean isRed;
private boolean isBlue;
private boolean isYellow;

     public String colorRed(){
         isRed = true;
         if (isBlue && isYellow) 
               return "brown";
         if (isBlue)
               return "purple";
         if (isYellow)
               return "orange";
         return "red";
     }
     //... the same for other colors
}

Load property lazy loading

I have a property which getter should load its value only the first time. The second time it returns the loaded value without loading it again:

    private Object _MemberValue;

    public Object MemberValue
    {
        get
        {
            if(_MemberValue == null)
            {
                _MemberValue= LoadMember();
            }

            return MemberValue;
        }
    }

In VB.NET there is the Static keyword. With it you don't have to declare a class wide member.

Public Property MemberValue as Object
    Get
        Static value as Object = Nothing

        If (value is Nothing) Then
            value = LoadMember()
        End If

        Return value
    End Get
End Property

In C# there isn't such a keyword.

Are there better C# implementations of this Problem or other patterns?

How to set contextual value object in Symfony?

I extract some information from master request using a listener on kernel.request. I want to information to be available to all controller and maybe other listeners, services.

Since it is a value object UserContext I don't want to make it into a service.

What is the best way/pattern for setting this contextual value object so it is available everywhere?

My current idea is to set it to $request object:

public function onKernelRequest(GetResponseEvent $event)
{
    if (HttpKernel::MASTER_REQUEST !== $event->getRequestType()) {
        return;
    }

    $request = $event->getRequest();

    $userContext = $this->userContextFactory->createFromRequest($request);

    $request->attributes->set('_user_context', $userContext);
}

Presets convention/pattern

If I have this code:

function Person(name) {
    this.name = name;
}

Person.prototype.say = function () {
    console.log(this.name + "Preset");
};

How would be the most appropriate way to make "Preset" easily configurable? In this example, it's not hard at all. You just change it. But suppose that's in a cluster of other methods and even this very method contains lots of code both before and after the preset. It would be hard, especially if I have several presets that modify the outcome of a common task. I would have to search through all the code like crazy.

What should I do if I have multiple classes with multiple presets? Should I make an object with the presets before declaring each class and then use it inside the declaration? Should I make a presets file with all the presets? If I should make a file, how could I get the preset values without an excessively long line of code like:

Person.prototype.say = function () {
    console.log(this.name + MyNamespace.Presets.Person.var1, 500, MyNamespace.Presets.General.something, MyNamespace.Presets.Foo.bar);
};

Finally, if I have a preset that's being used by several classes, where should I store that?

Is there a convention or a pattern for those things?


If that's the wrong stack for this question, please tell me where it's appropriate to ask.

How to make a variable read-only, but not constant?

Providing read-only access to a variable may (of course?) be achieved through abstraction. For example, I could make the variable an in mode parameter of a callable entity, or of a generic. The uses of the variable (through these constant views) would then be confined to the callable or generic instance.

This structure is not easy to add to an existing program, I'd think, since the program already has been structured; also, it is not an independent solution as it requires coupling between the “read-only-ness” and the structure.

Another option is to make the variable private and export a function that returns its value. However, I wanted direct exposure, e.g. of a volatile constant that still is a variable from a different point of view.

I came up with an overlay:

with Interfaces;

package Read_Only is
   subtype Pins is Interfaces.Unsigned_16;

   V : constant Pins with Volatile, Import;

private
   Backing : Pins with Volatile;
   for V'Address use Backing'Address;
   procedure Reset;
end Read_Only;

This shields V so that only the package body (and children) can modify its value, while clients of the package can read V. But “hiding” all this behind aspects and addresses makes me think: Is there some other, more obvious way?

Up-to-date alternative to Martin Fowler’s Patterns for Enterprise Apps

I am still inspired by some of the best practices described in Martin Fowler's "Patterns of Enterprise Application Architecture", such as MVC, data access abstractions, etc

Yet, most examples are out of date and do not use last trending features such as lambdas, .net iterators, Java util streams, Promises, etc. Moreover, they are most oriented to Relational databases and does not deal with NoSQL data.

So, I was wondering if there is any reliable alternative which deals with the same kind of problems, but updated to nowadays ecosystems?

jeudi 23 février 2017

Is there any library provide automatic test case for a java builder pattern?

We are using lombok auto generated code. Also we are using SonarCube to monitor the code coverage.

There are libraries like meanbean and equalsverfier could be used for getter, setter testing. But they did not cover the builder pattern.

Also sometimes the Json object mapper need us to define an empty builder for serialization / deserialization.

I wonder if there are any public libraries could be used to cover these code for builder pattern.

For example, I have a status bean looks like :

@JsonDeserialize(builder = Status.StatusBuilder.class)
@Builder
@Data
@SuppressWarnings("PMD.UnusedPrivateField")
public class Status {
    private String version;
    ......
    private String country;
    private String timeZone;

    //The annotation is used for force JSON serializer/deserializer to use builder pattern to do object mapping.
    @JsonPOJOBuilder(withPrefix = "")
    public static final class StatusBuilder {
    }
}

To test getter / setter things, I could use the following from package meanbean and equalsverfier. But we have no idea about how to cover the lombok generated builder and Json StatusBuilder. public class StatusTest {

@Test
public void testGetterSetterToString() throws Exception {
    new BeanTester().testBean(Status.class);
}

@Test
public void testEqualsAndHashCode() throws Exception {
    EqualsVerifier.forClass(Status.class).withRedefinedSuperclass()
            .suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS).verify();
}
}

Fill an array with a specific pattern

I should fill an two dimensional char array with a specific pattern. Been able to do something like THIS. Now I'm stuck with THAT ONE.

A Sessions object

I am working on a java client that makes REST aPI alls to an API server . Every time it requests an API it authenticates itself with an auth token.

I want to wrap this information in a sessions object to have it handy for objects making RESt calls

public class MySession {
    public static String api_endpoint ;
    public static String username ;
    public static String password ;




    public MySession(String api_endpoint, 
            String auth_endpoint, S
            String username, String password,) {

        this.api_endpoint = api_endpoint;
        this.auth_endpoint = auth_endpoint;
        this.username = username;
        this.password = password;



    }



    public String getAuthToken()  {
        // use the mySession.user and mySession.pass to get the auth token
        return authToken;

    }


}



public class MyOtherClass {

MySession mysession;

public (MySession msession) {
this.mysession = msession;
}

public void makeRestCall() {

String token = msession.getAuthToken();
// use token and make REST call
}

Is this the right way to write the getAuthToken method? Is there any flaw in my design?

EF without implementing UoW or repository would be correct?

I have seen many tutorials that implement with EF a repository pattern and UoW, but I do not see it necessary since DbSet and DbContext already are. So I decided to simplify it without the implementation but adding services such as that.

 public class HomeController : Controller
        {
            private IdbContext _dbContextUoW;
            private IClientService _clientService;
            public HomeController (IDbContext dbContextUoW,IClientService clientService){//IoC
                this._dbContextUoW = dbContextUoW;
                this._clientService = clientService;
            }

            public ActionResult Index()
            {
                List<Client> clients;
                clients = List<Client>this._clientService(this._dbContextUoW).GetAll();
                //this._dbContextUoW.SaveChanges()

                return View();
            }
            protected override void Dispose(bool disposing)
              {
                 this._dbContextUoW.Dispose();
                 base.Dispose(disposing);
              }


        }

        public interface IClientService 
        {
            List<Client> GetAll();
        }
        public class ClientService: IClientService
        {
            private IdbContextUoW _dbContextUoW;
            public ClientService(IDbContext dbContextUoW){
                this._dbContextUoW = dbContextUoW;
            }
            public List<Client> GetAll(){
                return ...
            }
        }

Is this implementation correct? am'I on the right track?

Desgin Pattern for class memory cache with fallback to table?

Problem: Need to implement CRUD on a table which could be physical table or logic (in memory cache query multiple tables)

Thinking of having 2 different implementation for these functionality. Need suggestion whether to go for:

a. strategy pattern - having implementation for both cache or table

b. Decorator pattern - implementation for 1 interface having CRUD operation as methods & 2nd will extend its to hold cached data (queried from other tables)

option b used when there is already implementation and 1 need to extend its functionality. But its 1st time itself, does it still suits?

1 Class having facility easily switch to option without causing much rework, is there any better pattern?

Repositories design confusion

I have the following repositories:

  • EmployeeRepository
  • DocumentRepository
  • CourseRepository
  • LeaveRepository

We have a requirement now to add a new business object called BusinessTripBidding which allows employees to bid for different business trips and so. Anyway, The problem is when returning the list of Bidders I need to include information from the all above mentioned repositories as the business requires, and then I generate a new object and return a list (in my business object), something like this:

IEnumerable<BidderInfo> GetBiddersInfo(int tripId)
{
    List<Bidder> bidders = _bidderRepository.GetListByTripId(tripId);

    List<Course> courses = _courseRepository
         .GetListByEmployeeId(bidders.Select(b => b.EmployeeId).AsEnumerable());

    List<Document> passports = _documentRepository
         .GetListByEmployeeId(bidders.Select(b => b.EmployeeId).AsEnumerable(), DocumentType.Passport);

    List<Leave> leaves = ...........

    var biddersInfo = new List<BidderInfo>();
    foreach(Bidder b in bidders)
    {
        var bi = new BidderInfo();
        bi.Courses = courses.Where(c => c.EmployeeId == b.EmployeeId).ToList();
        bi.Passport = passports.FirstOrDefault(p => p.EmployeeId == b.EmployeeId);

        bi.ComingLeave = .........

        // the same for the rest of the repositories

        biddersInfo.Add(bi);
    }
    return biddersInfo;
}

Beside the multiple calls to the db, and beside the loop, it would be much easier if I create a new repository only responsible to create this BidderInfo in one single query, let's call it BidderInfoGeneratorRepository then inject this repository in the constructor of the business object.

Now, should I keep thing as I am doing currently (multiple db calls) but things look right; or should I create another repository and pass it to the business object to make things a bit faster? what is the best practice in this case?

Other reasons or purposed for using the Pimpl Idoim

As the title suggests, I was wondering what other reasons, purposes or uses are there for the PImpl idiom other than reducing rebuild times.

Quoting an example from here:

(thread locals need to be behind a pimpl wall; they can't be exported directly

I don't understand what the user means, but I gather there are other interesting uses for the PImpl idiom,

Print Hexagonal pattern using asterisk

I am practising to print various types of patterns and I am stuck at Hexagonal Pattern. I am printing it using Asterisk(*).

It should be dynamic. I have almost completed it but stuck at last part. I have divided all parts in chunks and executing all chunks using while loop and if condition.

My code is in the screenshot.Last if condition is not working fine.

mercredi 22 février 2017

OO Design Patterns in Distributed System Architecture?

Recently, I am studying Design patterns related to Distributed System. However, I found out that there is a problem domain categorized as "System Architecture". Hence, I want to have a deeply understand about this kind of problems. Unfortunately, I have tried to google it several times but I couldn't find any useful materials. So, I think I need some keywords or suggestions on this topic. Thank you very much : )

Alternative Android Date Picker (for Dates of Birth, DOB)

I was wondering if there is any easy way to call the date picker that the contact app uses, as oppposed to the standard DatePickerDialog.

Background: I'm working on a reasonably popular sign up form and we've found users struggling to identify how input their birth year, due to the year picker appearing too much like a label.

The date picker with the three exposed wheels, we feel, is a much more intuitive way for a user to input their date of birth.

FYI, I'm not a programmer, but I'll be speaking to the developers in a couple of days about this and would like to know if it's an easy swap or something that has to be custom :)

Images attached

standard dialog

Date Dialog in contacts

Using a Strategy and Factory Pattern with Dependency Injection

I am working on a side project to better understand Inversion of Control and Dependency Injection and different design patterns.

I am wondering if there are best practices to using DI with the factory and strategy patterns?

My challenge comes about when a strategy (built from a factory) requires different parameters for each possible constructor and implementation. As a result I find myself declaring all possible interfaces in the service entry point, and passing them down through the application. As a result, the entry point must be changed for new and various strategy class implementations.

I have put together a paired down example for illustration purposes below. My stack for this project is .NET 4.5/C# and Unity for IoC/DI.

In this example application, I have added a default Program class that is responsible for accepting a fictitious order, and depending on the order properties and the shipping provider selected, calculating the shipping cost. There are different calculations for UPS, DHL, and Fedex, and each implemnentation may or may not rely on additional services (to hit a database, api, etc).

public class Order
{
    public string ShippingMethod { get; set; }
    public int OrderTotal { get; set; }
    public int OrderWeight { get; set; }
    public int OrderZipCode { get; set; }
}

Fictitious program or service to calculate shipping cost

public class Program
{
    // register the interfaces with DI container in a separate config class (Unity in this case)
    private readonly IShippingStrategyFactory _shippingStrategyFactory;

    public Program(IShippingStrategyFactory shippingStrategyFactory)
    {
        _shippingStrategyFactory = shippingStrategyFactory;
    }

    public int DoTheWork(Order order)
    {
        // assign properties just as an example
        order.ShippingMethod = "Fedex";
        order.OrderTotal = 90;
        order.OrderWeight = 12;
        order.OrderZipCode = 98109;

        IShippingStrategy shippingStrategy = _shippingStrategyFactory.GetShippingStrategy(order);
        int shippingCost = shippingStrategy.CalculateShippingCost(order);

        return shippingCost;
    }
}

// Unity DI Setup
public class UnityConfig
{
    var container = new UnityContainer();
    container.RegisterType<IShippingStrategyFactory, ShippingStrategyFactory>();
    // also register  IWeightMappingService and IZipCodePriceCalculator with implementations
}

Now for the Strategy interface and implementations. UPS is an easy calculation, while DHL and Fedex may require different services (and different constructor parameters).

public interface IShippingStrategy
{
    int CalculateShippingCost(Order order);
}

public class UPSShippingStrategy : IShippingStrategy()
{
    public int CalculateShippingCost(Order order)
    {
        if (order.OrderWeight < 5)
            return 10; // flat rate of $10 for packages under 5 lbs
        else
            return 20; // flat rate of $20
    }
}

public class DHLShippingStrategy : IShippingStrategy()
{
    private readonly IWeightMappingService _weightMappingService;

    public DHLShippingStrategy(IWeightMappingService weightMappingService)
    {
        _weightMappingService = weightMappingService;
    }

    public int CalculateShippingCost(Order order)
    {
        // some sort of database call needed to lookup pricing table and weight mappings
        return _weightMappingService.DeterminePrice(order);
    }
}

public class FedexShippingStrategy : IShippingStrategy()
{
    private readonly IZipCodePriceCalculator _zipCodePriceCalculator;

    public FedexShippingStrategy(IZipCodePriceCalculator zipCodePriceCalculator)
    {
        _zipCodePriceCalculator = zipCodePriceCalculator;
    }

    public int CalculateShippingCost(Order order)
    {
        // some sort of dynamic pricing based on zipcode
        // api call to a Fedex service to return dynamic price
        return _zipCodePriceService.CacluateShippingCost(order.OrderZipCode);
    }
}

The issue with the above is that each strategy requires additional and different services to perform the 'CalculateShippingCost' method. Do these interfaces/implementations need to be registered with the entry point (the Program class) and passed down through the constructors?

Are there other patterns that would be a better fit to accomplish the above scenario? Maybe something that Unity could handle specifically (http://ift.tt/2mmD7q1)?

I greatly appreciate any help or a nudge in the right direction.

Thanks, Andy

Drawing Spirograph designs

I am trying to draw spirograph designs (http://ift.tt/1cTOuLV) in Racket. I could manage following code but it is not working:

#lang racket

(require 2htdp/image
         2htdp/universe) 

(define img (rectangle 500 500 "solid" "white"))

(let* ((R 300)   ; outer circle radius
       (r 100)   ; inner circle radius
       (c 30)    ; distance of pen-tip from center of inner circle

       (l (/ c r))
       (k (/ r R))
       (imgfn
        (λ (t)
          (set! img (overlay/xy
                     img
                     (* R(+ (* (- 1 k) (cos (modulo t 360)))
                            (* l k (cos (/(* (- 1 k)
                                             (modulo t 360))
                                          k)))))
                     (* R(- (* (- 1 k) (sin (modulo t 360)))
                            (* l k (sin (/(* (- 1 k)
                                             (modulo t 360))
                                          k)))))
                     (circle 2 "solid" "blue")))
          img)))
  (animate imgfn)) 

Following diagram shows the distances that would affect the design:

enter image description here

Above code shows small circles for points but they do not draw a line, even if I have tried to reuse previous image. Moreover, the points are moving very fast while I would like the speed to be slowed down somewhat. Only after this we can see if it is following correct path or not.

Any help/suggestions will be appreciated.

Not GUID Entity ID generation while using CQRS pattern in microservices

I have a question about correct Entity ID generation while using CQRS pattern.

In my application I have Customer entity. I use microservices and Actor pattern for implementation: Azure Service Fabric Actor.

I have restriction - CustomerId should be unique across all the system(thanks cap) and it should be 5 digit number.

Common approaches for ID generation I met before:

  • Generate GUID in UI and pass already created GUID to API method.

Thats the approach I always used before, but I am pretty sure its not applicable in my current case since UI can not generate random 5 digit number which will be 100% unique.

  • Command returns Id from API method call

Ok, this approach is applicable in my case. But I use Actor pattern and all my actors live in different partitions on the server. That means creating unqiue ID is not a trivial task. This approach also violates CQRS pattern, but I think we can live with that since CQRS is not a silver bullet.

This goal can be achieved by using some proxy layer - for example new Actor - CustomersListActor, which implementation will contain list of all actors in the system with related Ids. That will help me generate new unique CustomerID.

But this approach have a big drawback - I have a bottleneck - CustomersListActor. So it kills all the benefits of microservices. Every POST call will have to pass through CustomersListActor. And its not multithreaded.

  • In a situation of DB-persisted systems there is a practice when we reserve batch of IDs from the DB and store them somewhere in memory. The purpose is to provide these reserved IDs while GetId request from client.

With microservices this approach looks like the previous one. We still need to take care of some Actor who works using one thread and stores all the info about existing Ids(or at least the MAX id).

I also read about approach of deviding Id to 2 pieces. GUID for storing data in persistance layer and Int ID for human-readable ID. But I dont like this approach beacuse I store two different unique IDs for one Entity. And this approach does not save me from creating same Actor with list of other actors.

So my main question is: What approach is widely used while working with microservices in case of CQRS and your EntityID is not GUID?

Java Regex to replace a pattern in a certain string

I want to replace a word with a trailing # in a string with the same word (# omitted)

example

#user should be replaced with user

Can someone help me?

Is there common approach to encapsulate xml data structure changes?

I'm working out a program module, that designed to get data as tree with strict structure. For storing it use a xml format.

But, just appeared situation when I need to do the same task with another data structure, that can be converted to previous one. And in future there is perspective that new data will have another structure too.

Is there any general solution for such a problem?

PS. For now, it's seemed to be good solution to make a module, that would get xslt stylesheet and xml and after that by use of xslt processor give me appretiate xml structured data.

Performance code of wrappering

Question: What is the performance cost of wrapping an object inside of another object? Both in RAM and CPU usage increase from calling the object directly.

Extra Details: I'm working on developing a framework that will wrapper code to isolate plugins from the core implementation of a program. The question keeps popping up in my head "What is the performance cost". I know it will be more than direct access to the code being wrapped. However, I can not seem to find any solid sources or data online to show exactly what results to expect. Which is an issue as I'm developing this to replace the implementation for roughly 40 projects. So when asked what level of overhead is expected in the update I need to have some data.

Also, in case anyone is unsure what I mean by wrapped code. It is the process in which an object is created using an interface that sends all method calls to an object stored in the object. This is done to hide the implementation of an object when the original object can not be modified or changed to include the interface. Below is an example of what I'm talking about.

public class WrapperObject implements WrapperInterface
{
    private SomeObjectClass theObject;

    public WrapperObject(SomeObjectClass theObject)
    {
        this.theObject = theObject;
    }

    public void method1()
    {
        theObject.method1();
    }

    public void method2()
    {
        theObject.method2("someData", 1);
    }
}

As well I do know about JIT in java and other optimization technics the JVM does. I'm asking what I can expect from the overhead of using a system like this for a large project. As I will be wrapping or converting just about everything before it gets to the plugin code. This includes methods that may be called a few 1000 times a second as well as methods only called once.

I will also be building prototypes in the next few days to test performance as well. I'm just looking for some design input to better understand what to expect. Rather than looking blindly at my code making guesses that waste time.

Grep two words with their subsequent words from a json file

I want to grep a combination of two words from a huge log file, the words are scattered and not in any particular order.

     Sample log :
    {"1a":"2017-01-28 00:00:00","2a":"sample","a":"12345","b":"2017-02-06","c":"2017-02-06T17:51:02.454-08:00","d":"Mozilla/5.0
    ; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1","e":"2017-02-06 
    ","f":"03","g":"example","h":"logA","i":"IFX","j":"a85","k":"12345678"},
{"1a":"2017-01-28 00:00:00","2a":"sample","a":"12345","b":"2017-02-06","c":"2017-02-06T17:51:02.454-08:00","d":"Mozilla/5.0
    ; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1","e":"2017-02-06 
    ","f":"03","g":"example","h":"logB","i":"IFX","j":"a85","k":"12345678"}

In this file, I want to grep "1a":"" and "h":"" which there should not be any duplicates

I tried using egrep this way but it gives the entire line :

egrep -oE '1a\|"h"' but this does not give the required output.

awk /pattern1/ && /pattern2/ filename #no use

Thanks for the help

Angular2 shared/core module in lazy

I have 4 feature modules which will be loaded lazy. Have multiple popups components, which is need for the feature modules. Currently i have created a shared module which will export these component and each feature module will import this shared module. The tradeoff for this kind of design is, the shared module will be included in all the feature bundles. The problem is some popup component is not needed in some feature module.

Any ideas?

How to solve double update cost to cache and remote database?

I am working on a web application caching big amount of data on front for better performance. The issue I am facing is that I need to update data in many ways and each update needs to be done on cache and on remote database which leads to double updating effort. I am asking for any best practice / design pattern to make this scenario easier to deal with.

I am using Angular 2 if this would change anything about the answer

mardi 21 février 2017

How do I use the SPA and Front Controller with in php?

For example, http://ift.tt/1fljiJ4

If you click another menu, url is in the form of a Front Controller, but Chrome's network tool will not redirecting the existing page.

example frontController.php

// require_once './index.php';

if ($_SERVER['REQUEST_URI'] == '/test1') {
  include 'test1.php';
} else if ($_SERVER['REQUEST_URI'] == '/tmp') {
  include 'tmp.php';
} else {
  include 'notfound.php';
}

always redirect index.php , I think it is natural.

How can I get it(SPA main file - index.*) to be called once?

What is best way to connect data from different services and use them with ng-model

I'm new to angular and to design some complicated things...

I have two services: phrasesService and translationsService, they stores two objects:

phrases = [ {text: "phrase1"}, {text: "phrase2"}, {text: "phrase3"} ]
    
translations = [ { language: "russian", phrases: ["phrase1", "phrase2", "phrase3"] }, { language: "hindi", phrases: ["phrase1", "phrase2, "phrase3"] }]

And I have methods to get translations:

getTranslationsInLang(lang) , that returns array of phrases in lang and getPhraseTranslation(lang, numPhrase) , that returns translation of one phrase

Now I want to display phrases and their translations in inputs (for editing):

<input class="form-control phrase-text" type="text" ng-model="phrase.text">
<input class="form-control translation-text" type="text" ng-model="????.translation">
  1. What is the best way to realize this, for store all data and display it for editing?
  2. And what should I use in ng-model for translation input?