Unit – Inheritance – Access to child class values

If you want to share a variable, you must define it in the parent or base class. If you define it as protected or public, it is accessible to all children and children. It's like copying the variable into all.

Basically, in OOP, low-level components should depend on high-level components without inversion. So, if you define a variable in the child class and access it in the parent class, you are violating the rules (I did not test it, but it should be impossible). Basically, you instantiate concrete or subordinate classes.

If you think so, your design is wrong. Just read over (OOP, solid, Uncle Bob)

Change states from child to parent while observing the SOLID principles

In artificial examples of some kind, it is often not clear whether or not they violate SOLID, and it is impossible to meaningfully rate the code as "good" or "bad". For example, the DIP says

"High-level modules should not depend on low-level modules, and both should depend on abstractions (such as interfaces)."

But what is "a high-level module" and what is "a low-level module" in this example? That's probably a matter of taste with a so invented car / driver example. You can see both the car and the driver together as "one module", or you can see each one of them as a module in their own right. For the latter case, it's easy to solve the mentioned DIP problem: just imagine another one IDriver Interface and make ICar depend on it Driver,

But is that "better"? Adding the interface makes the code a bit more complicated, and if that does not serve a purpose, it violates the KISS principle.

Another detail in your code is the weird-looking side effect in ExampleCar.Drive, Change the reference to a completely new car object within Drive looks inconspicuous to me – the "refueling" of the existing car would probably be more obvious, such as

 public void Drive(Driver owner){
    if(fuel > 0){
        fuel--;
        Console.Writeline("driving exampleCar. Fuel: " + fuel);
        return;
    }
    fuel=200;
    Console.Writeline("exampleCar refuled. Fuel: " + fuel);
 }

Perhaps this could be a violation of the "principle of least astonishment". If it is so Really A violation can only be evaluated in the context of a real application with real classes and real use cases. Perhaps there are reasons why the original side effect is necessary, and perhaps the effect in the "real" context may not look as unexpected to a user of those classes.

In short, there are more programming principles than just SOLID. Their application often requires compromises, and artificial examples usually lack sufficient context to rate them as "good" or "bad" in design.

Design Pattern – Preferred way to interact with parent and child components at an angle

I'm writing a web app in Angular 8.
There is a logic where a child component must interact with the parent component and vice versa.

Below is a diagram. I implemented the first approach, but I was wondering if it would be better to implement the second approach.

Code from my service

export class ScoreService {

  constructor() { }

  private matchWinnerSource = new Subject();

  // Child component is subscribed to this observable
  matchWinner = this.matchWinnerSource.asObservable();

  // Parent component calls this method
  setMatchWinner(winnerId: number, winnerStringRepresentation: string, matchId: number) {
    const data = {
      id: winnerId,
      winnerStringRepresentation,
      matchId
    }
    this.matchWinnerSource.next(data);
  }
}

Enter image description here

Note: Not sure if Desgin Patterns is an appropriate day here.

Export data from DHIS2 with link between parent and child tables?

We try to export a "parent table" with their "child table", if we can call it that.
Both are linked by a relationship type. When data is added to the parent table, the user can switch to the Relationship tab and add more data, which works very well.

The problem is with the export. The data is exported separately without linking or linking between them. We use an online server for DHIS2, so we do not have direct access to the database structure.

If this issue is resolved, we can use DHIS2 to reach the final implementation level. And the connection between these two tables is sensitive.

How can data from both tables be exported with a join / key connection between both tables?

dhis2 – Parent and child tables are exported without a join key, although there is a relationship.

We try to export a "parent table" with their "child table", if we can call them that.
Both are linked by a relationship type. When data is added to the parent table, the user can switch to the Relationship tab and add more data, which works very well.

The main problem is the export. The data is exported separately without linking or linking between them. We use an online server for DHIS2, so we do not have direct access to the database structure.

If this problem is resolved, we are ready to use DHIS2 for the final phase of the implementation. And the connection between these two tables is sensitive.

How can data from both tables be exported with a join / key connection between both tables?

python – Object of a class that moves from the main process to the child process

I'm trying to use multiprocessing in a class. I use Multiprocessing.Pipe () to pass instance o from the parent process to the child process.

Here I call the Multiprocessing.pipe (): –

