inheritance – How to override nullable field with non-nullable one dart

I have a class with a nullable property. I would like to make a superclass that overrides that property with a non nullable one

so

class Example {
String? name;
}

class NamedExample extends Example {
@override
String name;

}

Is there some way to do that? if not how is this goal conventionally accomplished.

I basically want two identical classes except one of them always has a property while it is optional in another.

inheritance – How to create inherrited copy constructor in c++, with a base class object in the parameter

Im new to c++ from java, i wanted to know what im doing wrong i would like to create

I wanna create a copy constructor in my derived class (MOTORCYCLE) that takes base class object parameter Vehicle then use the vehicle vector holding my desired object to pass those values in the constructor

everytime i do it i just get the EMPTY variable i made

Motorcycle::Motorcycle(const Vehicle &t,string outDate,double cost,int daysOut )
{
    this->t = t;
    this->outDate = outDate;
    this->cost = cost;
    this->daysOut= daysOut;
}

THEN i wish to call that member
like so

 class Motorcycles motorcycle(VehicleVector(2).getTitle(),"05-07-1997",5.0,8);


WORKING JAVA EXAMPLE:

public Motorcycle(Vehicle T, String Group, int RPM) {
        super(T);
        this.Grupo = Grupo;
        this.RPM = RPM;

    }

c++ – Factorize a function where inheritance is unwanted

I have this piece of code which I’d like to improve:

std::optional<IntersectionInfo> Scene::intersects(const Ray& ray) const
{
    float closest = std::numeric_limits<float>::max();
    int index = -1;

    int i = 0;
    for(auto& sphere : _spheres)
    {
        auto (b, d) = Intersections::intersects(ray, sphere._shape);
        if(b && d < closest)
        {
            closest = d;
            index = i;
        }

        i++;
    }

    i = 0;
    bool isPlane = false;
    for(auto& plane : _planes)
    {
        auto (b, d) = Intersections::intersects(ray, plane._shape);
        if(b && d < closest)
        {
            closest = d;
            index = i;
            isPlane = true;
        }

        i++;
    }

    i = 0;
    bool isBox = false;
    for(auto& box : _boxes)
    {
        auto (b, d) = Intersections::intersects(ray, box._shape);
        if(b && d < closest)
        {
            closest = d;
            index = i;
            isBox = true;
        }
    }

    i = 0;
    bool isTri = false;
    for(auto& tri : _triangles)
    {
        auto (b, d) = Intersections::intersects(ray, tri._shape);
        if(b && d < closest)
        {
            closest = d;
            index = i;
            isTri = true;
        }
    }

    if(index != -1)
    {
        IntersectionInfo info;
        info._intersection = ray._position + ray._direction * closest;

        if(isTri)
        {
            info._normal = Intersections::computeIntersectionNormal(ray, info._intersection, _triangles(index)._shape);
            info._material = *_triangles(index)._material;
        }
        else if(isBox)
        {
            info._normal = Intersections::computeIntersectionNormal(ray, info._intersection, _boxes(index)._shape);
            info._material = *_boxes(index)._material;
        }
        else if(isPlane)
        {
            info._normal = Intersections::computeIntersectionNormal(ray, info._intersection, _planes(index)._shape);
            info._material = *_planes(index)._material;
        }
        else
        {
            info._normal = Intersections::computeIntersectionNormal(ray, info._intersection, _spheres(index)._shape);
            info._material = *_spheres(index)._material;
        }

        info._intersection += info._normal * 0.001f;

        return info;
    }

    return {};
}

This function operates over several vectors (_spheres, _planes, _boxes and _triangles) which stores different types. Since the code is syntactically identical (but intersects and computeIntersectionNormal calls varies depending on the input type), I’d like to find a way to improve it.

An obvious solution would be to use inheritance and have a single vector storing a Shape, which would have virtual members for intersects and computeInteresctionNormal, however :

  • I do not wish to change the existing type structures just for the sake of this function.
  • This function is an hot loop of my program inheritance has shown a visible cost.

I’d also would like to avoid macros (unless they are really simple).

I came up with this :

enum class ShapeType
{
    None,
    Sphere,
    Plane,
    Box,
    Triangle
};

template<typename Shape>
std::function<IntersectionInfo()> intersectsWithShapes(const std::vector<MaterialShape<Shape>>& materialShapes, const Ray& ray, ShapeType currentType, float& closest, int& index, ShapeType& type)
{
    int i = 0;
    for(const auto& materialShape : materialShapes)
    {
        auto (b, d) = Intersections::intersects(ray, materialShape._shape);
        if(b && d < closest)
        {
            closest = d;
            index = i;
            type = currentType;
        }

        i++;
    }

    return (&)()
    {
        IntersectionInfo info;
        info._intersection = ray._position + ray._direction * closest;
        info._normal = Intersections::computeIntersectionNormal(ray, info._intersection, materialShapes(index)._shape);
        info._material = *materialShapes(index)._material;

        info._intersection += info._normal * 0.001f;

        return info;
    };
}

