mercredi 1 mars 2017

How do you call an interface standing between a class and its base class?

Note: I tagged design patterns just in (the unlikely) case it is actually one. If it's not I'll remove the tag.

consider this example:

template <class _base>
struct SplitPrint: public _base
{
    virtual void printPositive(int positive) = 0;
    virtual void printNegative(int negative) = 0;
    void print( int number) override
    { 
        _base::print(number);
        if (number >= 0)
            printPositive(number);
        else
            printNegative(number);
    }
};

struct Interface
{
    virtual void print( int number) = 0;
};

//implements the interface
struct NormalImplementer : public Interface
{
    void print( int number) override { std::cout << number << "\n"; }
};

//Still implements the interface
struct DifferentImplementer : public SplitPrint<NormalImplementer>
{
    void printPositive (int number) override { if (number > 10) std::cout << "big" << "\n"; }
    void printNegative (int number) override { if (number < -10) std::cout << "small" << "\n"; }
};

//Still implements the interface
struct TellSign : public SplitPrint<DifferentImplementer>
{
    void printPositive (int number) override { std::cout << "also, positive" << "\n"; }
    void printNegative (int number) override { std::cout << "also, negative" << "\n"; }
};


int main()
{
  NormalImplementer printer1;
  DifferentImplementer printer2;
  TellSign printer3;

  printer1.print(5); //5
  printer1.print(-42); //-42

  printer2.print(5); //5
  printer2.print(-42); //-42 small

  printer3.print(5); //5 also, positive
  printer3.print(-42); //-42 small also, negative
}

Here I split the pure virtual method "print" in two other methods, DifferentImplementer doesn't have to know how to print a number (silly example but hopefully you understand what I mean) as long as it knows how to print a positive number and how to print a negative one.

Do this OOP problem have a name? Is this example a good way to solve this problem in C++? is there a better/cleaner way to solve this problem in C++?

Local variables and dynamic memory allocation. Smart pointers [duplicate]

This question already has an answer here:

Profiling our project I have found poor code and I need to suggest best solution. I deliberately simplified the code for ease of understanding. The situation is the following:

struct TResource {};
typedef std::vector<TResource*> TResources;

struct TProgramm
{
    // Comment destructor to reproduce memory leaks
    ~TProgramm()
    {
        for(auto r : _resources)
        {
            delete r;
            r = nullptr;
        }
        _resources.clear();
    }

    TResources _resources;
};

struct TEpgSchedule
{
    TProgramm _program;
};
typedef std::vector<TEpgSchedule> TEpgSchedules;

void getEpgSchedules(TEpgSchedules& epg_schedules)
{
    TEpgSchedule epg_schedule; //crash code
    TResource* resource = new TResource();

    epg_schedule._program._resources.push_back(resource);
    epg_schedules.push_back(epg_schedule);
}

int main(int , char **)
{
    TEpgSchedules epg_schedules;
    getEpgSchedules(epg_schedules);
    // Doing more things with epg_schedules....

    return 0;
}

Initial problem was in memory leaks. To resolve it I have added destructor to the TProgramm struct. I have told myself - good job - but after running of my application I have received crash. After investigation of this new issue I found code labeled in my code as 'crash code'. It is clear that after adding destructor to the Programm struct my main function does the following:

  1. Create local variable epg_schedule in getEpgSchedules() function;
  2. Create new TResource and push it to the resources of the programm;
  3. Calling TEpgSchedule copy constructor for line epg_schedules.push_back(epg_schedule);
  4. Delete epg_schedule and its resources on getEpgSchedules() exit;
  5. Repeatedly deleting epg_schedulesom main() exit - crash!!!

Could you suggest how to refactor this code to avoid memory leaks and crashes?

How to Implement Generic builder with Mandatory ( required fields)?

this thread along with this blog Show very great examples of how to implement generic-builder but both of them assume that all fields are optional. in the builder pattern we use builderclass for the optional fields while all required fields should be added in the constructor of the class itself.

My question how to implement a generic builder that force to add values for required fields.

Need I apply design pattern for fill document data

I am using C# to create a document data.

public class Document{
      public string CreatorUsername {get;set;}
      public string CreatorDepartment {get;set;}
      public string DataFromServiceExternalService1 {get;set;}
      public string DataFromServiceExternalService2 {get;set;}
      public string DataFromServiceExternalService3 {get;set;}
      public string DataFromWebConfig {get;set;}
}