conn1, conn2 = multiprocessing.Pipe()


        self.devices = bussiness.initilaztion(self.comm_object,logger)

        conn1.send(self.devices)

        self.callmotor1dprocess = 

        multiprocessing.Process(target=callallmotor1d,args=(conn2))

        self.listofthread.append(self.callmotor1dprocess)

        self.callsov1sprocess =  

        multiprocessing.Process(target=callallsov1s,args=(conn2))

        self.listofthread.append(self.callsov1sprocess)

I call this code within the class. Now I should call method out of class.

 def callallmotor1d(conn):
    devices = conn.recv()
    while True:
        bussiness.motorallprocessing(devices)


def callallsov1s(conn):
    while True:
        devices = conn.recv()
        bussiness.allsov1processing(devices)

Now I call all multiprocessing initiate

def startprocess(self):
        for item in self.listofthread:
            item.start()
        self.button3.config(text="started")

   def stopprocess(self):
        for item in self.listofthread:
            item.kill()

But I got the mistake that is very common:
Error message:-

can't pickle _thread.lock objects
Traceback (most recent call last):
 File "C:/Users/misu01/PycharmProjects/opcua/ui_v7.py", line 226, in initilization conn1.send(devices)
 File "C:Usersmisu01AppDataLocalProgramsPythonPython37libmultiprocessingconnection.py", line 206, in send self._send_bytes(_ForkingPickler.dumps(obj))
 File "C:Usersmisu01AppDataLocalProgramsPythonPython37libmultiprocessingreduction.py", line 51, in dumps cls(buf, protocol).dump(obj)
TypeError: can't pickle _thread.lock objects

I do not know why the thread.lock object is created in my Alldevices class. I never used thread.lock in my class.

To avoid this error, I am trying to change my Alldevices class as follows:

Here is my change: –

Nevertheless, I got a mistake.
Is this my implementation correct?

Here self.allmotor1dobjects, self.allsov1sobjects, etc. are also class instances. I suspect that I have invoked instances of classes in my alldevice class because this does not work.

How can I fix this?

I'm not sure if multiprocessing.pipe () is the correct way to send an instance of the class to the main process to the child process

I also try to know how to create the thread.lock () object in my alldevice class.

Any help in this regard is greatly appreciated

class AllDevices:


def __init__(self,comobject,logger):
    self.mylock = threading.Lock()
    self._comobject = comobject
    dfM1D = pd.read_excel(r'D:OPCUAWorking_VF1.xls', sheet_name='Motor1D')
    dfM2D = pd.read_excel(r'D:OPCUAWorking_VF1.xls', sheet_name='Motor2D')
    dfsov1S = pd.read_excel(r'D:OPCUAWorking_VF1.xls', sheet_name='Valve1S')
    dfsov2S = pd.read_excel(r'D:OPCUAWorking_VF1.xls', sheet_name='Valve2S')
    dfanalog = pd.read_excel(r'D:OPCUAWorking_VF1.xls', sheet_name='AnalogTx')
    dfcontrolvalve = pd.read_excel(r'D:OPCUAWorking_VF1.xls', sheet_name='ControlValves')
    dfvibrofeeder = pd.read_excel(r'D:OPCUAWorking_VF1.xls', sheet_name='VibroFeeder')
    dfconveyor = pd.read_excel(r'D:OPCUAWorking_VF1.xls', sheet_name='Conveyor')
    dfdrives = pd.read_excel(r'D:OPCUAWorking_VF1.xls', sheet_name='Drive')

    self.allmotor1dobjects = callallmotor1D_V1.Cal_AllMotor1D(dfM1D, comobject, logger)
    self.allmotor2dobjects =  callallmotor2D_V1.Cal_AllMotor2D(dfM2D,comobject,logger)
    self.allsov1sobjects = callallsov1S_V1.Cal_AllSov1S(dfsov1S,comobject,logger)
    self.allsov2sobjects = callallsov2S_V1.Cal_AllSov2S(dfsov2S, comobject,logger)
    self.allanalogobjects = calallanalog_V1.Cal_AllAnalogInputs(dfanalog,comobject,logger)
    self.allcontrolvalveobjects = calallcontrolvalves_V1.Cal_AllControlValve(dfcontrolvalve,comobject,logger)
    self.allvibrofeederobjects = callallvibrofeeder_V1.Cal_AllVibroFeeder(dfvibrofeeder,comobject,logger)
    self.allconveyorobjects = callallconveyor_V1.Cal_AllConveyor1D(dfconveyor,comobject,logger)
    self.allabbdrivesobjects = calallABPdrives_V1.Cal_AllDrives(dfdrives, comobject,logger)

    def __getstate__(self):
    # Copy the object's state from self.__dict__ which contains
    # all our instance attributes. Always use the dict.copy()
    # method to avoid modifying the original state.
    state = vars(self).copy()
    # Remove the unpicklable entries.
    del state('mylock')
    return state

