lundi 30 novembre 2015

how make a singleton on python?

please help fix code. i try make pattern singletone:

class Room:
    obj = None 

    def __new__(cls):          
        if cls.obj is None:               
            cls.obj = object.__new__(cls) 
        return cls.obj   

    def __init__(self, left_wall, right_wall, front_wall, back_wall):
        self.left_wall = left_wall
        self.right_wall = right_wall
        self.front_wall = front_wall
        self.back_wall = back_wall

    def __str__(self):
        return str(self.left_wall) + str(self.right_wall) + str(self.front_wall) + str(self.back_wall)


room_obj = Room(True, False, True, True)
print(room_obj)

room_obj2 = Room(True, False, False, True)
print(room_obj2)

print(room_obj is room_obj2)

after I run this code, the console get the following:

kalinin@kalinin ~/python/object2 $ python index.py
TrueFalseTrueTrue
TrueFalseFalseTrue
False

It should not create two objects

How to access third-party WebApi in DDD. I should place it which layer? [on hold]

There is a business rule. I want to access third-party WebApi and pass some parameters to get some message. So I do not know I should place these logic in which layer. Maybe Domain Service or infrastructure Layer? Please help me and give me some suggestions. I am very confuse.

Domain Driven Design with Entity Framework Model First

Regarding persistence of DomainModel using EntityFramework. I would like to validate following approach with experts in this area:

Leverage OnModelCreating to map or ignore navigation properties which are not needed. Unfortunately all these are specific to Code-First.

VS

Treat Model First POCO as DTO & using anti-corruption layer

We have huge investment in database designed using model first, in order to leverage DDD that leaves out only one path for us - leave POCO classes generated by designer alone & Domain classes separate. When ever needed do a manually mapping or use AutoMapper. Am I correct?

Secondly what would be best place to have this mapping, anti-corruption layer?

EDIT: We have > 250 tables in the schema, going through code-first I feel like losing the comprehension ability that designer providers, also model first I have complete authority once .SQL is generated. However in code first I have to live at the mercy of code-first migration to generate / update tables for me.

How to Replace a Long Switch Statement

Let's say I have a switch statement that looks like this:

MakeADecision(enum Option, object HandleThis) {
    switch(Option)
        case 1:
            callMethodA(HandleThis);
        case 2:
            callMethodB(HandleThis);
        case 3:
            callMethodC(HandleThis);
}

Each of the methods do something totally different and can't be consolidated in anyway. Meaning, it won't work to have a single method name with some overloads, etc. callMethodA() might be a call to an external web service, while callMethodB() may just log the object in our own database. Also, this switch statement WILL grow in the future, and I'd rather not have to keep adding cases each time we need to expand.

I'm thinking there must be a pattern to handle this, just not sure what it is. Any ideas?

Chain of Responsibility - pass the request through all the chains

I browsed the web but I couldn't find an answer to my question...