The document data properties are comes from different services, applciation username, web config like this.

I need to wait downlaod Service1, Service2, Service2, Web.config results. After all data come I will create document.

I am new at design patterns and I wonder if I apply a design pattern about this problem. For example decorator patten or else.

Generic class method computation based on variable input

I roughly got the following setup:

#include <iostream>
using namespace std;

template<typename T>
class Element{
    T getX() const;
    T getY() const;
 private:
    T x,y;
    std::vector<float> handling_times;
    float cost;
};

template<typename T, typename Tnext>
class Bloc {
     T getX() const;
     T getY() const;
 private:
     T x,y;
     float effort;
     float damage_done;
};

template<typename T>
class Measurements {
void calcMeasurements(const std::vector<T*> &data);
     float getMean() const;
 private:
     float mean;
};


int main() {
     std::vector<Element<int>*> elements;
     // fill with elements
     std::vector<Bloc<float>*> blocs;
     // fill with blocs

     // calculate mean of blocs effort
     Measurements<Bloc<float>> bloc_mean_effort_measurement;
     bloc_mean_effort_measurement.calcMeasurements(blocs);

     return 0;
 }

So two classes Element and Bloc which hold some data I'd like to perform Measurements on. For example, I'd like to measure the getMean() of an Element's handling_times which is of type std::vector<float>. Another case would be to measure the mean of std::vector<Bloc<float>*> blocs based on the effort stored in each Bloc. As you can see the input types for an Measurement vary but the functionality behind the mean calculation always stays the same. I'd like to have this functionality only implemented once (mean is only the simplest example I could think of) and use it on different types. Furthermore, I can't get my head around, how to pass the Measurement object based on which entity (e.g. Element costs or Bloc effort) the measure should be computed. Would it make sense to have an enum PossibleMeasurements in Element with HANDLING_TIMES and COSTS. So to say for each private variable I would like to be able to compute measures on.

neural network back propagation hidden error become zero. working on mnist_data_train_100_csv file

def backpropagation(x,weight1,weight2,bais1,bais2,yTarget):
    del1=np.zeros((weight1.shape))
    del2=np.zeros((weight2.shape))
    bel1=np.zeros((bais1.shape))
    bel2=np.zeros((bais2.shape))
    hh=forward(weight1,x,bais1)
    hhout=sigmoid(hh)
    oo=forward(weight2,hhout,bais2)
    oout=sigmoid(oo)
    e=sum((oout-yTarget)**2)/2
    ooe=-(yTarget-oout)*(oout*(1-oout))
    hhe=np.dot(weight2.T,ooe)*(hhout*(1-hhout))
    del2=del2+np.dot(hhout,ooe.T)
    del1=del1+np.dot(x,hhe.T)
    bel1=bel1+hhe
    bel2=bel2+ooe
    return del1,del2,bel1,bel2

def forward(weight,inp,b):
    val=np.dot(weight.T,inp)+b
    return val

def sigmoid(x):
    val=1.0/(1.0+np.exp(-x))
    return val

here in backpropagation() value of this hhout*(1-hhout) making all 0. so it is right or wrong please correct me

SQL specification in repository pattern

I just read this article http://ift.tt/2mcMHzu he only few methods in his repository and one method query(SqlSpecification $specification). He creates object for each Query he needs. here is the codes:

the repository class ( i only mention the query method):

@Override
public List<News> query(Specification specification) {
    final SqlSpecification sqlSpecification = (SqlSpecification) specification;

    final SQLiteDatabase database = openHelper.getReadableDatabase();
    final List<News> newses = new ArrayList<>();

    try {
        final Cursor cursor = database.rawQuery(sqlSpecification.toSqlQuery(), new String[]{});

        for (int i = 0, size = cursor.getCount(); i < size; i++) {
            cursor.moveToPosition(i);

            newses.add(toNewsMapper.map(cursor));
        }

        cursor.close();

        return newses;
    } finally {
        database.close();
    }
}

the SQL specification:

public class NewestNewsesSpecification implements SqlSpecification {

@Override
public String toSqlQuery() {
    return String.format(
            "SELECT * FROM %1$s ORDER BY `%2$s` DESC;", 
            NewsTable.TABLE_NAME, 
            NewsTable.Fields.DATE
    );
}
}

and he create object for every new sql he needs, such as newsById($id) and so on....

in the newbie's sight like me, it seems interesting but I am afraid this is not a good practice to follow.

my question is simple, is this good practice and worth to follow?