std::optional<IntersectionInfo> Scene::intersects(const Ray& ray) const
{
    float closest = std::numeric_limits<float>::max();
    int index = -1;
    auto type = ShapeType::None;

    auto F1 = intersectsWithShapes(_spheres, ray, ShapeType::Sphere, closest, index, type);
    auto F2 = intersectsWithShapes(_planes, ray, ShapeType::Plane, closest, index, type);
    auto F3 = intersectsWithShapes(_boxes, ray, ShapeType::Box, closest, index, type);
    auto F4 = intersectsWithShapes(_triangles, ray, ShapeType::Triangle, closest, index, type);

    decltype(F1) F;

    switch(type)
    {
        case ShapeType::None: return {};
        case ShapeType::Sphere: F = F1; break;
        case ShapeType::Plane: F = F2; break;
        case ShapeType::Box: F = F3; break;
        case ShapeType::Triangle: F = F4; break;
    }

    return F();
}

I prefer this over the above function because adding a shape is simpler and less prone to error, and the entire interesting code is located in a small function. But it’s not ideal because now Scene::intersects() is entirely made of boilerplate code, it’s not obvious to guess why intersectsWithShapes returns a lambda, and this introdoces a visible code (althrough this time, only in debug build).

object oriented – Select inheritance hierachy at run time

I want to model a machine with a class machine. By the way the architecture of the project has been built, the module that defines each machine is its own directory.
So in directory manufacturer/machine_111/ there is a file machine.py

Class Machine(ModelX):
     def __init__(self):
     ....
     def do_something(self):
     ...

Each machine can inherit common behaviour form by being of the same model. So in manufacturer/models/ there is ‘modelX.py`

Class ModelX(BaseMachine):
    ....

It also inherits from the BaseMachine class in the main directory of the project.

My problem is that, for some machines, I don’t have special behaviour to inherit from the ModelX class. And some other machines are fine to be modelled with the BaseMachine class. I have more than 500 machines now and there is a lot of boilerplate code copied in the machines own directory to define or make an instance of the proper class in the hierarchy.

My goal is not to have to write the machine_111 module or the modelX.py if it is not needed. The current plan is to have some kind of conifguration file (JSON, or other format), to choose the the classes to inherit from.

In summary, I want to be able to write something like this:

a_machine = BaseMachine() # if there is no `modelX.py` and `model_11.py`
a_mahcine = ModelX() # if there is not `model_11.py` but there is `modelX.py`
a_machine = Machine() # if `model_111.py` exist

but the inheritance chain should be different. If modelX.py, ‘Machineinherits from it, and if not in inherits directly fromBaseMachine`.

What tools and design patterns can I use?

object oriented – Python inheritance: how to check the closest abstract parent class?

I’m dealing with two categories of machine learning algorithms. For simplicity, let’s call them A and B.

There are multiple concrete algorithms in each category, and my goal is to implement all of them. Because of this, my initial plan was to define abstract classes CategoryAAlgorithms and CategoryBAlgorithms, and have each of them define a set of methods that must be implemented by the concrete algorithms. So far so good – these abstract classes serve as a nice template and I find that they make my project a lot more understandable.

However, after I’ve done this, I found that the abstract methods defined in CategoryBAlgorithms contain all the abstract methods defined in CategoryAAlgorithms.

To avoid code duplication, I want to have CategoryBAlgorithms inherit from CategoryAAlgorithms. However, somewhere else in my code I do the following checks:

# just an example
if isinstance(some_instance_of_a_concrete_algorithm, CategoryAAlgorithms):
    do_some_kind_of_preprocessing()
elif isinstance(some_instance_of_a_concrete_algorithm, CategoryBAlgorithms):
    do_some_other_kind_of_preprocessing()

This means that, if I do the inheritance, then for a concrete algorithm from category B, both if statements would be true.

Is there a way for me to get around this issue? My initial thought was to check for the closest abstract parent, but I don’t think this is a clean solution, so I welcome other ideas.

Thanks in advance.

java – Composition or Inheritance for classes with almost similar implementations but different input and outputs for methods?

I have the following classes, which have quite similar method implementations. Only the classes’ method inputs and outputs seem to be of different types. When I put it like this, it sounds like a case for inheritance, however, the fact that the inputs and outputs are different and are related to two lambdas, make me wonder if they should remain without any relationship, as one lambda cannot be thought of in place of another (To be a case for inheritance).

My first class looks like the following.

public class JobPersistenceManager {
    private String jobIndexName;
    private JobLambda JobLambda;
    private MyDataPersistence myDataPersistence;
    private DataProcessorUtils dataProcessorUtils;
    private static final String JOB_ID = "jobId";
    private static final String JOB_NAME = "jobName";