Lets say I have 3 chains. I want the request to pass all 3 chains (it doesn't matter if the chain can handle the request or not). Is it possible to use CoR pattern for this problem?

To explain it better - I have a list that has to pass through several sets of rules. If it passes the 1st rule, list stays the same. Then it goes on to the 2nd rule, and 2nd rule changes a list. The changed list goes to the 3rd rule, it passes and the altered list is saved. Chains

Is there any standard way to transform object to different object?

I'm having a special case where I have implemented builder pattern. One of the variable is of type ExternalClassA, Where as the parameter passed to builder is of type InternalClassA. Currently I have used a method something like below:

Class Parent {
   String variableX;
   int variableY;
   ExternalZ variableZ;
   public static builder {
   ....
   ExternalZ varz;
   /* .. builder logic */
   private builder withExternalZ(InternalZ internalZ) { //This is the transform method I'm using currently
   this.variableZ.getSomeObject().setX(this.internalZ.getSomeObject().getX()); //Similar kind of lines making my transform method look ugly
    }
}

Is there any way to make my withExternalZ method look simpler? Currently I'm out Mapper pattern and Java8 Function (As explained in http://ift.tt/17MYsBW).

If anyone has better and simpler approach, kindly share.

Dependency Injection and IoC practices in a inherently tight coupling design

What's the best practice when dealing with a situation like the following (simplified symbolic analogous case, not asking for a particular implementation solution):

Imagine I want to create a custom class that represents my physical Calendar at my office desktop. It can be translated in Java as a GregorianCalendar(myCustomZone).

So, I create a class such as:

 class MyOfficeCalendar extends GregorianCalendar{
   public MyOfficeCalendar(){
        super(new SimpleTimeZone(...));
   }
 }

In these cases, code reviewers would say that instantiation in the constructor is a bad idea. But if I inject the SimpleTimeZone dependency into the constructor this seems to me like error prone, since my dependency only be instantiated in a desired way. I want the control at that scope, not exposing the possibility of erroneous injection. I mean, that certain instantiation is part of my caller class behaviour or paradigm. The definition of MYOfficeCalendar is precisely a GregorianCalendar working with this particular custom TimeZone instance.

So what is the best design usually in those cases?

  • Force MyCalendar to be flexible enough to be incoherent and rely on a correct IoC container xml or user

  • Instantiate in the constructor the absolute desired dependence

  • Manage the Whole thing without my convenient OOP class (I lie to adhere to the SingleResponsabilityPrinciple as muc as I can)

  • Change the whole architecture ?

Calling function before objects are created in a class

Basically, I have one class that owns another object:

class A()
{
    A() { initSystems() };
    void initSystems();
    B b;
}

class B()
{
    B() { //Does stuff that requires 'initSystems()' to be called before }
}

and for 'B' to function, the init systems function needs to be called in A. Is there any 'nice' way to work around this? Like creating the 'B' object later or something?

Which design pattern could be used for a shape editor? Visitor pattern in use for now

In hindsight of my question from earlier about the usage of the visitor pattern for a shape editor I came to the conclusion that I have to break the design rules of it.
Mainly because I need to update my Shape fields, so essentially I need to pass arguments back to the visitor.

Right now I am population the UI fields with the variables of the ShapeObject.

public class Editor implements ShapeVisitor{

    private Shape shape;

    @Override
    public Foo visit(CircleObject circle) {
          // populate fields
          shape = new CircleObject();
    }

    @Override
    public void visit(RectangleObject rectangle) {
          // populate fields
           shape = new RectangleObject();
    }


    public void setComponent(JsonArray arguments){
      Element element = getFromJson(arguments);
      element.getAttrs().accept(this);
    }
}

Somewhere in my code I have a Save Button which should update the ShapeObject.

        @Override
        public void buttonClick(ClickEvent event) {
                    element.setAttrs(shape);    
        }

Basically what I am doing is that I create a new Instance of a ShapeObject and update the fields there. Then I pass it to the element back via element.setAttrs(shape).


Essentially I would not need the visitor pattern at all, because I could achieve the same with the instanceof operator in the setComponent method. I am trying my best to avoid this operator, because in the near future I will have way more ShapeObjects then these two. I am not really sure if this is the approach I should take or maybe there is a even better one for a custom shape editor.

Best regards.

Refactoring or using Design Pattern on Switch-Case-Smell

Since I am currently dealing with Design Patterns and Refactoring some Legacy Code to write some JUnit-Tests, I am looking through my project, where I could apply it.

I found one method in one class, where I have a very long switch-case-statement. Of course this is a horrible scenario for unit-testing, since I need to create a test for every statement.

Now I thought about applying the Strategypattern. But the problem is, I have 30 different cases. That would mean I would have to create 30 classes. Is this advised, or should I consider some other way of refactoring? Morover the switch case is inside two for-loop, since it's an Excel-table.

Here is an excerpt of my method:

switch (column) {
    case CASE1:
        excelUtil.setCell(row, col++, item.getSomething(), styles[0]);
        break;
    case CASE2:
        excelUtil.setCell(row, col++, order.getSomething(), styles[0]);
        break;
    case CASE3:
        excelUtil.setCell(row, col++, order.getSomethingElse(), styles[0]);
        break;
    case CASE4:
        if (!StringUtils.isEmpty(order.getSomething())) {
            try {
                //do something before setting cell
                excelUtil.setCell(row, col++, soldToName, styles[0]);
            }
            catch (final Exception e) {
                excelUtil.setCell(row, col++, "", styles[0]);
            }
        }
        else {
            excelUtil.setCell(row, col++, "", styles[0]);
        }
        break; //.. and so on

Architecture design

I have the following scenario(the analogy is not accurate):

enter image description here

The specific implementation of MoveForward is implemented in "Dogfeature" and "SnakeFeature".

Dog snoopie = new Dog();
Snake kaa  = new snake();

snoopie.MoveForward();
kaa.MoveForward();

When I call snoopie.MoveForward() I want the MoveForward implemented in DogFeature to be executed.

I dont see this problem as a polymorphism or is it?

How do i solve this? any design patterns?

The language that i'm trying is C#.

Which architecture would be best to use (request or component based)

We have to bring up report which has the following use-cases:

  • Summarizing daily sales report which includes several charts thereby includes several Db server hits for bringing data for report page
  • the UI components must be thin and easily customizable and usable.
  • Updating several UI components based on search criteria
  • Above all the report has to be shown in 4-5seconds.
  • Also there has be security across the web application.
  • Avoid the plumbing work asap.

I have gone through these links Java Component based vs Request based frameworks and Design Patterns web based applications

and confused which framework (component or request based framework ) suits the best.

Regards

Kris

dimanche 29 novembre 2015

Extending Class via Multiple Private Inheritance - Is this a thing?

I'm trying to encapsulate existing functionality in a wide swathe of classes so it can be uniformly modified (e.g. mutexed, optimized, logged, etc.) For some reason, I've gotten it into my head that (multiple) private inheritance is the way to go, but I can't find what led me to that conclusion.

The question is: what is the name for what I am trying to do, and where I can see it done right?

What I think this isn't:

  • Decorator: All the descriptions I see for this pattern wrap a class to provide extra methods as viewed from the outside. I want to provide functionality to the inside (extract existing as well as add additional.)
  • Interface: This is close, because the functionality has a well-defined interface (and one I would like to mock for testing.) But again this pattern deals with the view from the outside.

I'm also open to alternatives, but the jackpot here is finding an article on it written by someone much smarter than me (a la Alexandrescu, Meyers, Sutter, etc.)

Example code:

// Original code, this stuff is all over
class SprinkledFunctionality
{
  void doSomething()
  {
    ...
    int id = 42;
    Db* pDb = Db::getDbInstance(); // This should be a reference or have a ptr check IRL
    Thing* pThing = pDb->getAThing(id);
    ...
  }
}

// The desired functionality has been extracted into a method, so that's good
class ExtractedFunctionality
{
  void doSomething()
  {
    ...
    int id = 42;
    Thing* pThing = getAThing(id);
    ...
  }

protected:
  Thing* getAThing(int id)
  {
    Db* pDb = Db::getDbInstance();
    return pDb->getAThing(id);
  }
}

// What I'm trying to do, or want to emulate
class InheritedFunctionality : private DbAccessor
{
  void doSomething()
  {
    ...
    int id = 42;
    Thing* pThing = getAThing(id);
    ...
  }
}

// Now modifying this affects everyone who accesses the DB, which is even better
class DbAccessor
{
public:
  Thing* getAThing(int id)
  {
    // Mutexing the DB access here would save a lot of effort and can't be forgotten
    std::cout << "Getting thing #" << id << std::endl; // Logging is easier
    Db* pDb = Db::getDbInstance(); // This can now be a ptr check in one place instead of 100+
    return = pDb->getAThing(id);
  }
}

Proper Architecture for Application-Level Collections

Given an application-wide collection of objects, and many unrelated classes that need frequent access to these objects, what is the best way to provide said access?

Example:

// Object A, stored in collections, used to do useful things
class A
{
  ...
public:
  QString property(const QString& propertyName) {return m_properties.value(propertyName);}

protected:
  QHash<QString,QString> m_properties;
}

// Collection class, contains methods to:
// - Access members of collections
// - Add/Remove members from collection
class GlobalCollection
{
public:
  // Accessors to collection/collection members
  static A* getAs() {return aHash;}
  static QHash<QString,A*> getAByKey(const QString& key) {return aHash.value(key);}
  static QList<A*> getAsMatchingCriteria(const QString& property, const QString& value)
  {
    QHash<A*> subsetOfA;

    foreach(A* pA, aHash.values())
    {
      if (pA->property(property) == value)
        subsetOfA << pA;
    }

    return subsetOfA;
  }

protected:
  QHash<QString,A*> aHash;
}

// Example client class that uses A's to do its job
class Client
{
public:
  // This is tied to a button click, and is executed during run-time at the user's whim
  void doSomethingNonTrivialWithAs()
  {
    // Get A* list based on criteria, e.g. "color" == "green"
    QList<A*> asWeCareAbout = ???;

    // Draw all the "green" A's in a circle holding hands
    foreach(A* pA, asWeCareAbout)
    {
      // Draw a graphical representation of pA
      // If pA has "shape" == "square", get a list of all the non-"green" "square" A's and draw them looking on jealously from the shadows
      // Else if pA has "shape" == "circle", draw the non-"green" "circles" cheering it on
    }
  }
}

Assumptions:

  • Preference has been given to small, lightweight classes, so client objects are legion
  • A client object could be several layers deep inside a "peer" of GlobalCollection, and intermediate layers have no dependency on A* or GlobalCollection
  • This is currently implemented as a singleton

Design Requirements and Problems with Other Solutions:

  • Dependency injection looks like an unreasonable burden on calling code (given the layering,) and sacrifices too much clarity for my liking
  • I'm not opposed to a static class instead of a singleton, but that doesn't feel much better than a singleton
  • Code that modifies the collection is isolated, so I'm not worried about that at this time
  • The solution needs to promote thread-safety in GlobalCollection and within A's (given that multiple clients could end up working on the same A*.) This is currently being achieved with one mutex and overzealous locking, in large part because it is so difficult to manage access to the A's.
  • I'm trying to iterate towards testability, and the current design makes nearly every test of a client require properly setting up the GlobalCollection first.
  • In production code we have multiple GlobalCollections (for A, B, C, etc.,) so template solutions are welcome.

While I'm refactoring legacy code to do this, my main concern is designing the right architecture in the first place. This seems like a very common logical concept, but all the solutions I see fail to address some important aspect of using it for production or have a glaring flaw/tradeoff. Maybe I'm being too picky, but in my experience the right tool for the job has zero drawbacks in that context.

SOLID Principle In Laravel with Repository Pattern

I have some confusion about use of Controller with Repository Pattern while maintaining SOLID Principle. Consider, I have two types of Quotations

  1. Commercial Quotation
  2. Private Quotation

And there is a high chance of new types of quotations in future. Each Quotations has different fields, business logics yet they share many common functions. So I created a QuotationInterface

Quotation Inteface

interface QuotationInterface
{   
    public function save(array $data);

}

Quotation class that implement the interface

class CommercialQuotation implements QuotationInterface
{   
    public function(array $data)
    {
        // save commercial quotation
    }
}

class PrivateQuotation implements QuotationInterface
{   
    public function(array $data)
    {
    // save Private quotation
    }
}

Quotation Repository

class QuotationRepository 
{
    public function save(array $data, QuotationInterface $quotation)
    {
        $quotation->save($data);
    }
}

QotationController

public function store(Resource $resource)
{

    $inputs = $resource->all();

    /**
    *  Clearly here Open/Close Principle is broken
    */

    if ($inputs['type'] == 'private'){

           $quotation = new PrivateQuotation;;

    }else if($inputs['type'] == 'commercial'){

           $quotation = new CommercialQuotation;

    }

    $this->repo->save($inputs, $quotation);
}

Here in my QuotationController, it is clearly violating Open/Close Principle..

Is it a good idea to Create a Controller for each type of quotation (might be 10+ some day, who know?) to avoid the OCP violation or my design is just wrong? Any suggestion, design change tips, resource are welcome.

NOTE: My Quotation Controller will have many other functions except the save only.

C# Design pattern for Workflow like Application

We are trying to develop an application , that handles few dozens of small actions, and combines them into the single so called "WorkFlow".

Workflow can be set of any actions on the clients machine, can be any action : ReadingXML file -> Put To DataBase -> Change Value in Registry, etc.

samedi 28 novembre 2015

Best design patterns for refactoring code without breaking other parts

I have some PHP code from an application that was written using Laravel. One of the modules was written quite poorly. The controller of this module has a whole bunch of reporting functions which uses the functions defined inside the model object to fetch data. And the functions inside the model object are super messy.

Following is a list of some of the functions from the controller (ReportController.php) and the model (Report.php)(I'm only giving names of functions and no implementations as my question is design related)

Functions from ReportController.php

questionAnswersReportPdf()
fetchStudentAnswerReportDetail()
studentAnswersReport()
wholeClassScoreReportGradebookCSV()
wholeClassScoreReportCSV()
wholeClassScoreReportGradebook()
formativeWholeClassScoreReportGradebookPdf()
wholeClassScoreReport()
fetchWholeClassScoreReport()
fetchCurriculumAnalysisReportData()
curriculumAnalysisReportCSV()
curriculumAnalysisReportPdf()
studentAnswersReportCSV()
fetchStudentScoreReportStudents()

Functions from Report.php

getWholeClassScoreReportData
getReportsByFilters
reportMeta
fetchCurriculumAnalysisReportData
fetchCurriculumAnalysisReportGraphData
fetchCurriculumAnalysisReportUsersData
fetchTestHistoryClassAveragesData
fetchAllTestHistoryClassAveragesData
fetchAllTestHistoryClassAveragesDataCsv
fetchHistoryClassAveragesDataCsv
fetchHistoryClassAveragesGraphData

The business logic has been written in quite a messy way also. Some parts of it are in the controller while other parts are in the model object.

I have 2 specific questions

a) I have an ongoing goal of reducing code complexity and optimizing code structure. How can I leverage common OOP design patterns to ensure altering the code in any given report does not negatively affect the other reports? I specifically want to clean up the code for some critical reports first but want to ensure that by doing this none of the other reports will break.

b) The reporting module is relatively static in definition and unlikely to change over time. The majority of reports generated by the application involve nested sub-queries as well as standard grouping & filtering options. Most of these SQL queries have been hosed within the functions of the model object and contain some really complex joins. Without spending time evaluating the database structure or table indices, which solution architecture techniques would you recommend for scaling the report functionality to ensure optimized performance? Below is a snippet of one of the SQL queries

$sql = 'SELECT "Parent"."Id", "Parent"."ParentId", "Parent"."Name" as systemStandardName, string_agg(DISTINCT((("SubsectionQuestions"."QuestionSerial"))::text) , \', \') AS "quesions", count(DISTINCT("SubsectionQuestions"."QuestionId")) AS "totalQuestions", case when sum("SQUA"."attemptedUsers")::float > 0 then (COALESCE(round(( ( sum(("SQUA"."totalCorrectAnswers"))::float / sum("SQUA"."attemptedUsers")::float ) *100 )::numeric),0)) else 0 end as classacuracy, case when sum("SQUA"."attemptedUsers")::float > 0 then (COALESCE((round(((1 - ( ( sum(("SQUA"."totalCorrectAnswers"))::float / sum("SQUA"."attemptedUsers")::float ) ) )::float * count(DISTINCT("SubsectionQuestions"."QuestionId")))::numeric,1)),0)) else 0 end as pgain FROM "'.$gainCategoryTable.'" as "Parent" '.$resourceTableJoin.' INNER JOIN "SubsectionQuestions" ON "SubsectionQuestions"."QuestionId" = "resourceTable"."ResourceId" INNER JOIN "Subsections" ON "Subsections"."Id" = "SubsectionQuestions"."SubsectionId" LEFT Join ( Select "SubsectionQuestionId", count(distinct case when "IsCorrect" = \'Yes\' then CONCAT ("UserId", \' \', "SubsectionQuestionId") else null end) AS "totalCorrectAnswers" , count(distinct CONCAT ("UserId", \' \', "SubsectionQuestionId")) AS "attemptedUsers" From "SubsectionQuestionUserAnswers"'; if(!empty($selectedUserIdsArr)){ $sql .= ' where "UserId" IN (' .implode (",", $selectedUserIdsArr).')' ; }else { $sql .= ' where "UserId" IN (' .implode (",", $assignmentUsers).')' ; }

              $sql .= ' AND "AssessmentAssignmentId" = '.$assignmentId.' AND "SubsectionQuestionId" IN ('.implode(",", $subsectionQuestions).') Group by "SubsectionQuestionId"
              ) as "SQUA" on "SQUA"."SubsectionQuestionId" = "SubsectionQuestions"."Id"
              INNER JOIN "AssessmentAssignment"
              ON "AssessmentAssignment"."assessmentId" = "Subsections"."AssessmentId"
              INNER JOIN "AssessmentAssignmentUsers"
              ON "AssessmentAssignmentUsers"."AssignmentId" = "AssessmentAssignment"."Id"
              AND "AssessmentAssignmentUsers"."Type" = \'User\'
                          '.$conditaionlJoin.'
              WHERE      "Parent"."Id" IN ('.implode(',', $ssLeaf).') 
                          '.$conditionalWhere.'
              GROUP BY   "Parent"."Id",
                         "Parent"."ParentId",
                         "Parent"."Name"
              '.$sorter;

    $results = DB::select(DB::raw($sql));

PHP PDO How to keep just one MYSQL connection

I'd like to know a better or best way to initialize PDO mysql connection once and use it. I actually implemented singleton design pattern to PDO and it works just fine, I'm happy with it, but anyway I found a lot of discussions going on stackoverflow about singleton design pattern and how bad it really is, that it's anti-pattern, bad for testing and etc... To be honest I don't know other ways to make the same functionality without using singleton and as long as it works I don't care, the project where I'm using singleton pattern is really small and probably will never be extended. Should I really stop using singleton pattern in PHP everywhere? I would be really happy if someone out here could explain me what are alternatives to singleton pattern if I want let's say to keep the same MYSQL connection in whole application.

User profile public and private profile user design patter in AngularJS

I have the next problem.

In the platform I am building there are users that you can follow or unfollow. Also, if you are looking at your own profile, you can edit it (instead of following it).

Currently I have one state /profile/:id that renders the user profile with angularjs

I have one template _profile.html and a controller profileCrtl. The controller is responsible to check if the profile is authenticated and therefore to set different variables to show different html tags. For example if the user is seeing his own profile, we are not going to show the follow button. Instead, he/she will see an edit button to allow the user to edit his/her profile.

The problem with this approach is that porfileCtrl and _profile.html are responsible to manage the public profile user view and the private profile view and I think it is not a good design pattern.

I am considering three solutions to improve my code:

  1. To use two templates, _publicProfile and _privateProfile and keep only one controller profileCtrl. We will have two states.

  2. To use two templates, _publicProfile and _privateProfile and to have two controllers. profilePublicCtrl and profilePrivateCtrl. (I feel this may be the best solution). We will have two states.

  3. To have only one state and change templateUrl dinamically if user is the authenticated user or a public user.

What do you think is the best solution? Do you have any alternative to the ones considered above? When and where in the code should I check if the profile the user is viewing is a public profile or the user’s profile?

I have already looked up a lot of answers online and there seems to be a lot of opinions and I find difficult to know what is the best design pattern. I appreciate your input. Thank you.

vendredi 27 novembre 2015

How to model similar but not exact data in object oriented paradigm?

I have an interface and two data sources that populate concrete instances of objects that implement the interface. The interface exposes methods that only one of the two instances can satisfy in a meaningful way.

public interface IFoo {
    public int getValueA();
    public int getValueB();
}

public FooFromFile implements IFoo {
    int a;
    int b;
    ...
    public int getValueA() {
        return a;
    }
    public int getValueB() {
        return b;
    }
}

public FooFromNetwork implements IFoo {
    int a;
    ...
    public int getValueA() {
        return a;
    }
    public int getValueB() {
        return 0; // return 0 because FooFromNetwork never gets value b.
    }
}

Every code base I've worked on has code like this and I find it usually stems from a desire to apply 'is-a' relationships where something else may be more appropriate. I have some time to refactor the code base on which I am currently working. What would be some good modeling solutions for situations like this? The actual code is much more complicated than this but solving the toy issue here, with a robust pattern that scales, would go a long way.

is it possible to use an interface to speak to another class in java?

suppose i have Class A and class B and an interface called Message

public interface Message{
   public void sendMessage();
}

public class A implements Message{
   @Override
    public void sendMessage(){
      //call the sendMessage() in class B.
    }
}

public class B implements Message{
    @Override
     public void sendMessage(){
       System.out.println("Hola Stack!");
      }

 }

without a direct reference to class B can i somehow invoke the sendMessage() method in class B from class A?

What would be a suitable database schema for the following scenario?

I have newsid and keyword. Now i have a mapping of keywords to newsid's in a many to many fashion. for eg

**keyword**     **Newsid**
FIFA           221,123,133
Stack          12,2
dragon         23,577,33

Also i have a mapping that should store priority for each keywords for a particular user for e.g. Lets suppose user "mark" has the following keywords with priority for him:-

**Keyword**     **priority**
apple           0.5
jeff jones      0.9 
sugar           0.3



Use cases 
1)to get all the news id that are mapped to a specific keyword 
2)to get all the keyword that are mapped to a specific news id
3)To increase the value of priority for keyword x by value y for user z
4)Retrieve the list of all keywords
5)add a new keyword r for user s with priority f