def __setstate__(self, state):
    # Restore instance attributes.
    vars(self).update(state)
    self.mylock = threading.Lock()

@property
def allmotor1d(self):
    return self.allmotor1dobjects

@property
def allsov1s(self):
    return self.allsov1sobjects

No improvement of the error: –

2019-09-06 10: 54: 17,835: _thread.lock objects can not be cracked
Tracing (last call last):
File "C: Users misu01 Desktop SMS_SIMULATION ui_v7.py", line 220, in Initialization
conn1.send (devices)
File "C: Users misu01 AppData Local Programs Python Python37 lib multiprocessing connection.py", line 206, in send
self._send_bytes (_ForkingPickler.dumps (obj))
File "C: Users misu01 AppData Local Programs Python Python37 lib multiprocessing reduction.py", line 51, in dumps
cls (buf, protocol) .dump (obj)

python – iterates on child XML elements and their children and children, and so on, without nested for loops

I have written a program that reads and processes XML files submitted by external users. The part of the code goes through the children of the XML node, appends a dictionary – a future row in a table – and repeats the process for each child and its child, and so on.

The example XML node looks like this:

xmlstr =  '1065106.46675706.310.0023750.000.000.001041356.46675706.310.000.000.000.00466158.9359838.400.000.000.000.000.000.000.000.000.000.000.000.000.001065106.46675706.310.00556001.19138410.820.0050000.0050000.000.00509105.27537295.490.000.000.000.000.000.000.00