    @Inject
    public JobPersistenceManager(String jobIndexName,
                                 JobLambda JobLambda,
                                 MyDataPersistence myDataPersistence) {
        this.jobIndexName = jobIndexName;
        this.JobLambda = JobLambda;
        this.myDataPersistence = myDataPersistence;
        createIndexIfNotExists(this.jobIndexName);
    }

    public SearchDocumentResult searchJob(MyJobInput myJobInput) throws IOException {
        return myDataPersistence
                .searchDocument(this.jobIndexName,
                        dataProcessorUtils.transformObjectDataPayloadToMap(myJobInput));
    }

    public MyJobOutput invokeCreateJobLambdaAndIndexData(final MyJobInput myJobInput)
            throws IOException {
        String personRequestPayload = dataProcessorUtils.transformObjectDataInputJson(myJobInput);
        Map<String, String> createdJobOutput = this.JobLambda.invokeLambda(personRequestPayload);
        this.indexCreatedJob(myJobInput, createdPersonOutput);
        return MyJobOutput.builder().withJobID(createdJobOutput.get(JOB_ID))
                .withJobName(createdJobOutput.get(JOB_NAME)).build();
    }

    public int indexCreatedJob(final MyJobInput myJobInput,
                               final Map<String, String> createdJobOutput) throws IOException {
        myJobInput = modifyJobInput(myJobInput);
        String documentToIndex = dataProcessorUtils.transformObjectDataInputJson(myJobInput);
        return myDataPersistence.indexDocument(this.jobIndexName, documentToIndex);
    }

    private void createIndexIfNotExists(final String indexName) {
        if (!myDataPersistence.doesIndexExist(indexName)) {
            myDataPersistence.createIndex(CreateIndexInput.builder().indexName(indexName).build());
        }
    }
}

My second class looks like the following.

public class EmployeePersistenceManager {
    private EmployeeLambda employeeLambda;
    private MyTestDataPersistence myTestDataPersistence;
    private DataProcessorUtils dataProcessorUtils;
    private String employeeIndexName;
    private static final String PERSON_ID_KEY = "personId";
    private static final String PERSON_NAME_KEY = "personName";

    @Inject
    public EmployeePersistenceManager(String employeeIndexName,
                                    EmployeeLambda employeeLambda,
                                    MyTestDataPersistence myTestDataPersistence,
                                    DataProcessorUtils dataProcessorUtils) {
        this.employeeIndexName = employeeIndexName;
        this.employeeLambda = employeeLambda;
        this.myTestDataPersistence = myTestDataPersistence;
        this.dataProcessorUtils = dataProcessorUtils;
        createIndexIfNotExists(employeeIndexName);
    }

    public SearchDocumentResult searchPerson(EmployeeInput employeeInput) throws IOException {
        return myTestDataPersistence
                .searchDocument(employeeIndexName,
                        dataProcessorUtils.transformObjectDataPayloadToMap(employeeInput));
    }

    public EmployeeOutput invokeCreatePersonLambdaAndIndexData(final EmployeeInput employeeInput)
            throws IOException {
        String personRequestPayload = dataProcessorUtils.transformObjectDataInputJson(employeeInput);
        Map<String, String> createdPersonOutput = this.employeeLambda.invokeLambda(personRequestPayload);
        this.indexCreatedEmployee(employeeInput, createdPersonOutput);
        return EmployeeOutput.builder().withPersonId(createdPersonOutput.get(PERSON_ID_KEY))
                .withPersonName(createdPersonOutput.get(PERSON_NAME_KEY)).build();
    }

    public int indexCreatedEmployee(final EmployeeInput employeeInput,
                                  final Map<String, String> createdPersonOutput) throws IOException {
        employeeInput = modifyEmployeeInput(employeeInput);
        String documentToIndex = dataProcessorUtils.transformObjectDataInputJson(employeeInput);
        return myTestDataPersistence.indexDocument(this.employeeIndexName, documentToIndex);
    }

    public Map.Entry<String, Map<String, String>> invokeLambda(final String payload) {
        return new AbstractMap.SimpleEntry<>(payload, this.employeeLambda.invokeLambda(payload));
    }

    private void createIndexIfNotExists(final String indexName) {
        if (!myTestDataPersistence.doesIndexExist(indexName)) {
            myTestDataPersistence.createIndex(CreateIndexInput.builder().indexName(indexName).build());
        }
    }
}

As you can see, the methods perform almost the same actions. Only the indexCreatedEmployee and indexCreatedJob methods from the classes have an extra step of processing the input.