Note that keywords are not predetermined and can increase to any number,So is the case with News and users.

Flawed solution thus far I have a database with the following structure

Table -News(newsid,story)
Table -Keyword(keyword,[list_of_news_id seprated by comma])
Table -User_preference(userid,[(keyword1 -priority1),(keyword2-priority2)...])
Table -User(userid,name)

The problem with my solution is that to query keyword mapped to a specific id i need to process all tuples of Keyword table.

Moreover to update the priority of a certain keyword for a certain user , I would have to first retrieve all keyword priority pair for him(since they are in a common column) and then select my desired keyword and manually change it using some text processing and replace the value with new one.

Please suggest me a suitable database schema that fulfills all my use case requirements and that doesn't need to alter the database schema each time with addition of new keywords/news/users.

Thanks in advance.

How to design a flexible document model for a CMS?

I am facing a modelling challenge, which I hope you can provide input on. I will present an idealized version of the problem below:

I want to represent documents (pages) in a CMS. Something like this:

Page 
\-*-> Revision 
      \---> Document
            \-*-> Section
                  \-*-> Paragraph
      \---> User

The persistence layer is document oriented. Let's say every revision is stored as a JSON blob. Serialization is required for persistence and a REST API. Serialization/deserialization should be a simple operation, something like serialize( revision ) -> blob and deserialize( blob ) -> revision.

So far so simple. However, the CMS should allow plugins that can associate additional information with each bit of the document model. E.g.:

  • A social plugin would maintain carma points for each user
  • A comment plugin would allow reader comments on every page
  • A workflow plugin would associate a state with each page
  • A review plugin would allow annotations on each paragraph
  • A chart plugin could associate a chart with a paragraph

