jeudi 23 février 2017

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?