Should I keep these classes as they are now without any relationships between them, or should I create an abstract persistence manager class and perform the following.

  1. Move createIndexIfNotExists to the abstract class
  2. Create abstract methods search(), invokeLambda() and indexCreatedData() methods and implement them in each child class. The data types MyJobInput and MyEmployeeInput are POJO classes that don’t have any relationship. So I guess these methods I mentioned would then take “Object” parameters?

EmployeeLambda and JobLambda are again classes with no relationship between them. Another concern I had towards creating some sort of inheritance was that, Employee Lambda and JobLambda cannot be used inter-changeably. So was wondering if they should inherit the same parent class just because they’re both lambda classes.

OR is there another way to go about this? Any advice would be much appreciated. Thank you very much in advance.

Powershell SharePoint 2010 capture Permissions of folders in library with Broken Inheritance

I am looking for some code to find all users or Ad Group who have some sort of permission in specific folder (with broken Permission) in a specific library of a team-site. With the following code I can find all the folder within a library that has unique permission (Broken Inheritance)

$web = Get-SPWeb $SiteURL #$($SiteIdentity.Url)
Write-Host "Site: " $web.Title
#$list = $web.Lists("Shared Documents") 
$list = $web.GetList($web.Url +"/Documents/")
write-host "Library Title: "$list.Title
$list.Folders  | ft Name, HasUniqueRoleAssignments, Folder

But not getting the list of users/AD group those have some sort of(read , contrib etc) permission on that specific folder.

inheritance – Duplicate document libraries

I am very new to sharepoint and need a little help

I have created a communications site, I have then created new pages within the site and inserted a document structure. I then began to populate the document structure with folders only to find that the same folder structure had appeared on the other pages and what ever I do to one it happens on all, how do i break the inheritance please? I need all pages to be different

Hope that makes sense?

postgresql – TimescaleDB database design – should I use inheritance?

I have the following TimescaleDB hypertable:

CREATE TABLE public.data
(
    event_time timestamp with time zone NOT NULL,
    pair_id integer NOT NULL,
    entry_id bigint NOT NULL,
    event_data1 int NOT NULL,
    event_data2 int NOT NULL,
    CONSTRAINT con1 UNIQUE (pair_id, entry_id ),
    CONSTRAINT pair_id_fkey FOREIGN KEY (pair_id)
        REFERENCES public.pairs (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
    <unique index on event_time, pair_id, entry_id>
)

<Some continuous aggregates>

But when querying this data I would actually never need to just get data across pair_id’s such as:
SELECT * FROM data WHERE <some condition on the time>

Instead I would like to query the data such that I get the data joined on the event_time for each pair_id – something like this:

event_time pair_id1_event_data1 pair_id1_event_data2 pair_id2_event_data1 pair_id2_event_data2

Or:

|event_time | pair_id1_continous_agregate1 | pair_id1_continous_agregate2 | pair_id2_continous_agregate1 | pair_id2_continous_agregate2 | … |
| — | — | — | — | — | — |
Sorry for not writing the actual query, I’m still learning how to do this.

Given I have 1000s of pair_ids, does this database design make sense to have efficient query performance?

The alternative I am considering is to use inheritance like this https://www.postgresql.org/docs/current/ddl-inherit.html:
I have about 5 types of data stored in this table, some of them have an extra column or two

  1. Create a parent table
  2. For each data_type create a data_type_table inheriting from the parent table
  3. For each pair_id create a table inheriting from the appropriate data_type_table

Questions

  • A) Is this type of inheritance even supported in TimescaleDB?
  • B) Would this improve my query performance?
  • C) Is there another alternative which would be better?

c++ – Inheritance Access Issue

Am geting the following error, “Use of deleted function ‘Derived::Derived'” while executing the below code related to Inheritance. Also in the note it says, “Derived::Derived() is implicitly deleted because
the default definition would be ill informed”. Can someone help me in fixing this:

#include <iostream>

//BASE CLASS
class Base
{
public:
    int a;
    
    void display()
    {
        std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
    }
    
    //constructor
    Base(int la, int lb, int lc) : a {la}, b {lb}, c {lc}
    {
        
    }

protected:
    int b;

private:
    int c;
};

//DERIVED CLASS
class Derived : public Base
{
    //a from Base is Public
    //b from Base is Protected
    //c from Base has No access
    
public:
    void access_base_members()
    {
        a = 100;    //OK since a is Public in parent
        b = 200;    //OK since b is Protected type in Parent. So derived CLASS will have access
        //c = 300;    //NOK since c is private in parent and hence cannot be accessed
    }
};


int main()
{
    std::cout << "nBase Member access=>nn";
    
    Base base(1,2,3);
    base.a = 10; //OK
    //base.b = 20; //NOK since Protected
    //base.c = 30; //NOK since Private
    base.display();

    Derived derived;
    derived.a = 111;        //OK since public in parent
    //derived.b = 222;        //NOK since protected members cannot have direct access in OBJECTS
    //derived.c = 333;        //NOK since private
}