It should be possible to mix and match such plugins. Each plugin will have to provides at least a mechanism to serialize, unserialize, and display the relevant information (plus an API and UI to interact with it, but that's not central here, I think).

As an additional constraint, I want 3rd parties to fetch the (JSON) representation of a document via the REST API, and conveniently use the data within, ideally using the same deserialization logic that I am using internally.

The question is: how should I design the core model, the classes that represent Page, Revision, Document, Section, and Paragraph? How is that extra info from the plugins associated with the respective parts of the core model? How do plugins integrate their logic for serializing/unserializing/rendering the content with the standard interfaces for these tasks?

PS: I'm not going to write yet another CMS, and I'm not interested in using an existing CMS. The above is an idealized problem, intended to allow discussion of design principles.

Factory of factories?

I have concrete factory classes which implement MyFactory interface. I want to get concrete factory objects based on parameter. How to do this?

One way is to create factory of factories[FoF], and FoF would be parameterized factory.

Is there any more elegant way to do this?

This is purely intellectual exercise, I am not facing any problem in my project.

Good Java Design pattern/implementation approach suggestion for the below case.

I have the question regarding the code snippet below.

interface Component{
    boolean isRelevant();
}
public abstract class AbstractComponent implements Component {
    String componentType;
    List<String> data;
    public AbstractComponent(String componentType, List<String> data) {
        //assign values. 
    }
}
class ComponentA implements Component {
    //Constructor with super method to pass type and data to parent class. 
    public boolean isRelevant() {
        //Use data to check relevance. 
    }
} and so on components. 

//Main program to Test 
List<Component> components; //Initialize all Components with type and data.Ex:  new Component("CompA", Data);

Iterate through the Component and run isRelevance over components.

for each component {
    boolean flag = comp.isRelevant()
    //HOW DO I Check Component Type here that need to be used in next section as i explained?
}

Secondly based on the combination of Components with true/false, we will arrive with name. Ex: CompA is relevant, B is relevant and C is not. ===> "Good" CompA is not relevant, B is relevant and C is not. ===> "Better" I was thinking of creating a Map with 1/0 bit flags combination and assigning the name. Say "110" => Good. Can i have some suggestions on giving a better design/implementation approach for this?

Better way to ensure a method logic executed once without boolean flag

This is a way to execute Dosomething logic once using flag. (C# code and Update is always called once per frame.)
And it's not so complicated, simple, very plain and well used way.

class Monster {
    bool isCalled = false;
    float energy = 0.0f;

    void Update()
    {
        energy += Random.Range(0f, 1f);
        if((isCalled == false) && (energy>100.0f))
        {
            isCalled = true;
            DoSomething();
        }
    }

    void DoSomething(){}
}

But, I think the management of boolean flag is a kind of tiresome task.
So I am trying to find better alternatives.

Is there any better or elegant way to do this (executing Dosomething once) without boolean flag?
For example, another design pattern's way, etc.

jeudi 26 novembre 2015

javascript pattern for generic transport functionality

In case my javascript library needs to support multiple underlying transport methods but expose a consistent interface for the applications, then what would be a good design pattern? Multiple transports could include HTTP, websocket etc. Is there any any pattern which can abstract all this and provide a consistent interface?

Which "Gang of Four" design pattern is right for this situation?

I'm creating a Django app and I want to be able to communicate with my users via either email or text message. They would choose their preferred mode of communication through their preferences settings. Would it make any sense to use the "template" or "strategy" design pattern to implement this feature? This seems like the type of situation in which a design pattern would be appropriate.

Thanks.

observer pattern with decorator pattern

I am trying to implement a game log observer that that shows dynamically selected actions taken in selected players/phases of a game. I am also trying to implement a decorator pattern to enable dynamic toggling of logging for each player's action or game phase.

For example, I can select to view logs for only 1 player or all players. Or just one phase or all phases (risk game: reinforce, attack, fortification phases).

This is where I am stuck. I have no idea where to start. I understand the decorator pattern and the observer somewhat but don't know how to implement this. The way I figured it was that the decorator pattern allows you to make the choices/actions you want and its "results" are added to the observer. Is that right? Any ideas to point me in the right direction would be appreciated!

Syntax highlighting using JTextPane and DefaultStyledDocument

As in the topic, I want to create text pane containing highlighted code. But I have no idea how to create abstract class, which will be used to support multiple programming languages (like Notepad++). Or should I use interface?

public abstract MyAbstractDocument extends DefaultStyledDocument
{
    private AttributeSet[] attributes;
    private String[] keywords;
    /* getters and abstract setters */ 
}

I'm not sure if the interface will be easier here...

    public interface MyDocumentInterface
    {
        /* getters and setters */
        public abstract void recolor(StyledDocument doc); // support
        // for coloring syntax
    }

I want to use abstract factory to detect (by file extension) which document should be loaded. And one more question - how to color only last changes? Should I use buffer storing recent changes?

Design solutions for fragments and asynchronous processing in Android

I struggled with some issues about design complex tasks with fragments use. Fragments and asynchronous are quite new for me, so I think it will be better to describe my app.

Application App works with GitHub API and has two screens: list of repositories and details about selected one. For retrieving data from json I use Retrofit and store it in SQLite. Little remark As I understood Retrofit can be used asynchronously but in case of additional work with DB it is better to use asynchronous for operations under DB also. In my case I'm checking internet connection: in case of absence I load data from DB. Otherwise I upgrade DB and then use it. Now I want to add fragments for different screen density support( usual master - detail workflow).

And my questions are

Where is the better place to run async tasks? Is it a right solution to make it in activity and then pass result to fragments?

What is the better solution for asynchronous processing? As I understood from my search about that, AsyncTask is deprecated but the easiest solution.

JS patterns with closures and performance

I have a doubt about JS patterns and performance, after read "Javascript: The good parts" by Douglas Crockford you an idea of how Closures works, the first in mind it's to write code like this

(function(){
    "use strict";

    var OpenSloth = {};

    OpenSloth.someFunction = function () {...};

    OpenSloth.someOtherFunction = function () {...};

    window.OpenSloth;
})();

But I read latter a book named "High Performance Javascript" by Nicholas C. Zakas (Also O'Reilly) and they say from the page 24 to 25:

Closures are one of the most powerful aspects of Javascript, allowing a function to access data outside of its local scope. The use of cloasures has been popularized through the writings of Douglas Crockford and is now ubiquitous in most complex web aplications. There is, however, a performance impact associated with using cloasures...

...Since the closure's [[Scope]] property cointains references to the same objects as the execution context's scope chain, there is a side effect. Typically, a function's activation object is destroyed when the execution context is destroyed. When there's a cloasure involved, through, the activation object isn't destroyed, because a reference still exists in the closure's [[Scope]] property. This means that cloasures require more memory overhead in a script than a nonclosure function...

High Performance JavaScript, by Nicholas C/ Zakas. Copyright 2010 Yahoo!, Inc, 978-0-596-80279-0."

After that I want to reduce closures as far as I can, then I came up with this solution:

var OpenSloth = {};

OpenSloth._someFunction = function () {
    "use strict";

    ...
};

OpenSloth._someOtherFunction = function () {
    "use strict";

    ...
};

But I want to know whats the conventions about it, I'm writing bad code with this second option? and why? it is an anti-pattern?

Thanks for your time.

Java distributed tasks

I am building system which should be consisted of 3 servers and same Java (Spring mvc) service would be running on all 3 of them. Service will be able to do 3 categories of tasks, i.e. A, B and C.

What I want is to make each service on servers perform only one category while communicating with other server. If one server dies, remaining servers should negotiate and only one of them should take category.

Example: Server 1 - Service does A Server 2 - Service does B Server 3 - Service does C

Server 2 Dies

Server 1 and Server 3 negotiate

Server 1 - Service does A and B Server 3 - Service does C

If server 2 returns to normal state it should take category from Server 1 (A or B)

Is there any pattern, architecture, technology, link that could help me solve this?

Initialize factory method

Snippet of my object creation:

object = function ()
{
  var private = 'Yes.';

  var pub = {
    sayHello: function () {
      return isThisRealLife();
    }
  }

  function isThisRealLife() {
    return private + ' ' + 'Hello world!';
  }

  return pub;
}

What would be the best solution (minor error-prone) to initialize this?

Ideias:

  • Create a init method in pub -> object().init('foobar').
  • object = function (myVar) -> object('foobar').
  • Make object a IIFE with init method -> object.init('foobar').

Java creating patterns

I have 7 classes that extends one parent abstract class. Also I have 7 classes that match first classes. I want to create one object of second classes depending on class first object. Which pattern I should use. I think about factory, but sometimes I need to add new classes and there are many of factories. So when I want to add new class I have to add it to all factories.

Sanks for any suggestions.

How to create objects of either of two types implementing the same method using the DRY principle

I'm not very good at CS domain language, so I hope I can make myself understood.

I'm looking for a DRY way to create objects of on of two types based on a boolean flag. Both types have one method each - differently named - which implements the same logic. This logic I'd like to implement only once (think of an abstract super class here, which won't work in this case though, I think).

Example

To be more concrete, consider this. There are two classes (in my case one inheriting from org.eclipse.core.runtime.jobs.Job and one inheriting org.eclipse.ui.progress.UIJob (which itself extends org.eclipse.core.runtime.jobs.Job)).

Both implement a certain logic (the same!) in a run-type method. For the class extending Job, this method is called run(IProgressMonitor m), for the one extending UIJob this method is called runInUIThread(IProgressMonitor m).

I want to be able to

  1. Implement the logic only once (DRY!), and for example have both run() and runInUIThread simply call something like super.run(). But because in Java classes cannot extend more than one class, I cannot do something like MyUIJob extends UIJob, MyAbstractJob where MyAbstractJob implements abstractRun(), and MyUIJob#runInUIThread(){ super.abstractRun() }.
  2. Start either job (MyJob and MyUIJob) from the same method (say, in a handler class), depending on, for example, a flag boolean isUIJob.

I've had a brief look at design patterns such as "AbstractFactory" and "Prototype", but these don't seem to work for my case as either would still need "double extension inheritance". (Or am I wrong?)

Hence the question: How can I implement the above in Java?

javascript module dependency implementation

JS beginner here, trying to implement JS library/sdk. Have read through the common patterns and planning to use revealing module pattern as of now. For context, lets take an example. We have a library and people can rent books from library. So the library will expose 2 objects to application - library and rented_book. For simplicity, lets say this library does not maintain list of available books but just rented books.

Now I will create a file called library.js and put the complete module for library object in it. And create another module book.js and code for the same in it. Now my doubts are

  1. How do I create the relationship between these two objects. When a user wants to rent a book, should I do a new on the book object and create it
  2. How do I make sure that the book module is loaded before the library object?

Basically, I am confused on how to create a library in this way. Any links to stuff that explain this will help a lot.

Best way to use shared components in Chain of Responsibility pattern

I have a problem with Chain of Responsibility pattern. All handlers implements this class:

/// <summary>
/// Chain of Responsibility pattern
/// </summary>
abstract public class ChainHandler
{
    protected LogWrapper Log;
    protected ChainHandler successor;

    /// <summary>
    /// SetSuccessor
    /// </summary>
    private void SetSuccessor(ChainHandler successor)
    {
       this.successor = successor;
    }

    protected oAPI NotImplemented
    {
        get { return new oAPI(HTTPCodes.NotImplemented); }
    }

    /// <summary>
    /// Set Successor to the end of chain
    /// </summary>
    /// <param name="successor">Handler</param>
    public void Add(ChainHandler successor)
    {
        if (this.successor == null) SetSuccessor(successor);
        else
        {
            this.successor.Add(successor);
        }
    }
    protected oAPI ReferToSuccessor (iAPI request)
    {
        if (successor != null) return successor.HandleRequest(request);
        return NotImplemented;
    }
    /// <summary>
    /// output API builder
    /// </summary>
    /// <param name="code">HTTP code</param>
    /// <returns></returns>
    protected oAPI RB(HTTPCodes code, string messsage = null, string data = null, bool hasError = false)
    {
        return new oAPI(Shared.User, code, message) { Data = data, HasError = hasError };
    }
    /// <summary>
    /// Serializer (JSON)
    /// </summary>
    public Func<object, string> Serializer { get; set; }
    /// <summary>
    /// Handle request
    /// </summary>
    /// <param name="request">request</param>
    /// <returns>result</returns>
    public abstract oAPI HandleRequest(iAPI request);
}

Then I implement DocHandler

public class DocHandler:ChainHandler
    {
     public DocChain()
     {
      Log = new LogWrapper(this);
     }
     public override oAPI HandleRequest(iAPI request)
     {
      switch (request.Comand)
      {
       case iAPI.Target.GetModel:
        return GetModel(request.DocID);
      }
      return ReferToSuccessor(request);
      }
 private Doc GetDoc(int id)
    {
     Log.Debug("get document by id: " + id);
     using (var unit = UnitOfWork.Create())
     {
      var repository = unit.GetRepository<Doc>();
      Doc doc = repository.Get(id);
      if (doc == null)
      {
       Log.Error("Document not found");
       throw new DocumentNotFoundException();
      }
      return doc;
     }
    }

 public oAPI GetModel(int DocId)
      {
       var Model = GetDoc();
       return RB(HTTPCodes.OK, data: Serializer(
       Model));
       }
}

And CloudHandler

 public class CloudHandler:ChainHandler
    {
        private IDAVService _service;
        private string RemoteRepository;
        public CloudChain(IDAVService service)
        {
            Log=new LogWrapper(this);
            _service=service;
        }

        public override oAPI HandleRequest(iAPI request)
        {
            switch (request.Comand)
                    {
                    case iAPI.Target.UploadModel:
                    return Upload(request.DocID,request.VersionID);
                    case iAPI.Target.DownloadModel:
                    return Download(request.VersionID, request.DocID);
                    }
            return ReferToSuccessor(request);
        }
        public oAPI Upload(int DocID,int VersionID)
        {
            // Need to get model from DocHandler
            var model = ???
            service.Upload(model);
            return RB(HTTPCodes.OK);
        }
        public oAPI Download(int DocID,int VersionID)
        {
            // Need to get model from DocHandler
            var model = ???
            service.Download(model);
            return RB(HTTPCodes.OK);
        }
    }

And my problem in finding the best way to share methods and properties between handlers. Now I use static class SharedComponents where each handler delegate own method.

public static class SharedComponents
    {
        public static Func<int, Doc> GetDoc;
    }

In DocHandler I delegate method SharedComponents.GetDoc = this.GetDoc; and then use it in CloudHandler var Model = SharedComponents.GetDoc(docid). This is spagetti to write delegates to hundred of shared methods.

But how I tested this? I will must initialize all handlers (because A uses method of B and B may use methods of C etc.) to test one method in one handler. Horror!

I try to set shared methods as static to use like var Model = DocHandler .GetDoc(docid). But this solution breaking Dependency inversion principle. And if some shared method use context (like session in UnitOfWork) to I need in test initialise all handlers again!

mercredi 25 novembre 2015

Multi-format file conversion design pattern

In the past, I tried two times implementing a multi format converter. One was a Markup converter which should be able to convert GitHub, StackOverflow, MoinMoin, MediaWiki etc. The other is a photobook converter which currently converts ifolor to scribus but should support at least two more photo book formats plus pdf.

The problem is always the same: Different formats have different features. For example: MediaWiki and MoinMoin have different understandings of Macros while most other Markup languages don't support macros. Or ifolor had some border formats which were hard to implement in scribus and don't look nice.

I don't like the idea of implementing direct converters for every possible combination (for 4 formats this are 12 converters with a lot of redundancy). I started with a 'superset data structure' which contains all the features of all formats as a link between import and export filters of the given formats, but I wonder if there is a Best practice way to do such a thing or a something like a Design Pattern which could be helpful to know about, for example an architecture where import and export directly communicate without a 'super format'?

Well, the two projects are currently suspended because of a lack of time (and demand) but I'm willing to learn how I can do it better next time. The photobook did its job for my personal book and will probably be continued soon. Its code is on GitHub.

What is best practice for asynchronous javascript error handling?

I am interested what is considered best practice for handling errors from an asynchronous JavaScript function. I have given two examples below one which handles the error in an if statement and one which handles the success in the if statement. Previously I have always handled the error in the if statement but wondered whether this was the best approach. Please let me know which you consider to be the best approach and why?

function(err, res){
    if(err){
       // handle error
       return;
    }
    // code to handle response
}

or

function(err, res){
    if(!err){
       // code to handle response
       return;
    }
    // handle error
}

Thanks in advance

Suitability of different approaches of factory method pattern

Say I need car object. Could you please tell about the scenarios in which one approach would be better than the other?

Method#1

CreateCar(engineType, carBodyDesign, color, otherconfiguration1,...,otherconfigurationN)
{

    engine=MakeEngine(engineType);
    body=MakeCarBody(carBodyDesign);
    .
    .
    .
    //assemble all parts here
    return car;

}

Method#2

ModelNo has the info about engineType,carBodyDesign, etc. color, seatCoverColor, etc info are absent.

CreateCar(ModelNo, color,otherconfiguration1,...,otherconfigurationN)
{
    car=MakeCar(modelNo);
    car.configurableItem1=MakeConfigurableItem1(otherconfiguration1);
    .
    .
    .
    car.configurableItemN=MakeConfigurableItemN(otherconfigurationN);
    return car;

}

Best design pattern for interactions in the form of cyclic graph

I have a PHP script which uses an external API. The interaction process is quite complicated, but generally the script consists of several "commands" (aka API function handlers) which should be invoked in a sequence which could be represented as a cyclic graph. Some commands can be invoked several times after other commands on some conditions. What is the best way to design this behavior?

Node.js filling child object with data from parent object (inheritance using util.inherits)

let's say that I've got a parent (let's say base) object, and a child object that's an extended version of base one.

I'll use sample code from metaduck.com. Here we have the parent:

function Animal() {

  var walked = false

  function walk() {
    console.log('walking...')
    walked = true
  }

  function hasBeenWalked() {
    return walked
  }

  return {
    walk: walk
  , hasBeenWalked: hasBeenWalked
  }
}
module.exports = Animal

and the child:

var Animal = require('./animall')

function Cat() {
  var cat = {}
  var walked = false

  cat.__proto__ = Animal()

  cat.pat = function pat() {
    console.log('being patted')
  }

  cat.lasagna = function lasagna() {
    console.log('Lasagna!')
    walked = true
  }

  return cat
}

module.exports = Cat

It works great if you don't have any parameter in constructors, but let's say that we've an Animal(color,size) and a Cat(name).

Is there a simple way to get a Cat('Garfield') filled with data from already existing Animal('orange','big')? I would like to make some kind of factory from Animal that creates a lot of Cats with different names. How can I do that?

Facade pattern combined with observer pattern

I got an assignment to find out exactly what the facade pattern is. I have googled and found out it is ment to shield a client from a very complex system by making an "interface". So I have 2 questions, I have seen in multiple examples is they make an C# interface for the complex system, but I have also seen a few that used A class as the "Interace" (as seen here). I can only make sence of it if it is a base class that simpliefies a lot of different complex method calls to different classes as in (the bank example seen here)

So my first question is if I am correct that you would implement the "interface" as a class?

My other question then is, could you use facade pattern together with the observer pattern. The facade class would observe on all subjects and then control what methods in different classes should be called, depending on the subject?

Matlab: How to find similarity of two patterns

I have a problem to find the similarity of two patterns. I use LCS of this two pattern to represent their longest common part. For example given a pattern

P=<{School}, {Cinema}, {Park,Bank}, {Restaurant}>

and a pattern

Q=<{School, Market},{Park}, {Restaurant}>,

their longest common sequence is

LCS(P,Q)= <{School}, {Park}, {Restaurant}>.

I have to apply this to a cell array of numeric strings of different dimensions and I have a lot of difficultes: I have no idea, I can do it. I find in MAtlab function like Strcmp, Strcmpi, Strncmp, Strncmpi but they are for strings of same size; i think to use regexp but I don't know how. I have read other questions about compare strings but no-one appears to help me. Can you give me suggests?

mardi 24 novembre 2015

regex validity in java using compile method

I am trying to check validity of n regex and it works good but it does not passes all the test cases . I am not able to find out why is this happening.

import java.util.Scanner;
import java.util.regex.Pattern;

    public class Solution

{
    public static void main(String[] v)
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        sc.next();
        int j=0;
        String[] patt=new String[n];
        while(j<n)
            {
            patt[j]=sc.nextLine();
            j++;
        }
        for(int i=0;i<n;i++)
        {
        try
        {
            Pattern.compile(patt[i]);
            System.out.println("Valid");
            //System.out.println(patt.length);
        }
        catch(Exception e)
        {
            System.out.println("Invalid");
        }

        }
    }
}

For Page Object Pattern, when designing the page objects in Selenium, how do you handle multiple modals correctly?

Let me further explain. You have a page where an application lives. However, upon first login, the user is prompted with a welcome screen that loads in the center of the browser. Like a pop-up from the application. This welcome screen is to help the user get familiar with the app. You can move on through the screens by reading the information and clicking the Continue button. After several of these pop-ups, the application will now be available for testing.

So how would I handle this in the Page Object Pattern using Selenium. Should I have a main page that just has functionality to navigate through these modals? Or should the main page return objects that represent each of the individual modals? Or should each modal be a separate page that I interact with?

Basically, I can think of several options:

ApplicationPage.Modal1.Continue();

or

Modal1.Continue(); Modal2.Continue();

or

ApplicationPage.ContinueThroughModal1();

or

ModalPage.Continue1(); ModalPage.Continue2();

returning a copy of an object which is same as the original

package Test;
public class Test {
    class Book implements Cloneable {
        int bookID = 0;
        public void setID(int i) {
            this.bookID = i;
        }
    }
    class bookFactory {
        Book b;
        bookFactory() {
            b = new Book();
            b.setID(20);
        }
        public Book GetBooks() {
            return b;
            //now i want to
            //return a copy of b but it should be in the original state
        }
    }
}

i tried using b.clone bt there is no clone function in b object i can simply create a new object bt i want to return book object from the existing object bt with original properties..

Chain of Responsibility vs Events

I always have the doubt when it's came to chose one of these 2 patterns. For example: Let assume that I have an input manger and when I press the one button, I want the main player to execute the jump action. In this case, I can use 2 different solutions:

  1. I have one input the inputManger that tells the GameManger what just append and the gameManger tells the Player-manger to act. So it's something like: inputManger ---> Game manger ---> Player-manger and this is the Chain of Responsibility pattern.
  2. the PlayerManger register the jump event on the inputManger i receive the input and the PlayerManger automatically execute his jump routine.

So my question it's: Why would I choose one pattern ove the other? Both have their pro an cons, so witch are you common choices when you have this kind of situations?

To implement neural network, the composite pattern is right selection?

I would like to implement neural-network by Java.

Because I learn design pattern at this semester, I also would like to apply design pattern to implement neural-network.

Since neural-network is tree(or graph), the composite pattern is the best selection.

If I miss more important pattern, please let me know.

Thank you for your comment in advance.

If getOrCreate is an antipattern, how can I avoid it?

According to http://ift.tt/q0MLpA I believe getOrCreate function is an antipattern.

function getOrCreateObj(something) {
  let f = find(something, db); 
  return f || createObj(something);  
}

What should I do to avoid it?

Design mixin classes

Initial situation

I have one app, 'devices' with some views:

class DeviceUpdateView(LoginRequiredMixin, UpdateView):
    model = Device
    form_class = DeviceEditForm

    def get_form(self, form_class=None):
        form = super(DeviceUpdateView, self).get_form(form_class=None)
        form.fields['beacon'].queryset=Beacon.objects.filter(customer_account=self.request.user.default_customer_account)
        return form

class DeviceCreateView(LoginRequiredMixin, CreateView):
    model = Device
    form_class = DeviceEditForm

    def get_initial(self):
        initial = super(DeviceCreateView, self).get_initial()
        initial['customer_account'] = self.request.user.default_customer_account
        return initial

    def get_form(self, form_class=None):
        form = super(DeviceCreateView, self).get_form(form_class=None)
        form.fields['beacon'].queryset=Beacon.objects.filter(customer_account=self.request.user.default_customer_account)
        return form

I have another app ('buildings') vith this view:

class BuildingCreateView(LoginRequiredMixin, UserFormKwargsMixin, CreateView):
    model = Building
    form_class = BuildingEditModelForm

    def get_initial(self):
        initial = super(BuildingCreateView, self).get_initial()
        initial["customer_account"] = self.request.user.default_customer_account
        return initial

DRY Mixin

Now, I want to factorize my code in order to be more "DRY".

I then create this mixin, in my devices/views.py:

class BeaconFilterMixin(object):
    def get_form(self, form_class=None):
        form = super(BeaconFilterMixin, self).get_form(form_class=None)
        form.fields['beacon'].queryset=Beacon.objects.filter(customer_account=self.request.user.default_customer_account)
        return form

And my views become:

class DeviceUpdateView(LoginRequiredMixin, BeaconFilterMixin, UpdateView):
    model = Device
    form_class = DeviceEditForm


class DeviceCreateView(LoginRequiredMixin, BeaconFilterMixin, CreateView):
    model = Device
    form_class = DeviceEditForm

    def get_initial(self):
        initial = super(DeviceCreateView, self).get_initial()
        initial['customer_account'] = self.request.user.default_customer_account
        return initial

Nice and sweet!

Now the question

I want to do exact same thing and create a "InitialCustomerAccountMixin" that could be used by both 'buildings' and 'devices' apps.

The code will be:

class InitialCustomerAccountMixin(object):
    def get_initial(self):
        initial = super(InitialCustomerAccountMixin, self).get_initial()
        initial['customer_account'] = self.request.user.default_customer_account
        return initial

The question is: where do I put my mixins code? For an 'app-scope' mixin, I get that I should put the code in the views.py or in a mixins.py file in the app. But for a 'multi-app' mixin, I don't know the design principle to follow.

Binary complement patterns in hopfield network

any body knows, why do Binary complement patterns in hopfield network exist??? or how are they created?

thank you so much

Refactor several nested if with same else

This is not about an existing piece of code but I'm looking for some pattern that may exist in the case that some nested if perform the same thing in their else statement.

if(condition1(a)) {       
    doSomethingWith1(a);        
    if(condition2(a)) {
        doSomethingWith2(a);
    } else {
        elseFn();
    }    
} else {
    elseFn();
}

The doSomethingWith... functions are changing the value of a, making it complex to have all the condition in one if.

So I'm just wondering if there is a clearer way to write it (in C, if possible).

Thanks guys

lundi 23 novembre 2015

Check if pattern exists in a String

I would like to check if a pattern exists in a String using iteration.

Here is what I have currently but I keep getting false as a result of it.

public static void main(String args[]) {
        String pattern = "abc";
        String letters = "abcdef";

        char[] patternArray = pattern.toCharArray();
        char[] lettersArray = letters.toCharArray();

        for(int i = patternArray.length - 1; i<= 2; i++){
            for(int j = lettersArray.length - 1; j <= 5;j++){
                if(patternArray[i] == lettersArray[j]){
                    System.out.println("true");
                } else{
                    System.out.println("false");
                }
            }
        }
    }

Basically I would like to check if abc exists in the String abcdef

Note: I don't want to use regex because is too easy. I am trying to find a solution without it because I am curious how to do it with iteration.

Should I pass the object in or build it in the constructor?

Perhaps this doesn't really matter, but I have a hunch I should 'pass in the object', but I'm not sure why.

Situation

I have some Record objects that are being created by reading a text file (e.g. a CSV file). One of the fields defines possible actions to perform on this record.

For example:

class Action:
    def __init__(self, create, update, delete):
        self.create = create
        self.update = update
        self.delete = delete

    @staticmethod
    def parse_from_string(actions):
        return Action('c' in actions, 'u' in actions, 'd' in actions)

Which of these two is better design?

class Record1:
    def __init__(self, actions_string, name, ...etc):
        self.action = Actions.parse_from_string(actions_string)
        ...

class Record2:
    def __init__(self, actions, name, ...etc):
        self.action = actions

With the difference in their use being:

action_string, name_string,... = read_details_from_file()

record1 = Record1(action_string, name_string, ...)

# vs.
actions_obj = Actions.parse_from_string(actions_string)
record2 = Record2(actions_obj, name_string, ... )

I think I am leaning to the second model, but I don't know why? Also, should I enforce that the object passed to the Record2 constructor is of the correct type?

How to implement business rules at each node in a self hierarchical tree structure

In a self hierarchical tree like structure, I would like to check for business rules(based on node type) at each node level on every node addition/edition/deletion. I tried implementing composite design pattern but no luck. Please suggest.

Sample class structure.

class Parent
{
    int Id;
}

class ChildType1 : Parent
{
    string propForType1;
    List<Parent> ListOfChildren;
}

class ChildType2 : Parent
{
    string propForType2;
    List<Parent> ListOfChildren;
}

Decide upon method usage at runtime. Polymorphism

Well, this is kind of embarrassing, but I've forgotten how to do the following in plain old Java:

abstract class Animal {
   protected String name;
   public Animal(String name) {
       this.name = name;
   }
}

class Flea extends Animal {
    private double jumpHeight;

    public Flea(String name, double jumpHeight) {
        super(name);
        this.jumpHeight = jumpHeight;
    }

    public double jump() {
       return jumpHeight();
    }
}

class Giraffe extends Animal {
    private int strideLength;

    public Giraffe(int strideLength) {
        super("Berta");
        this.strideLength = strideLength;
    }

    public int stride() { return strideLength; }
}

class Gorilla extends Animal {
    private String call;

    public Gorilla(String call) {
        super("Boris");
        this.call = call;
    }

    public String call() { return "Gorilla says " + call; }
}

Now I would like to decide the appropriate method at runtime, without having to add all the methods to each Animal (no abstract methods) and without meaningless placeholders (like imagine a Flea has no call).

I would like to do this without casting. So no:

if(Animal instanceof Gorilla) ((Gorilla) animal).call();

I could come up with a solution incorporating interfaces like jumpable and could use that, but I'm sure there was a certain pattern that was exactly for this kind of task.

Any ideas?

how to implement a repository of algorithms?

I have a set of algorithms implemented in Java and packaged as jar files. The algorithms are intended for 3rd party to access them. The algorithms have several variations. Overtime, new versions and new types of algorithms will be added to. At the same time I don't wont all the 3rd parties to be forced to use the new algorithm.

I am considering implement a simple repository system for this. The requirements are as follows:

  1. create/delete of the repos, so that each repo contain one set of variations of the algorithm.
  2. algorithms in one repos can have serverl versions running at the same time.
  3. new algorithms can be added to the a repo.

Is there some open source project fit my requirement? Or is there some design pattern for problems like this?

dimanche 22 novembre 2015

Properties and inheritance defined at runtime

I am supposed to create a semantic network.

The tricky part is that the information to create the semantic network will come from a text file which I will not know anything about (size of the semantic network, relationships, names, attributes). I don't need to do any operation with the data, just retrieve it and be able to express its relationship with other nodes.

  • I was considering using regular inheritance but I guess I won't be able to create 'custom' classes with an undefined number of attributes (by the way, all attributes will be handled as Strings).
  • Then I thought plain old tree structures will do it, but it feels a little bit un-Swifty
  • Now I'm thinking of using a dictionary, the keys for the attribute names and an array of strings as values so I can mimic inheritance var attributes = [String: [String]]() This still feels crumby though.

  • I've looked at protocols, extensions and generics but I can't figure a way to use them to solve this. For what I know Protocols are more flexible than classes

Is there a 'standard' way to solve this kind of problems? Is there a way to define objects at runtime? What would be a nice 'swifty' way to implement this?

Thank you

Instantiating a class or using a static method in PHP

I am learning OOP and I am creating a WordPress plugin. I've looked through a bunch of different popular WordPress plugins and they all use different coding styles and methods to achieve the same things.

I have created the below stripped down functions as an example. Some plugins will use one style, whereas other plugins will use the others.

The function is to simply print out 3 buttons within a WordPress post edit screen. What would be considered the correct/preferred/best way to go about this?

function sliced_print_buttons( $id ) {

    $emails = new Sliced_Emails();
    $pdf = new Sliced_Pdf();
    $admin = new Sliced_Admin();

    $email_button = $emails->get_email_button( $id );
    $pdf_button = $pdf->get_pdf_button( $id );
    $convert_button = $admin->get_convert_invoice_button( $id );

    echo $email_button;
    echo $print_button;
    echo $convert_button;
}

Instantiate 3 different classes as above?

function sliced_print_buttons( $id ) {

    $email_button = Sliced_Emails::get_email_button( $id );
    $pdf_button = Sliced_Pdf::get_pdf_button( $id );
    $convert_button = Sliced_Admin::get_convert_invoice_button( $id );

    echo $email_button;
    echo $print_button;
    echo $convert_button;

}

Use static methods to to print the buttons as above?

function sliced_print_buttons( $id ) {

    echo email_button();
    echo print_button();
    echo convert_button();

}

Or create separate functions that could print the buttons?

I'm getting myself pretty confused looking through all of the different WordPress plugins and reading up on OOP. Some guidance would be much appreciated.

Intercepting Filter pattern

I want to implement intercepting filter pattern in JAVA to find if the password entered is as per the requirement. For this I can create a filter class. But how do I handle the situation when password is incorrect, should I pass it to the target class or return false from filter class. I was following some online tutorial to authenticate request but in that they have not mentioned what to do when authentication fails. Also I don't think my understanding of target class is correct, for me the target class is something which is called after all the filters show that the request is authenticated.

Thanks

Generating different Objects with each js plugin initilization

I have following code.

(function (window) {

    window.plug = function() {

        this.version = '1.0.0';

        this.value = arguments[0];

        this.init();

    }

    plug.prototype.init = function () {

        var a = document.createElement('div');
        a.textContent = 123;
        self = this;
        a.addEventListener('click', function (e){
            console.log(self.value);
        });

        document.body.appendChild(a);

    };

}(window));

When user initializes the plugin it should create different object per each. for an instance var plug = new plug(1); var plug = new plug(3); var plug = new plug(5); is called three times, when the user clicks on generated div tag, it should log the three different valuees passed.

And how do you implement a jquery style plugin initialization method in vanila js

Eg: plug({attr1: 1, arrr2: 2});

if someone could give me a detailed explanation i really appreciate that.

demo

Is this pattern for subscribing to events okay?

I want to have a logger which is "made available" to my application. My application logs interesting things, and subscribers subscribe to those messages. For example a subscriber might put message in a database, or the windows event log, or a message bus, etc.

A simplified reproduction of what I've written is below:

using System;
using System.Reactive.Subjects;

namespace ConsoleApplication17
{
    internal interface ILogger
    {
        void Log(String message);
    }

    internal class Logger : ILogger
    {
        private readonly Subject<String> _logMessagesObservable = new Subject<string>();

        public void Log(string json)
        {
            _logMessagesObservable.OnNext(json);
        }

        public IObservable<String> LogMessagesObservable { get { return _logMessagesObservable; } }
    }

    internal class ConsoleLogListener
    {
        public ConsoleLogListener(IObservable<String> messages)
        {
            messages.Subscribe(Console.WriteLine);
        }
    }

    internal class WindowsEventListener
    {
        public WindowsEventListener(IObservable<String> messages)
        {
            messages.Subscribe(WriteToEventLog);
        }

        private void WriteToEventLog(String message)
        {
            //Write to event log
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Logger logger = new Logger();

            //Link up any subscribers
            new ConsoleLogListener(logger.LogMessagesObservable);
            new WindowsEventListener(logger.LogMessagesObservable);
            //... more listeners go here.           

            DoSomeWork(logger);
        }

        private static void DoSomeWork(ILogger logger)
        {
            logger.Log("Something interesting");
            logger.Log("Something else interesting");
        }
    }
}

But I'm not happy about the code which looks like this:

//Link up any subscribers
new ConsoleLogListener(logger.LogMessagesObservable);
new WindowsEventListener(logger.LogMessagesObservable);
//... more listeners go here. 

It irks me for some reason but I can't put my finger on it. I guess it just looks odd to new up a listener like that and not keep the reference to it.

Is there a better / more accepted pattern for what I'm trying to do?

How to overcome returning ID from a database insert method design challenge

It will probably be a long post but please bear with me. The basic idea is this:

public int InsertPersonAndGetPersonId(Person person){
    _dbContext.Insert(person);
    return person.PersonId;
}

The method above is simple but it violates clean programming principles.

  1. It is against Command/Query separation in methods.
  2. It does more than one job.

When I am evaluating different approaches, I usually list the pros and cons and choose the one that has the least cons and the least trade-offs. Therefore, honestly, the method above looks better than the alternatives listed below. But I still would like to get the opinions of SO community and perhaps I learn a new pattern that works best with this challenge.

Alternative #1

The one alternative is to have two methods. While the one is inserting new records, the other gets the lastly added personId from database. But this is not reliable unless you prevent database from accepting new person insertion between the time you insert a record and get its id from database.

You can even do filtering by the a property of Person (Name for instance) when getting the record from database but in addition to what I said above, there can also be more than one person who have the same name but different PersonIds.

It is also doing one more database trip. I am a pragmatic person and don't like to speculate about performance without actually measuring it. However, if I can prevent something with a simple change which will contribute to the performance even slightly, then I find it silly not to do it. Of course, while doing it, I also consider clean code practices.

Alternative #2

The other method can be to change InsertPersonAndGetPersonId is in and have something like following:

public class PersonRepository
{
    private int _personId;

    public void InsertPerson(Person person){
        _dbContext.Insert(person);
        _personId = person.PersonId;
    }

    public int GetLastPersonId
        return _personId;
    }
} 

Even though I don't like the name of this method GetLastPersonId(), which may bring a different personId than expected but let's assume that it returns the id of person object. The reason it is bad, besides what I already said, it is modifying the state of the object, therefore have a side effect.

Alternative #3

We can simply have the method below:

public void InsertPerson(Person person){
    _dbContext.Insert(person);
    _personId = person.PersonId;
}

and since person is reference type, we can access person.PersonId like following:

var personRepository = new PersonRepository();
var person = new Person() {Name="Hello"};
personRepository.InsertPerson(person);
Console.WriteLine(person.PersonId);

Did I like it? No! It is way too hidden and unpredictable and you don't really know it unless you check the implementation detail and then we break the beauty of abstraction.

Alternative #4

We can use out like follows:

public void InsertPerson(Person person, out int personId){
    _dbContext.Insert(person);
    personId = person.PersonId;
}

But this looks more silly and cumbersome than the first one InsertPersonAndGetPersonId. If I am going to have to return something, then I would return it using return and make the signature more explicit for the developers. Also in fact, out and ref makes more sense when we need to return multiple values. For instance TryParse(), returns boolean but also you can get the parsed value using out or ref too.

Update

Due to a couple of comments, I decided to clarify my question a little bit more. What I am asking is how to get the PersonId without breaking the clean code principles. I am using EF and therefore getting the id from database is not a problem and in fact you can see it in my first example. Sorry for the confusion.

How do chat servers distribute messages to multiple clients?

This is really a programming design question more than a specific language or library question. I'm tinkering with the idea of a standalone chat server for websockets that will accept several remote browser-based javascript clients. I'm going for something super simple at first, then might build it up. The server just keeps accepting client connections and listens for messages. When a message is received, it will be sent back to all the clients.

What I need to better understand is which approach is best for sending the messages out to all clients, specifically, sending immediately to all clients, or queuing the messages to each client's queue to be sent when a client connection handler's turn comes up. Below are the two examples in a python-like pseudo-code:

Broadcast Method

def client_handler(client):
    while true:
        if(client.pending_msg):
            rmsg = client.recv()
            for c in clients:
                c.send(rmsg)
        client.sleep(1)

Queue Method

def client_handler(client):
    while true:
        if client.pending_msg:
            rmsg = client.recv()
            for c in clients:
                c.queue_msg(rmsg)
        if client.has_queued:
            client.send_queue
        client.sleep(1)

What is the best approach? Or, perhaps they are good for different use-cases, in which case, what are the pros, cons and circumstances for which they should be used. Thanks!

Can't use jQuery function inside Object Literal

I'm trying to learn how the object literals pattern works in Javascript. In one of my projects i'm stuck on a part where I use some jQuery functions. For the sake of the problem I build a little example.

I hope someone can provide me with some awesome hints.

Javascript: creating an object literal, and calling the init() method.

HTML: Some parts with a remove button. When clicked, I want to display an alert with the associated id extracted as data-attribute from the DOM. But there is the part it is failing, javascript does not know what .data means in that specific function.

Thanks... !

var test = {
  init: function() {
    this.dom();
    this.events();
  },
  dom: function() {
    this.$contentbox = $('.box');
    this.$buttons = this.$contentbox.find('a');
  },
  events: function() {
    this.$buttons.on('click', this.removeDiv);
  },
  removeDiv: function(event) {
    event.preventDefault();
    var div = this.closest('.removeMe'); // This works perfectly
    var divID = div.data('id'); // Crashing -> Uncaught TypeError: div.data is not a function
    alert('Product ' + divID + ' is to be deleted...');
  }
}

test.init();
<script src="http://ift.tt/1oMJErh"></script>

<div class="box">
  <div class="content">
    Hi there! Click X to delete item :)
  </div>
  <div data-id="6" class="removeMe">
    Product 6 <a href="#">(X)</a>
  </div>
  <div data-id="7" class="removeMe">
    Product 7 <a href="#">(X)</a>
  </div>
  <div data-id="8" class="removeMe">
    Product 8 <a href="#">(X)</a>
  </div>
</div>

how to get object of some class as response from enum when i pass a string

Here is the scenario, I am trying to get object(s) of some class type when i pass a string as input to the enum.

I have a list of static final variables mentioned below,

MyDetail.Carriers
MyDetail.Plan
MyDetail.Benefits

I want to select one or more objects depending of string input(i.e Carriers / Plan / Benefits).

samedi 21 novembre 2015

How to use shared_ptr in a decorator pattern implementation correctly?

I am getting memory leak issues in the following code. I understand there are some flows. But not sure. How to use shared_ptr in these scenarios? And in case I need to add more decorators, say Chocolate-Pista-Icecream, how to pass the pointer correctly such that it will get deleted at the exit?

    class AbstractCream
{
public:
    virtual void ShowFlavour() = 0;
    virtual ~AbstractCream()
    {
        cout << endl << "AbstractCream-DTOR";
    }
};

class IceCream :public AbstractCream
{
public:
    void ShowFlavour()
    {
        cout << "IceCream";
    }
    ~IceCream()
    {
        cout << endl << "IceCream Dtor";
    }
};

class DecoratorCream :public AbstractCream
{
private:
    std::shared_ptr<AbstractCream> AbCream;
public:
    DecoratorCream(std::shared_ptr<AbstractCream>abs) :AbCream(abs)
    {}
    void ShowFlavour()
    {
        AbCream->ShowFlavour();
    }
    virtual ~DecoratorCream()
    {
        cout << endl << "DecoratorCream-DTOR";

    }
};

class ChocolateCream : public DecoratorCream
{
public:
    ChocolateCream(std::shared_ptr<AbstractCream>abs) :DecoratorCream(abs)
    {}
    void ShowFlavour()
    {
        cout << "CholocateCream added..";
        DecoratorCream::ShowFlavour();
    }
    ~ChocolateCream()
    {
        cout << endl << "ChocolateCream-DTOR";
    }

};
class PistaCream : public DecoratorCream
{
public:
    PistaCream(std::shared_ptr<AbstractCream> abs) :DecoratorCream(abs)
    {}
    void ShowFlavour()
    {
        cout << "PistaCream added..";
        DecoratorCream::ShowFlavour();
    }
    ~PistaCream()
    {
        cout << endl << "PistaCream-DTOR";
    }
};

class StrawberryCream : public DecoratorCream
{
public:
    StrawberryCream(std::shared_ptr<AbstractCream> abs) :DecoratorCream(abs)
    {}
    void ShowFlavour()
    {
        cout << "StrawberryCream added..";
        DecoratorCream::ShowFlavour();
    }
    ~StrawberryCream()
    {
        cout << endl << "StrawberryCream-DTOR";
    }
};


int main()
{
    std::shared_ptr <AbstractCream> ice1( new IceCream());
    std::shared_ptr <PistaCream> pista1(new PistaCream(ice1));
    std::shared_ptr <AbstractCream> ice2(new IceCream());
    std::shared_ptr <ChocolateCream>choco1( new ChocolateCream(ice2));

    pista1->ShowFlavour();
    cout << endl;
    choco1->ShowFlavour();
    cout << endl;

    getchar();
    _CrtDumpMemoryLeaks();
    return 0;
}

Desgin a Java POJO with lazy loading property

Please consider below example:

A web application creates a user object for every logged in user. This object has simple String properties for firstName, lastName ...

Each user can have a car too. Consider that fetching the user car is very expensive, so we prefer not to set the users car when user logs in. Instead we want to get car when a use case needs it.

To implement this we have created a User pojo as:

public class User() {
  private String FirstName;
  private String LastName;   
  private Car cars;
  //Here we have the service object, this could be injected with spring or JEE
  private CarServices carServices;

  public Car getCar() {
    //If the cars is not fetched yet, go on and get it from your service
    if (car == null) {
      car = carServices.getCarFromDB(...)
    }
    return car;
  }

}

To initial user after a login:

User newUser = new User();
newUser.setFirstName("foo");
newUser.setLastName("bar");
//We just let user have service, so he can use this service latter
newUser.setCarServices( new CarServices() );

And every use case which needs the user car can get it easily:

newUser.getCar()

However, I have been argued that in this way my User object is not a simple pojo any more and this is not a good approach.

How can I achieve this requirement in better way.

php web application architecture

I am building an internal invoicing platform (PHP and SQL)which would mostly interact to the database to read/write data. So the idea is to get some data from the databse and assign it to a particular tab. I have ~ 10 tabs and x amount of data to be read, which is growing on a constant pace. To limit the calls to database and improve the speed I am thinking of: 1. Have one call to the database 2. Create the buckets and save them in session 3. When some cells are updated by the user on the webpage I would update that row in the db and would not make a call to create new session, but instead update the current session variables and reasign the buckets. 4. Only one person will be working on this platform.

Is this a reasonable approach in terms of design and performance? Also, if there would be more people working on this platform in the future it would "break down", so I am also open to multi-person design suggestions.

Communicating to an Object from another without coupling in java?

So i have a Person object, and a GumballMachine object. the behavior i'm searching for is, in the intent to avoid unnecessary coupling, have the method "insertCoin()" called from within the person object, which will then call the "insertCoin()" within the GumballMachine to receive a Gumball. What's a proper design-pattern, or solution that avoids coupling, and keeps these two objects as oblivious to each other as possible while having a type of "Bridge" between them?

3D Programming, Matrix4 Explanation

I know the basics of the Matrix4 struct in (in this situation I am referring to the one in OpenTK), like it is used to hold data related to the camera translation, rotation, eye vector, etc. But can someone provide me with a better explanation about the class, like how and why it is used in most—if not all—3D games for representing this data.

The sourcecode(which is not very well documented in my opinion)to the Matrix4 struct is located here

python mediattor pattern memory leak?

i have few classes that communicate with each other over another class (something like Mediator pattern).

Every class prints message when created and when they are destoryed.

like on this picture

When i create Mediator object, Mediator holds references to all other objects, and all objects hold references to Mediator. Afrer that objects destructors are not called when program finishes. like on this picture

Why is that? Is this a memory leak?

Data Repository Pattern Design C#

I have an entity class

public partial class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
}

and this entity

public partial class User
{
    public User()
    {
        this.Tokens = new HashSet<Token>();
    }

    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Token> Tokens { get; set; }
}

I have a repository pattern

public abstract class DataRepositoryBase<T> : IDataRepository<T>
       where T : class, new()
{
        protected abstract T AddEntity(T entity);

        protected abstract T UpdateEntity(T entity);

        protected abstract IEnumerable<T> GetEntities();

        protected abstract T GetEntity(int id);
}

How can I call repository using generic data repository using some thing like this.<T> just using generic interface not creating new class? Thanks.

_datarepositorypattern.GetDataRepository<IProductRepository>();
_datarepositorypattern.GetDataRepository<IUserRepository>();

Creating a C# program to check for new emails in outlook and trying to match a pattern in the subject line.No errors found but the code is not working

Creating a C# program to check for new emails in outlook and trying to match a pattern in the subject line. No errors found in the code but it is not working.

Have tried creating a console application that checks for a pattern in the subject line.If the pattern is found, needs to write a message out to the console.Have used Itemadd event here.

The equivalent of this code in VBA is working perfectly fine. C#enter image description here

vendredi 20 novembre 2015

Domain driven design - Document conversion application

I have to create a document conversion application which has to be done using domain driven design.

Basically my application will receive data in xml\csv(as string input) format which is to be converted to a standard xml,json or csv format using xslt(as string output).

There are also some rules(stored in a relational database) which are applied to the data after converting to xml or json format.

The end interface might be Rest API or Wcf application.

But now I am confused as how I am supposed to create this using domain driven design.

What will be my domain models, will this include the rules which are stored in the database ?

and where I put the core format conversion logic, in the service layer or directly in API or wcf service classes ?

Thanks!

Handling Context In Spring

I'm working on a small project and I'm looking for a good way to handle context in spring. I find myself creating a context holder class to hold my properties using setter injection. The problem I'm having with this is that I'm grabbing a context object and passing it around. I'm looking for a design pattern or something that can help me do this in a cleaner way. As a simple example let's say I'm currently doing something like the below, where the fields are injected through setter injection and I'm looking for a better way to inject the properties Also, pretend I had a large amount of properties, too large to use something like @Value cleanly:

public class MyContext{

    private String configItem1;
    private String configItem2;
    private String configItem3;


    public void setConfigItem1(String configItem1){
        this.configItem1 = configItem1;
    }

    public void setConfigItem2(String configItem2){
        this.configItem2 = configItem1;
    }

    public void setConfigItem3(String configItem3){
        this.configItem3 = configItem1;
    }

}

Sample spring context:

<bean id="appProperties"
       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:my-app.properties</value>
            </list>
        </property>
    </bean>


<bean id="myContext" class="these.are.not.the.droids.you.are.looking.for.context.MyContext" >
     <property name="configItem1" value="${some.item.1}" />
     <property name="configItem2" value ="${some.item.2}"/>
     <property name="configItem3" value="${some.item.3}" />
</bean>

how to set mask and pattern in dynamic fields in AngularJS?

I'm setting the propieties of dynamic fields with Angular, but I have a problem with the mask and the pattern because is null for some fields.

<md-input-container ng-repeat="field in dynamicFields" md-no-float class="md-block m-l-16">
<input name="{{field.name}}" ng-model="consumer[field.name]" placeholder="{{field.text}}" mask="{{field.mask}}" requiered="{{field.required}}" ng-change="textChanged()" />
</md-input-container>

The other fields name, model, placeholder, and required works perfect but mask and pattern don't work because some fields have null value.

This is the controller that populate the fields

for (var item in fields) {
    $scope.dynamicFields.push({
    text: fields[item].description,
    type: fields[item].type,
    pattern: fields[item].pattern || null,
    required: required.indexOf(item) >= 0,
    mask: maskedFields[item] || null,
    name: item
});

This is the error: "TypeError: Cannot read property 'then' of undefined".

Any suggestions? thanks btw!!

For notifications like a mailbox, what design pattern, how do I model my schema objects

In a webapp (ASP MVC), I have a view/page that lists new notifications/incoming messages similar to a list box (picture a mail box, but much simpler) across sessions for users. I understand INotifyPropertyChange and Observables

My scenario: I have a simple Transactions table with a TransactionType, only some transactions with Transaction.Transactype == Approve/Reject need notifications.

How do I model this in the database and the object so that I can pick up these changes, everytime the user logs back in, across session?

Here is what I did,

  1. I created a separate Transaction.ApproveTable and I attached a trigger on insert, but I am looking them across the sessions
  2. I created an MSMQ journal, but its blocking since its serial from notifying other users. I also have a role notification scenario, where I notify all member of the role.