Code I wrote (hold on, he's pretty ugly):

# code to help you get started
from lxml import etree
tree = etree.fromstring(xmlstr)
tree.xpath('.')(0).getchildren()
xml_node = tree.xpath('.')(0)

# real use case starts here
table = ()
tmp = {}
for b in xml_node:
    lvl = 0
    tag = b.tag
    txt = b.text

    table.append(tmp)
    tmp = {}
    tmp('lbl') = tag
    tmp('lvl') = lvl

    for elem in b.getchildren():
        lvl = 1
        tag = elem.tag
        txt = elem.text
        if tag.lower().strip().startswith('foo'):
            tmp(tag) = txt
        else:
            table.append(tmp)
            tmp = {}
            tmp('lbl') = tag
            tmp('lvl') = lvl

        for el in elem.getchildren():
            lvl = 2
            tag = el.tag
            txt = el.text
            if tag.lower().strip().startswith('foo'):
                tmp(tag) = txt
            else:
                table.append(tmp)
                tmp = {}
                tmp('lbl') = tag
                tmp('lvl') = lvl

            for e in el.getchildren():
                lvl = 3
                tag = e.tag
                txt = e.text
                if tag.lower().strip().startswith('foo'):
                    tmp(tag) = txt
                else:
                    table.append(tmp)
                    tmp = {}
                    tmp('lbl') = tag
                    tmp('lvl') = lvl

                for e in e.getchildren():
                    lvl = 4
                    tag = e.tag
                    txt = e.text
                    if tag.lower().strip().startswith('foo'):
                        tmp(tag) = txt
                    else:
                        table.append(tmp)
                        tmp = {}
                        tmp('lbl') = tag
                        tmp('lvl') = lvl

                    for e in e.getchildren():
                        lvl = 5
                        tag = e.tag
                        txt = e.text
                        if tag.lower().strip().startswith('foo'):
                            tmp(tag) = txt
                        else:
                            table.append(tmp)
                            tmp = {}
                            tmp('lbl') = tag
                            tmp('lvl') = lvl

                        for e in e.getchildren():
                            lvl = 6
                            tag = e.tag
                            txt = e.text
                            if tag.lower().strip().startswith('foo'):
                                tmp(tag) = txt
                            else:
                                table.append(tmp)
                                tmp = {}
                                tmp('lbl') = tag
                                tmp('lvl') = lvl

                            for e in e.getchildren():
                                lvl = 7
                                tag = e.tag
                                txt = e.text
                                if tag.lower().strip().startswith('foo'):
                                    tmp(tag) = txt
                                else:
                                    table.append(tmp)
                                    tmp = {}
                                    tmp('lbl') = tag
                                    tmp('lvl') = lvl


                                if e.getchildren():
                                   raise NotImplementedError

# make_sure_last_row_is_appended
try:
    if table(-1)('lbl') != tag:
        table.append(tmp)
except KeyError:
    # probably table has only 1 row
    table.append(tmp)

# remove_technical_first_row
p = table.pop(0)

The output looks like this (as it should be, there is no margin in terms of structure):

( {'lbl': 'Level1', 'lvl': 0, 'Foo_A': '1065106.46', 'Foo_B': '675706.31', 'Foo_B1': '0.00'}, {'lbl': 'Level1_A', 'lvl': 1, 'Foo_A': '23750.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level1_B', 'lvl': 1, 'Foo_A': '1041356.46', 'Foo_B': '675706.31', 'Foo_B1': '0.00'}, {'lbl': 'Level1_B_1', 'lvl': 2, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level1_B_2', 'lvl': 2, 'Foo_A': '466158.93', 'Foo_B': '59838.40', 'Foo_B1': '0.00'}, {'lbl': 'Level1_B_2_1', 'lvl': 3, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level1_B_2_2', 'lvl': 3, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level1_C', 'lvl': 1, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level1_D', 'lvl': 1, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level2', 'lvl': 0, 'Foo_A': '1065106.46', 'Foo_B': '675706.31', 'Foo_B1': '0.00'}, {'lbl': 'Level2_A', 'lvl': 1, 'Foo_A': '556001.19', 'Foo_B': '138410.82', 'Foo_B1': '0.00'}, {'lbl': 'Level2_A_1', 'lvl': 2, 'Foo_A': '50000.00', 'Foo_B': '50000.00', 'Foo_B1': '0.00'}, {'lbl': 'Level2_B', 'lvl': 1, 'Foo_A': '509105.27', 'Foo_B': '537295.49', 'Foo_B1': '0.00'}, {'lbl': 'Level2_B_1', 'lvl': 2, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level2_B_2', 'lvl': 2, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'})

The main problem with this code is that I have no control over the input XML. Theoretically, it can be more nested than I would expect in my code. So far I've & # 39; n & # 39; + 3 for loops written, where & # 39; n & # 39; is the maximum nesting level observed in a test pattern. However, an input XML can be nested more easily than & nbsp; & ngr; + 3.

What I wrote was partly justified because I was in a hurry, but frankly I have no idea how to handle it more elegantly. I've worked through the methods suggested in several articles (for example, this or that), but I have not come up with anything. Maybe this can be done with the statement & # 39; while True … break & # 39; or the method getchildren (), which is hidden in a generator function …

It is also important to keep the data structure so that the lxml._Element.iter () method is a bad idea instead of lxml._Element.getchildren ().

So far, the performance was not a problem.
In the final phase of the remodeling process, I usually improve the variable names and divide the descriptive-name code into the smallest possible functions according to the "clean code" method, so suggestions in this area, though desirable, are subordinate to the main problem.

How can I improve my code?

Entity – why a child class can access an object, not a parent class

I own a block class that is the parent and StandardBlock is the child. A standard block script is attached to the ready-made block. After my little knowledge about inheritance, this would work

public class Block : MonoBehaviour
{
HUD HUDscript;
// Start is called before the first frame update
void Start()
{
    HUDscript = GameObject.FindWithTag("Canvas").GetComponent();  
}
public void OnCollisionEnter2D(Collision2D col)
{
    HUDscript.addPoints();
    Destroy(gameObject);
}
}

and children's class

public class StandardBlock : Block
 {

      // some code
}

But that's the mistake I got

NullReferenceException: The object reference was not set to an instance of an object
Block.OnCollisionEnter2D (UnityEngine.Collision2D col) (under Assets / Scripts / Gameplay / Block.cs: 24)

while writing OnCollisionEnter2D in the children's class it worked out great

SQL Server – Select a column if a specific type of child record exists. Otherwise, a fallback will occur

I have a table named Order, and an order contains several child records in the OrderStatus table.
The order status contains steps that follow the progress of an order. The job status contains a date / time field with a timestamp when the particular status was completed.

I need to retrieve the date stamp of a particular status type (eg XX) if it exists for the order. Otherwise, the date of status YY is used.