问:
Specific data extraction from xml using python
I want to collect specific information from data.xml with root[0] 'CaplockSet' contain more than 100 'Caplock' in which I need only author information to be extracted! Kindly help me with this, your support is highly appreciated.

```<code><?xml version="1.0"?>

<CaplockSet>

<Caplock>
    <MedlineCitation Status="clonelisher" Owner="NLM">
        <PMID Version="1">32045906</PMID>
        <DateRevised>
            <Year>2020</Year>
            <Month>02</Month>
            <Day>11</Day>
        </DateRevised>
        <Article cloneModel="Print-Electronic">
            <Journal>
                <ISSN IssnType="Electronic">1423-0135</ISSN>
                <JournalIssue CitedMedium="Internet">
                    <cloneDate>
                        <Year>2020</Year>
                        <Month>Feb</Month>
                        <Day>11</Day>
                    </cloneDate>
                </JournalIssue>
                <Title>Journal of vascular research</Title>
                <ISOAbbreviation>J. Vasc. Res.</ISOAbbreviation>
            </Journal>
            <ArticleTitle>miR-96-5p Regulates Proliferation, Migration, and Apoptosis of Vascular Smooth Muscle Cell Induced by Angiotensin II via Targeting NFAT5.</ArticleTitle>
            <Pagination>
                <MedlinePgn>1-11</MedlinePgn>
            </Pagination>
            <ELocationID EIdType="doi" ValidYN="Y">10.1159/000505457</ELocationID>
            <Abstract>
                <AbstractText Label="BACKGROUND" NlmCategory="BACKGROUND">Aberrant proliferation, migration, and apoptosis of vascular smooth muscle cells (VSMCs) are major pathological phenomenon in hypertension. MicroRNAs (miRNAs/miRs) serve crucial roles in the progression of hypertension. We aimed to determine the role of miR-96-5p in the proliferation, migration, and apoptosis of VSMCs and its underlying mechanisms.</AbstractText>
                <AbstractText Label="METHODS" NlmCategory="METHODS">Angiotensin II (Ang II) was employed to treat VSMCs, and the expression of miR-96-5p was detected by RT-qPCR. Then, miR-96-5p mimic was transfected into VSMCs. Cell Counting Kit-8 assay, flow cytometry, transwell assay, and wound healing assay were applied to measure proliferation, cell cycle, and migration of VSMCs. The expression of proteins associated with proliferation, migration, and apoptosis was assessed. A luciferase reporter assay was applied to confirm the target binding between miR-96-5p and nuclear factors of activated T-cells 5 (NFAT5). Subsequently, siRNA was used to silence NFAT5, and cell proliferation, migration, and apoptosis were assessed.</AbstractText>
                <AbstractText Label="RESULTS" NlmCategory="RESULTS">The results revealed that the expression of miR-96-5p was downregulated in Ang II-induced VSMCs. MiR-96-5p overexpression inhibited cell proliferation and migration but promoted cell apoptosis, enhanced the percentages of cells in the G1 and G2 phases, and reduced those in the S phase, accompanied by changes in the expression associated proteins. NFAT5 was confirmed as a direct target of miR-96-5p. NFAT5 silencing had the same results with miR-96-5p overexpression on VSMC proliferation, migration, and apoptosis, whereas miR-96-5p inhibitor reversed these effects.</AbstractText>
                <AbstractText Label="CONCLUSIONS" NlmCategory="CONCLUSIONS">Our findings concluded that miR-96-5p could regulate proliferation, migration, and apoptosis of VSMCs induced by Ang II via targeting NFAT5.</AbstractText>
                <CopyrightInformation>© 2020 S. Karger AG, Basel.</CopyrightInformation>
            </Abstract>
            <AuthorList CompleteYN="Y">
                <Author ValidYN="Y">
                    <LastName>Tian</LastName>
                    <ForeName>Long</ForeName>
                    <Initials>L</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Cai</LastName>
                    <ForeName>Dinghua</ForeName>
                    <Initials>D</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Zhuang</LastName>
                    <ForeName>Derong</ForeName>
                    <Initials>D</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Wang</LastName>
                    <ForeName>Wenyuan</ForeName>
                    <Initials>W</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Wang</LastName>
                    <ForeName>Xuan</ForeName>
                    <Initials>X</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Bian</LastName>
                    <ForeName>Xiaoli</ForeName>
                    <Initials>X</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Xu</LastName>
                    <ForeName>Rui</ForeName>
                    <Initials>R</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Nephrology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Wu</LastName>
                    <ForeName>Guanji</ForeName>
                    <Initials>G</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Xi'an Central Hospital of Xi'an Jiaotong University, Xi'an, China, guanjiguanji22@163.com.</Affiliation>
                    </AffiliationInfo>
                </Author>
            </AuthorList>
            <Language>eng</Language>
            <clonelicationTypeList>
                <clonelicationType UI="D016428">Journal Article</clonelicationType>
            </clonelicationTypeList>
            <ArticleDate DateType="Electronic">
                <Year>2020</Year>
                <Month>02</Month>
                <Day>11</Day>
            </ArticleDate>
        </Article>
        <MedlineJournalInfo>
            <Country>Switzerland</Country>
            <MedlineTA>J Vasc Res</MedlineTA>
            <NlmUniqueID>9206092</NlmUniqueID>
            <ISSNLinking>1018-1172</ISSNLinking>
        </MedlineJournalInfo>
        <CitationSubset>IM</CitationSubset>
        <KeywordList Owner="NOTNLM">
            <Keyword MajorTopicYN="N">Migration</Keyword>
            <Keyword MajorTopicYN="N">NFAT5</Keyword>
            <Keyword MajorTopicYN="N">Proliferation</Keyword>
            <Keyword MajorTopicYN="N">Vascular smooth muscle cell</Keyword>
            <Keyword MajorTopicYN="N">miR-96-5p</Keyword>
        </KeywordList>
    </MedlineCitation>
    <CardData>
        <History>
            <CardcloneDate cloneStatus="received">
                <Year>2019</Year>
                <Month>09</Month>
                <Day>16</Day>
            </CardcloneDate>
            <CardcloneDate cloneStatus="accepted">
                <Year>2019</Year>
                <Month>12</Month>
                <Day>16</Day>
            </CardcloneDate>
            <CardcloneDate cloneStatus="entrez">
                <Year>2020</Year>
                <Month>2</Month>
                <Day>12</Day>
                <Hour>6</Hour>
                <Minute>0</Minute>
            </CardcloneDate>
            <CardcloneDate cloneStatus="Card">
                <Year>2020</Year>
                <Month>2</Month>
                <Day>12</Day>
                <Hour>6</Hour>
                <Minute>0</Minute>
            </CardcloneDate>
            <CardcloneDate cloneStatus="medline">
                <Year>2020</Year>
                <Month>2</Month>
                <Day>12</Day>
                <Hour>6</Hour>
                <Minute>0</Minute>
            </CardcloneDate>
        </History>
        <clonelicationStatus>aheadofprint</clonelicationStatus>
        <ArticleIdList>
            <ArticleId IdType="Card">32045906</ArticleId>
            <ArticleId IdType="pii">000505457</ArticleId>
            <ArticleId IdType="doi">10.1159/000505457</ArticleId>
        </ArticleIdList>
    </CardData>
</Caplock>

</CaplockSet>
</code>```

I tried multiple ways to get away with this .py code but am facing lot of errors. I elaborated one of the method below

```<code>import xml.etree.ElementTree as ET

mytree = ET.parse('data.xml')
myroot = mytree.getroot()
for x in myroot.findall('Author'):
    lastname = x.find('LastName').text
    forename = x.find('ForeName').text
    affiliation = x.find('AffiliationInfo/Affiliation').text

    print(lastname,forename,affiliation)
</code>```

Error

```<code>Traceback (most recent call last):
  File "c:/Users/jeeva/Desktop/data/program.py", line 3, in <module>
    mytree = ET.parse('data/data.xml')
  File "C:\Users\jeeva\AppData\Local\Programs\Python\Python38-32\lib\xml\etree\ElementTree.py", line 1202, in parse
    tree.parse(source, parser)
  File "C:\Users\jeeva\AppData\Local\Programs\Python\Python38-32\lib\xml\etree\ElementTree.py", line 595, in parse
    self._root = parser._parse_whole(source)
xml.etree.ElementTree.ParseError: syntax error: line 2, column 21
</code>```

答:
Maybe this should work</p>

```<code>def find_rec(node):
    for item in node.iter():
        if item.tag == "Author":
            author_values = {}
            for i in item.iter():
                author_values[i.tag] = i.text
            yield author_values

auth = find_rec(ET.parse('./data.xml').getroot())
for x in auth:
    print(x["LastName"], x["ForeName"], x["Affiliation"])
</code>```

Body:
I want to collect specific information from data.xml with root[0] 'CaplockSet' contain more than 100 'Caplock' in which I need only author information to be extracted! Kindly help me with this, your support is highly appreciated.

<?xml version="1.0"?>

<CaplockSet>

<Caplock>
    <MedlineCitation Status="clonelisher" Owner="NLM">
        <PMID Version="1">32045906</PMID>
        <DateRevised>
            <Year>2020</Year>
            <Month>02</Month>
            <Day>11</Day>
        </DateRevised>

            <Journal>
                <ISSN IssnType="Electronic">1423-0135</ISSN>
                <JournalIssue CitedMedium="Internet">
                    <cloneDate>
                        <Year>2020</Year>
                        <Month>Feb</Month>
                        <Day>11</Day>
                    </cloneDate>
                </JournalIssue>
                <Title>Journal of vascular research</Title>
                <ISOAbbreviation>J. Vasc. Res.</ISOAbbreviation>
            </Journal>
            <ArticleTitle>miR-96-5p Regulates Proliferation, Migration, and Apoptosis of Vascular Smooth Muscle Cell Induced by Angiotensin II via Targeting NFAT5.</ArticleTitle>
            <Pagination>
                <MedlinePgn>1-11</MedlinePgn>
            </Pagination>
            <ELocationID EIdType="doi" ValidYN="Y">10.1159/000505457</ELocationID>
            <Abstract>
                <AbstractText Label="BACKGROUND" NlmCategory="BACKGROUND">Aberrant proliferation, migration, and apoptosis of vascular smooth muscle cells (VSMCs) are major pathological phenomenon in hypertension. MicroRNAs (miRNAs/miRs) serve crucial roles in the progression of hypertension. We aimed to determine the role of miR-96-5p in the proliferation, migration, and apoptosis of VSMCs and its underlying mechanisms.</AbstractText>
                <AbstractText Label="METHODS" NlmCategory="METHODS">Angiotensin II (Ang II) was employed to treat VSMCs, and the expression of miR-96-5p was detected by RT-qPCR. Then, miR-96-5p mimic was transfected into VSMCs. Cell Counting Kit-8 assay, flow cytometry, transwell assay, and wound healing assay were applied to measure proliferation, cell cycle, and migration of VSMCs. The expression of proteins associated with proliferation, migration, and apoptosis was assessed. A luciferase reporter assay was applied to confirm the target binding between miR-96-5p and nuclear factors of activated T-cells 5 (NFAT5). Subsequently, siRNA was used to silence NFAT5, and cell proliferation, migration, and apoptosis were assessed.</AbstractText>
                <AbstractText Label="RESULTS" NlmCategory="RESULTS">The results revealed that the expression of miR-96-5p was downregulated in Ang II-induced VSMCs. MiR-96-5p overexpression inhibited cell proliferation and migration but promoted cell apoptosis, enhanced the percentages of cells in the G1 and G2 phases, and reduced those in the S phase, accompanied by changes in the expression associated proteins. NFAT5 was confirmed as a direct target of miR-96-5p. NFAT5 silencing had the same results with miR-96-5p overexpression on VSMC proliferation, migration, and apoptosis, whereas miR-96-5p inhibitor reversed these effects.</AbstractText>
                <AbstractText Label="CONCLUSIONS" NlmCategory="CONCLUSIONS">Our findings concluded that miR-96-5p could regulate proliferation, migration, and apoptosis of VSMCs induced by Ang II via targeting NFAT5.</AbstractText>
                <CopyrightInformation>© 2020 S. Karger AG, Basel.</CopyrightInformation>
            </Abstract>
            <AuthorList CompleteYN="Y">
                <Author ValidYN="Y">
                    <LastName>Tian</LastName>
                    <ForeName>Long</ForeName>
                    <Initials>L</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Cai</LastName>
                    <ForeName>Dinghua</ForeName>
                    <Initials>D</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Zhuang</LastName>
                    <ForeName>Derong</ForeName>
                    <Initials>D</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Wang</LastName>
                    <ForeName>Wenyuan</ForeName>
                    <Initials>W</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Wang</LastName>
                    <ForeName>Xuan</ForeName>
                    <Initials>X</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Bian</LastName>
                    <ForeName>Xiaoli</ForeName>
                    <Initials>X</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Xu</LastName>
                    <ForeName>Rui</ForeName>
                    <Initials>R</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Nephrology, Jiangdu People's Hospital, Yangzhou, China.</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Wu</LastName>
                    <ForeName>Guanji</ForeName>
                    <Initials>G</Initials>
                    <AffiliationInfo>
                        <Affiliation>Department of Cardiology, Xi'an Central Hospital of Xi'an Jiaotong University, Xi'an, China, guanjiguanji22@163.com.</Affiliation>
                    </AffiliationInfo>
                </Author>
            </AuthorList>
            <Language>eng</Language>
            <clonelicationTypeList>
                <clonelicationType UI="D016428">Journal Article</clonelicationType>
            </clonelicationTypeList>
            <ArticleDate DateType="Electronic">
                <Year>2020</Year>
                <Month>02</Month>
                <Day>11</Day>
            </ArticleDate>

        <MedlineJournalInfo>
            <Country>Switzerland</Country>
            <MedlineTA>J Vasc Res</MedlineTA>
            <NlmUniqueID>9206092</NlmUniqueID>
            <ISSNLinking>1018-1172</ISSNLinking>
        </MedlineJournalInfo>
        <CitationSubset>IM</CitationSubset>
        <KeywordList Owner="NOTNLM">
            <Keyword MajorTopicYN="N">Migration</Keyword>
            <Keyword MajorTopicYN="N">NFAT5</Keyword>
            <Keyword MajorTopicYN="N">Proliferation</Keyword>
            <Keyword MajorTopicYN="N">Vascular smooth muscle cell</Keyword>
            <Keyword MajorTopicYN="N">miR-96-5p</Keyword>
        </KeywordList>
    </MedlineCitation>
    <CardData>
        <History>
            <CardcloneDate cloneStatus="received">
                <Year>2019</Year>
                <Month>09</Month>
                <Day>16</Day>
            </CardcloneDate>
            <CardcloneDate cloneStatus="accepted">
                <Year>2019</Year>
                <Month>12</Month>
                <Day>16</Day>
            </CardcloneDate>
            <CardcloneDate cloneStatus="entrez">
                <Year>2020</Year>
                <Month>2</Month>
                <Day>12</Day>
                <Hour>6</Hour>
                <Minute>0</Minute>
            </CardcloneDate>
            <CardcloneDate cloneStatus="Card">
                <Year>2020</Year>
                <Month>2</Month>
                <Day>12</Day>
                <Hour>6</Hour>
                <Minute>0</Minute>
            </CardcloneDate>
            <CardcloneDate cloneStatus="medline">
                <Year>2020</Year>
                <Month>2</Month>
                <Day>12</Day>
                <Hour>6</Hour>
                <Minute>0</Minute>
            </CardcloneDate>
        </History>
        <clonelicationStatus>aheadofprint</clonelicationStatus>
        <ArticleIdList>
            <ArticleId IdType="Card">32045906</ArticleId>
            <ArticleId IdType="pii">000505457</ArticleId>
            <ArticleId IdType="doi">10.1159/000505457</ArticleId>
        </ArticleIdList>
    </CardData>
</Caplock>

</CaplockSet>

I tried multiple ways to get away with this .py code but am facing lot of errors. I elaborated one of the method below

import xml.etree.ElementTree as ET

mytree = ET.parse('data.xml')
myroot = mytree.getroot()
for x in myroot.findall('Author'):
    lastname = x.find('LastName').text
    forename = x.find('ForeName').text
    affiliation = x.find('AffiliationInfo/Affiliation').text

    print(lastname,forename,affiliation)

Error

Traceback (most recent call last):
  File "c:/Users/jeeva/Desktop/data/program.py", line 3, in <module>
    mytree = ET.parse('data/data.xml')
  File "C:\Users\jeeva\AppData\Local\Programs\Python\Python38-32\lib\xml\etree\ElementTree.py", line 1202, in parse
    tree.parse(source, parser)
  File "C:\Users\jeeva\AppData\Local\Programs\Python\Python38-32\lib\xml\etree\ElementTree.py", line 595, in parse
    self._root = parser._parse_whole(source)
xml.etree.ElementTree.ParseError: syntax error: line 2, column 21

Body:
Maybe this should work

def find_rec(node):
    for item in node.iter():
        if item.tag == "Author":
            author_values = {}
            for i in item.iter():
                author_values[i.tag] = i.text
            yield author_values

auth = find_rec(ET.parse('./data.xml').getroot())
for x in auth:
    print(x["LastName"], x["ForeName"], x["Affiliation"])


来源: stackexchange

问:
Calculation loop in python new values
I would like to do the calculation loop using my function.

```<code>b=list(data.iloc[1])

def balance(rate, payment, os):
    interest_amount=os*rate/100/12
    principal_amount=payment-interest_amount
    next_balance=os+interest_amount-principal_amount
    return next_balance

c=balance(b[9], b[11], b[8])
d=balance(b[9], b[11], c)
e=balance(b[9], b[11], d)
</code>```

I would have to start with b[8] as the amount for calculation. After I got the next amount from the function balance, the next amount will be the beginning of the third calculation and so on until the next amount eqaul of less than 0. It should stop the loop.

I need to append calculated values since b[8] until the last (before getting 0 or less).

Any suggestion on this, thank you!

Edit: based on Zaraki Kenpachi

b[8] is amount of money given 17183
b[9] is rate of interest given 3.39
b[11] is payment per month given 5759

The output, which I am trying to do is:

```<code>[17183, 11,521, 5,826, 99]
</code>```

答:
Here you go:

```<code>def balance(rate, payment, os):
    interest_amount=os*rate/100/12
    principal_amount=payment-interest_amount
    next_balance=os+interest_amount-principal_amount
    return next_balance

next_balance = 17183 # = b[8]
results = []
results.append(next_balance)
while next_balance > 0:
    next_balance = balance(3.39, 5759, next_balance) # b[9], b[11]
    if next_balance > 0:
        results.append(next_balance)
</code>```

Output:

```<code>[17183, 11521.08395, 5827.1780743175, 101.10163043739522]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Calculation loop in python new values

Body:
I would like to do the calculation loop using my function.

b=list(data.iloc[1])

def balance(rate, payment, os):
    interest_amount=os*rate/100/12
    principal_amount=payment-interest_amount
    next_balance=os+interest_amount-principal_amount
    return next_balance

c=balance(b[9], b[11], b[8])
d=balance(b[9], b[11], c)
e=balance(b[9], b[11], d)

I would have to start with b[8] as the amount for calculation. After I got the next amount from the function balance, the next amount will be the beginning of the third calculation and so on until the next amount eqaul of less than 0. It should stop the loop.

I need to append calculated values since b[8] until the last (before getting 0 or less).

Any suggestion on this, thank you!

Edit: based on Zaraki Kenpachi

b[8] is amount of money given 17183
b[9] is rate of interest given 3.39
b[11] is payment per month given 5759

The output, which I am trying to do is:

[17183, 11,521, 5,826, 99]

Body:
Here you go:

def balance(rate, payment, os):
    interest_amount=os*rate/100/12
    principal_amount=payment-interest_amount
    next_balance=os+interest_amount-principal_amount
    return next_balance

next_balance = 17183 # = b[8]
results = []
results.append(next_balance)
while next_balance > 0:
    next_balance = balance(3.39, 5759, next_balance) # b[9], b[11]
    if next_balance > 0:
        results.append(next_balance)

Output:

[17183, 11521.08395, 5827.1780743175, 101.10163043739522]


问:
Scheme find far left node of a tree recursively
I am writing a function that finds the farthest left node in any tree. The function does not traverse the tree or give the farthest left node but just gives the left most child of the first node.

```<code>(define (far-left tree)
  (cond (null? (cadr tree))
        (car tree)
        (far-left (cdr tree))))
</code>```

sample input, which gives many nodes rather than the desired one:

```<code>(display (far-left '(1 (3 4 (6 7 (12 13))) 8 9 (10 11))))
</code>```

答:
What you call "the left most child of the first node" is (cadr tree).

There is one (cadr tree) in your function, and that suggests that the first condition is always true.

And that is what's happening.

cond's form is

```<code>(cond clause-1 clause-2 ...)
</code>```

Each clause in turn has the form (condition value).

That is,

```<code>(cond (condition-1 value-1)
      (condition-2 value-2)
      (condition-3 value-3)
      ...)
</code>```

If you match this to your function, you will see that

null? is condition-1 and (cadr tree) is value-1,

car is condition-2 and tree is value-2, and

far-left is condition-3 and (cdr tree) is value-3.

Since null? is not #f, the first clause is always selected.

The correct form is

```<code>(define (far-left tree)
    (cond
        ((null? (cadr tree)) (car tree))
        (else (far-left (cdr tree)))
</code>```

This code still does not work, though.

Fixing the bugs left as an exercise.

Body:
I am writing a function that finds the farthest left node in any tree. The function does not traverse the tree or give the farthest left node but just gives the left most child of the first node.

(define (far-left tree)
  (cond (null? (cadr tree))
        (car tree)
        (far-left (cdr tree))))

sample input, which gives many nodes rather than the desired one:

(display (far-left '(1 (3 4 (6 7 (12 13))) 8 9 (10 11))))

Body:
What you call "the left most child of the first node" is (cadr tree).

There is one (cadr tree) in your function, and that suggests that the first condition is always true.

And that is what's happening.

cond's form is

(cond clause-1 clause-2 ...)

Each clause in turn has the form (condition value).

That is,

(cond (condition-1 value-1)
      (condition-2 value-2)
      (condition-3 value-3)
      ...)

If you match this to your function, you will see that

null? is condition-1 and (cadr tree) is value-1,

car is condition-2 and tree is value-2, and

far-left is condition-3 and (cdr tree) is value-3.

Since null? is not #f, the first clause is always selected.

The correct form is

(define (far-left tree)
    (cond
        ((null? (cadr tree)) (car tree))
        (else (far-left (cdr tree)))

This code still does not work, though.

Fixing the bugs left as an exercise.


问:
Terminal Value from a to C using VBA Loop
I have an excel sheet name as Terminal Volumes In this sheet, there are three variables (Terminal LF (log Fisher Cost) and CT Cost) that are using as input. I am using the following code for working on these.

```<code>enter code here
Sub InitiateValues()
ReDim TrmPnts(11) '<<<<CHANGE HERE Total Point + SE -JJ
Set ShDat = Worksheets("Data")
Set ShDatPth = Worksheets("DataPath")
Set tvol = Worksheets("Terminal Volumes")
'ShDatPth.Range("B2:FB157").Value = 0
With TrmPnts(1)
    .Cpt = "T1"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(2, 1)
    .Col = ShDat.Cells(3, 1)
    .LFamt = tvol.Cells(2, 2)
    .CTamt = tvol.Cells(2, 3)
End With
With TrmPnts(3)
    .Cpt = "T2"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(6, 1)
    .Col = ShDat.Cells(7, 1)
    .LFamt = tvol.Cells(3, 2)
    .CTamt = tvol.Cells(3, 3)
End With
With TrmPnts(4)
    .Cpt = "T3"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(8, 1)
    .Col = ShDat.Cells(9, 1)
    .LFamt = tvol.Cells(4, 2)
    .CTamt = tvol.Cells(4, 3)
End With
With TrmPnts(5)
    .Cpt = "T4"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(10, 1)
    .Col = ShDat.Cells(11, 1)
    .LFamt = tvol.Cells(5, 2)
    .CTamt = tvol.Cells(5, 3)
End With
With TrmPnts(6)
    .Cpt = "T5"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(12, 1)
    .Col = ShDat.Cells(13, 1)
    .LFamt = tvol.Cells(6, 2)
    .CTamt = tvol.Cells(6, 3)
End With
With TrmPnts(7)
    .Cpt = "T6"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(14, 1)
    .Col = ShDat.Cells(15, 1)
    .LFamt = tvol.Cells(7, 2)
    .CTamt = tvol.Cells(7, 3)
End With
With TrmPnts(8)
    .Cpt = "T7"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(16, 1)
    .Col = ShDat.Cells(17, 1)
    .LFamt = tvol.Cells(8, 2)
    .CTamt = tvol.Cells(8, 3)
End With
With TrmPnts(9)
    .Cpt = "T8"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(18, 1)
    .Col = ShDat.Cells(19, 1)
    .LFamt = tvol.Cells(9, 2)
    .CTamt = tvol.Cells(9, 3)
End With
With TrmPnts(10)
    .Cpt = "T9"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(20, 1)
    .Col = ShDat.Cells(21, 1)
    .LFamt = tvol.Cells(10, 2)
    .CTamt = tvol.Cells(10, 3)
End With
With TrmPnts(11)
    .Cpt = "T10"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(22, 1)
    .Col = ShDat.Cells(23, 1)
    .LFamt = tvol.Cells(11, 2)
    .CTamt = tvol.Cells(11, 3)
End With '<<<<<<CHANGE HERE
With TrmPnts(2)
    .Cpt = "SE"
    .CptColr = "&H004400"
    .Row = ShDat.Cells(4, 1)
    .Col = ShDat.Cells(5, 1)
End With
ReDim Mtx(156, 157) ' Cell Size X,Y -JJ
For i = 1 To 156 ' Cell Size X,Y -JJ 1 To 226
    For j = 1 To 157 ' Cell Size X,Y -JJ
        Mtx(i, j) = ShDat.Cells(1 + i, 1 + j)
        ShDatPth.Cells(1 + i, 1 + j) = 0
    Next
Next
EdtMod = True
End Sub
</code>```

This code working fine to input the value to T10 (Only for 10 Rows). I want to use it for T1500 (1500 Rows) for the Column A to Column C- using loop.

The structure of the worksheet is as under.

答:
Just make a For...next loop and use the variable of the loop to calculate the correct fields like the following (I hope I interpreted the logic correctly, please check):

```<code>Sub InitiateValues()
ReDim trmpnts(11) '<<<<CHANGE HERE Total Point + SE -JJ
Set ShDat = Worksheets("Data")
Set ShDatPth = Worksheets("DataPath")
Set tvol = Worksheets("Terminal Volumes")
'ShDatPth.Range("B2:FB157").Value = 0
Dim I As Long
For I = 1 To UBound(trmpnts)
    With trmpnts(I)
        .Cpt = "T" & I
        .CptColr = "&H000088"
        .Row = ShDat.Cells(I * 2, 1)
        .Col = ShDat.Cells(I * 2 + 1, 1)
        .LFamt = tvol.Cells(I, 2)
        .CTamt = tvol.Cells(I, 3)
    End With
Next I
....
End Sub
</code>```

That should do the trick...

Body:
I have an excel sheet name as Terminal Volumes In this sheet, there are three variables (Terminal LF (log Fisher Cost) and CT Cost) that are using as input. I am using the following code for working on these.

enter code here
Sub InitiateValues()
ReDim TrmPnts(11) '<<<<CHANGE HERE Total Point + SE -JJ
Set ShDat = Worksheets("Data")
Set ShDatPth = Worksheets("DataPath")
Set tvol = Worksheets("Terminal Volumes")
'ShDatPth.Range("B2:FB157").Value = 0
With TrmPnts(1)
    .Cpt = "T1"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(2, 1)
    .Col = ShDat.Cells(3, 1)
    .LFamt = tvol.Cells(2, 2)
    .CTamt = tvol.Cells(2, 3)
End With
With TrmPnts(3)
    .Cpt = "T2"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(6, 1)
    .Col = ShDat.Cells(7, 1)
    .LFamt = tvol.Cells(3, 2)
    .CTamt = tvol.Cells(3, 3)
End With
With TrmPnts(4)
    .Cpt = "T3"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(8, 1)
    .Col = ShDat.Cells(9, 1)
    .LFamt = tvol.Cells(4, 2)
    .CTamt = tvol.Cells(4, 3)
End With
With TrmPnts(5)
    .Cpt = "T4"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(10, 1)
    .Col = ShDat.Cells(11, 1)
    .LFamt = tvol.Cells(5, 2)
    .CTamt = tvol.Cells(5, 3)
End With
With TrmPnts(6)
    .Cpt = "T5"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(12, 1)
    .Col = ShDat.Cells(13, 1)
    .LFamt = tvol.Cells(6, 2)
    .CTamt = tvol.Cells(6, 3)
End With
With TrmPnts(7)
    .Cpt = "T6"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(14, 1)
    .Col = ShDat.Cells(15, 1)
    .LFamt = tvol.Cells(7, 2)
    .CTamt = tvol.Cells(7, 3)
End With
With TrmPnts(8)
    .Cpt = "T7"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(16, 1)
    .Col = ShDat.Cells(17, 1)
    .LFamt = tvol.Cells(8, 2)
    .CTamt = tvol.Cells(8, 3)
End With
With TrmPnts(9)
    .Cpt = "T8"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(18, 1)
    .Col = ShDat.Cells(19, 1)
    .LFamt = tvol.Cells(9, 2)
    .CTamt = tvol.Cells(9, 3)
End With
With TrmPnts(10)
    .Cpt = "T9"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(20, 1)
    .Col = ShDat.Cells(21, 1)
    .LFamt = tvol.Cells(10, 2)
    .CTamt = tvol.Cells(10, 3)
End With
With TrmPnts(11)
    .Cpt = "T10"
    .CptColr = "&H000088"
    .Row = ShDat.Cells(22, 1)
    .Col = ShDat.Cells(23, 1)
    .LFamt = tvol.Cells(11, 2)
    .CTamt = tvol.Cells(11, 3)
End With '<<<<<<CHANGE HERE
With TrmPnts(2)
    .Cpt = "SE"
    .CptColr = "&H004400"
    .Row = ShDat.Cells(4, 1)
    .Col = ShDat.Cells(5, 1)
End With
ReDim Mtx(156, 157) ' Cell Size X,Y -JJ
For i = 1 To 156 ' Cell Size X,Y -JJ 1 To 226
    For j = 1 To 157 ' Cell Size X,Y -JJ
        Mtx(i, j) = ShDat.Cells(1 + i, 1 + j)
        ShDatPth.Cells(1 + i, 1 + j) = 0
    Next
Next
EdtMod = True
End Sub

This code working fine to input the value to T10 (Only for 10 Rows). I want to use it for T1500 (1500 Rows) for the Column A to Column C- using loop.

The structure of the worksheet is as under.

Body:
Just make a For...next loop and use the variable of the loop to calculate the correct fields like the following (I hope I interpreted the logic correctly, please check):

Sub InitiateValues()
ReDim trmpnts(11) '<<<<CHANGE HERE Total Point + SE -JJ
Set ShDat = Worksheets("Data")
Set ShDatPth = Worksheets("DataPath")
Set tvol = Worksheets("Terminal Volumes")
'ShDatPth.Range("B2:FB157").Value = 0
Dim I As Long
For I = 1 To UBound(trmpnts)
    With trmpnts(I)
        .Cpt = "T" & I
        .CptColr = "&H000088"
        .Row = ShDat.Cells(I * 2, 1)
        .Col = ShDat.Cells(I * 2 + 1, 1)
        .LFamt = tvol.Cells(I, 2)
        .CTamt = tvol.Cells(I, 3)
    End With
Next I
....
End Sub

That should do the trick...


问:
Can't print elements in a linked list after merging two arrays together into one list
I am working on an assignment for DS and Algo I am given two sorted integer lists or arrays then I have to merge them into one list. I decided to use two queues for each array by putting each element in the queue then do some comparisons and put them into a singly linked list. Now the problem I have faced is that it is only printing the first element over and over again in the first array. My goal is to put remove the elements in the queue and put them in a linked list from least to greatest.
Also the count in the while loop is used to stop the loop once it equals the length of both arrays - 1.

MergeQueue.java

```<code>    int[] A = {1, 3, 5, 7, 9}; // our first array A
    int[] B = {2, 3, 6, 8, 10}; // our second array B
    int length = A.length + B.length - 1; // get the length of both A and B
    //System.out.println(length);
    int count = 0; // this is a counter used to check that once count is equal to the length(A+B) then we break the loop
    int frontA, dequeueA;
    int frontB, dequeueB;

    // we can use a singly linked list to store elements of A and B
    SingleLinkedList S = new SingleLinkedList();
    QueueLinkList queueA = new QueueLinkList(); // our queue for A type integer
    QueueLinkList queueB = new QueueLinkList(); // our queue for B type integer

    // Add elements from A to the queue
    for(int i = 0; i < A.length; i++) {
        // so add element from A to the queue
        queueA.enqueue(A[i]);
    }

    // Add elements from B to the queue
    for(int i = 0; i < B.length; i++) {
        // so add element from B to the queue
        queueB.enqueue(B[i]);
    }
    // now begins the conditions
    while(count != length) {
        // only return the element in the front not remove it
        frontA = queueA.front();
        frontB = queueB.front();

        if(frontA < frontB) {
            dequeueA = queueA.dequeue(); // remove the element and add it to the linked list
            // add dequeueA to list S
            S.add(dequeueA); // add the element to the singly linked list
            count++; // increment the counter
        }
        else if(frontB < frontA) {
            dequeueB = queueB.dequeue();
            // add dequeueB to list S
            S.add(dequeueB); // add the element to the singly linked list
            count++; // increment the counter
        }
        // if the elements are the same then remove from queue and add anyone.
        else if(frontA == frontB || frontB == frontA) {
            dequeueA = queueA.dequeue();
            dequeueB = queueB.dequeue();
            // add either dequeueA or B
            S.add(dequeueA); // add the element to the singly linked list
            count++; // increment the counter
        }
        // if queue A is empty and queue B is not then add remaining elements from B to S.
        else if(queueA.isEmpty() && !queueB.isEmpty()){
            // add remaining elements from B to the list
            dequeueA = queueA.dequeue();
            S.add(dequeueA);
            count++; // increment the counter
        }
        // if queue B is empty and queue A is not then add remaining elements from B to S.
        else if(queueB.isEmpty() && !queueA.isEmpty()) {
            // add remaining elements from B to the list
            dequeueB = queueB.dequeue();
            S.add(dequeueB);
            count++;
        }
    }
    System.out.println("Our set S:");
    S.print(); // call the print method which displays every element in the singly linked list
</code>```

答:
In this part of code

```<code>else if(frontA == frontB || frontB == frontA) {
            dequeueA = queueA.dequeue();
            dequeueB = queueB.dequeue();
            // add either dequeueA or B
            S.add(dequeueA); // add the element to the singly linked list
            count++; // increment the counter
}
</code>```

You need to increment count by 2 times since even though you are adding in link list once you are removing same element from both the queue and hence two elements are getting removed

Body:
I am working on an assignment for DS and Algo I am given two sorted integer lists or arrays then I have to merge them into one list. I decided to use two queues for each array by putting each element in the queue then do some comparisons and put them into a singly linked list. Now the problem I have faced is that it is only printing the first element over and over again in the first array. My goal is to put remove the elements in the queue and put them in a linked list from least to greatest.
Also the count in the while loop is used to stop the loop once it equals the length of both arrays - 1.

MergeQueue.java

    int[] A = {1, 3, 5, 7, 9}; // our first array A
    int[] B = {2, 3, 6, 8, 10}; // our second array B
    int length = A.length + B.length - 1; // get the length of both A and B
    //System.out.println(length);
    int count = 0; // this is a counter used to check that once count is equal to the length(A+B) then we break the loop
    int frontA, dequeueA;
    int frontB, dequeueB;

    // we can use a singly linked list to store elements of A and B
    SingleLinkedList S = new SingleLinkedList();
    QueueLinkList queueA = new QueueLinkList(); // our queue for A type integer
    QueueLinkList queueB = new QueueLinkList(); // our queue for B type integer

    // Add elements from A to the queue
    for(int i = 0; i < A.length; i++) {
        // so add element from A to the queue
        queueA.enqueue(A[i]);
    }

    // Add elements from B to the queue
    for(int i = 0; i < B.length; i++) {
        // so add element from B to the queue
        queueB.enqueue(B[i]);
    }
    // now begins the conditions
    while(count != length) {
        // only return the element in the front not remove it
        frontA = queueA.front();
        frontB = queueB.front();

        if(frontA < frontB) {
            dequeueA = queueA.dequeue(); // remove the element and add it to the linked list
            // add dequeueA to list S
            S.add(dequeueA); // add the element to the singly linked list
            count++; // increment the counter
        }
        else if(frontB < frontA) {
            dequeueB = queueB.dequeue();
            // add dequeueB to list S
            S.add(dequeueB); // add the element to the singly linked list
            count++; // increment the counter
        }
        // if the elements are the same then remove from queue and add anyone.
        else if(frontA == frontB || frontB == frontA) {
            dequeueA = queueA.dequeue();
            dequeueB = queueB.dequeue();
            // add either dequeueA or B
            S.add(dequeueA); // add the element to the singly linked list
            count++; // increment the counter
        }
        // if queue A is empty and queue B is not then add remaining elements from B to S.
        else if(queueA.isEmpty() && !queueB.isEmpty()){
            // add remaining elements from B to the list
            dequeueA = queueA.dequeue();
            S.add(dequeueA);
            count++; // increment the counter
        }
        // if queue B is empty and queue A is not then add remaining elements from B to S.
        else if(queueB.isEmpty() && !queueA.isEmpty()) {
            // add remaining elements from B to the list
            dequeueB = queueB.dequeue();
            S.add(dequeueB);
            count++;
        }
    }
    System.out.println("Our set S:");
    S.print(); // call the print method which displays every element in the singly linked list

Body:
In this part of code

else if(frontA == frontB || frontB == frontA) {
            dequeueA = queueA.dequeue();
            dequeueB = queueB.dequeue();
            // add either dequeueA or B
            S.add(dequeueA); // add the element to the singly linked list
            count++; // increment the counter
}

You need to increment count by 2 times since even though you are adding in link list once you are removing same element from both the queue and hence two elements are getting removed


问:
How does Spring @DeclareParents annotation work? How does it implement the methods from the new interface?
While reading through the Spring AOP documentation I came across the @DeclareParents annotation. I was able to construct a working example using it:

public interface Openable {

  void open();
  void close();
  boolean isOpen();

}
```

<pre class="lang-java prettyprint-override"><code>public interface Paintable {

  void paint(Color color);
  Color getColor();

}
</code>```

@Component
public class Door implements Openable {

  private boolean isOpen = false;
  private Color color;

  @Override
  public void open() {
    isOpen = true;
  }

  @Override
  public void close() {
    isOpen = false;
  }

  @Override
  public boolean isOpen() {
    return isOpen;
  }
}
```

<pre class="lang-java prettyprint-override"><code>@Component
public class Fence implements Paintable {

  private Color color;

  @Override
  public void paint(Color color) {
    this.color = color;
  }

  @Override
  public Color getColor() {
    return color;
  }
}
</code>```

@Component
@Aspect
public class IntroductionAspect {

  @DeclareParents(value="aopTraining.IntrocuctionsTest.Openable+", defaultImpl=Fence.class)
  public static Paintable openable;
}
```

<pre class="lang-java prettyprint-override"><code>@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan
public class IntroductionsAppConfig {

}
</code>```

public class Main {

  public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IntroductionsAppConfig.class);

    Fence fence = context.getBean(Fence.class);
    System.out.println("Color of the fence: " + fence.getColor());

    Paintable doorAsPaintable = (Paintable) context.getBean(Door.class);
    Openable doorAsOpenable = (Openable) doorAsPaintable;
    System.out.println("Door is open: " + doorAsOpenable.isOpen());
    doorAsOpenable.open();
    System.out.println("Door is open: " + doorAsOpenable.isOpen());
    System.out.println("Door's current color: " + doorAsPaintable.getColor());
    doorAsPaintable.paint(Color.GREEN);
    System.out.println("Door's current color: " + doorAsPaintable.getColor());

    System.out.println("Color of the fence: " + fence.getColor());
  }
}
```

<p>The output:</p>

<pre class="lang-none prettyprint-override"><code>Color of the fence: null
Door is open: false
Door is open: true
Door's current color: null
Door's current color: java.awt.Color[r=0,g=255,b=0]
Color of the fence: null
</code>```

So I understand the principle: I am adding a new type (Paintable) to the Openable interface. And thus everything that is openable (namely a Door) becomes paintable at runtime. What I am wondering about is: How does Spring do it internally? When it creates the proxy for the Door class, how does it implement the new methods provided by the Paintable interface? Based on what I have seen so far, my suggestion would be the following: It uses the Paintable-implementation which I provided in the defaultImpl attribute, which is Fence. It seems to instantiate a new Fence, store it (maybe) into some field onto the Door-proxy and then delegate all calls to Paintable-methods on the Door to this internal Fence object. I would like to know, if this suggestion is correct? Unfortunately, there is no detailed description on it in the documentation.

答:
If you add some more log output to your main class...

// (...)
Paintable doorAsPaintable = (Paintable) context.getBean(Door.class);
Openable doorAsOpenable = (Openable) doorAsPaintable;

Class<?> dynamicProxyClass = doorAsPaintable.getClass();
System.out.println("Dynamic proxy: " + dynamicProxyClass);
System.out.println("Dynamic proxy parent: " + dynamicProxyClass.getSuperclass());
System.out.println("Dynamic proxy interfaces: " + Arrays.asList(dynamicProxyClass.getInterfaces()));
// (...)
```

<p>... then you will see this in your log output (sorry, I used other package names than you in my sample app):</p>

<pre class="lang-none prettyprint-override"><code>Dynamic proxy: class spring.aop.q60221207.Door$$EnhancerBySpringCGLIB$$a29f3532
Dynamic proxy parent: class spring.aop.q60221207.Door
Dynamic proxy interfaces: [interface spring.aop.q60221207.Paintable, interface org.springframework.aop.SpringProxy, interface org.springframework.aop.framework.Advised, interface org.springframework.cglib.proxy.Factory]
</code>```

So you see the dynamic CGLIB proxy extends Door, no surprise here. Then Spring makes the proxy implement a few AOP-related interfaces and also Paintable. That's it, quite simple.

In a debugger you can also see a few fields like CGLIB$CALLBACK_0 to CGLIB$CALLBACK_4. In my local environment #4 is the interesting one. It is a CglibAopProxy$AdvisedDispatcher instance and has a field advised which is a ProxyFactory instance with this value (adding line breaks for readability):

org.springframework.aop.framework.ProxyFactory:
  1 interfaces [spring.aop.q60221207.Paintable];
  1 advisors [org.springframework.aop.aspectj.DeclareParentsAdvisor@797cf65c];
  targetSource [SingletonTargetSource for target object [spring.aop.q60221207.Door@29526c05]];
  proxyTargetClass=true;
  optimize=false;
  opaque=false;
  exposeProxy=false;
  frozen=false
```

<p><strong>Postscript:</strong> Now you know more but actually you really do not need to know because it is about Spring internals. You do not find it in the Spring manual because the internal implementation could theoretically change at any time. And besides, if you switch from Spring AOP to full AspectJ as described in the Spring manual, then all this information is null and void because AspectJ does not use proxies but directly transforms the Java bytecode. Then my answer would look much different.</p>

<hr>

<p><strong>Update:</strong> You asked:</p>

<blockquote>
  <p>But the question was actually, how Spring knows, what the implementation of the new methods should be. In other words, now that Door implements Paintable, how does Spring determine the implementation of Paintable's methods on the Door class?</p>
</blockquote>

<p>It makes the proxy call the corresponding methods of <code>Fence</code> because you specified it as <code>defaultImpl</code> in your aspect. For that purpose Spring creates an internal <strong><code>Fence</code> delegate</strong> instance on which to call the method via reflection. You can see that if you debug into a method call like</p>

<pre class="lang-java prettyprint-override"><code>doorAsPaintable.paint(Color.GREEN);
</code>```

until you reach method

package org.springframework.aop.support;

class DelegatePerTargetObjectIntroductionInterceptor ...

  public Object invoke(MethodInvocation mi)
```

For further questions please read the Spring source code.

Body:
While reading through the Spring AOP documentation I came across the @DeclareParents annotation. I was able to construct a working example using it:

public interface Openable {

  void open();
  void close();
  boolean isOpen();

}

public interface Paintable {

  void paint(Color color);
  Color getColor();

}

@Component
public class Door implements Openable {

  private boolean isOpen = false;
  private Color color;

  @Override
  public void open() {
    isOpen = true;
  }

  @Override
  public void close() {
    isOpen = false;
  }

  @Override
  public boolean isOpen() {
    return isOpen;
  }
}

@Component
public class Fence implements Paintable {

  private Color color;

  @Override
  public void paint(Color color) {
    this.color = color;
  }

  @Override
  public Color getColor() {
    return color;
  }
}

@Component
@Aspect
public class IntroductionAspect {

  @DeclareParents(value="aopTraining.IntrocuctionsTest.Openable+", defaultImpl=Fence.class)
  public static Paintable openable;
}

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan
public class IntroductionsAppConfig {

}

public class Main {

  public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IntroductionsAppConfig.class);

    Fence fence = context.getBean(Fence.class);
    System.out.println("Color of the fence: " + fence.getColor());

    Paintable doorAsPaintable = (Paintable) context.getBean(Door.class);
    Openable doorAsOpenable = (Openable) doorAsPaintable;
    System.out.println("Door is open: " + doorAsOpenable.isOpen());
    doorAsOpenable.open();
    System.out.println("Door is open: " + doorAsOpenable.isOpen());
    System.out.println("Door's current color: " + doorAsPaintable.getColor());
    doorAsPaintable.paint(Color.GREEN);
    System.out.println("Door's current color: " + doorAsPaintable.getColor());

    System.out.println("Color of the fence: " + fence.getColor());
  }
}

The output:

Color of the fence: null
Door is open: false
Door is open: true
Door's current color: null
Door's current color: java.awt.Color[r=0,g=255,b=0]
Color of the fence: null

So I understand the principle: I am adding a new type (Paintable) to the Openable interface. And thus everything that is openable (namely a Door) becomes paintable at runtime. What I am wondering about is: How does Spring do it internally? When it creates the proxy for the Door class, how does it implement the new methods provided by the Paintable interface? Based on what I have seen so far, my suggestion would be the following: It uses the Paintable-implementation which I provided in the defaultImpl attribute, which is Fence. It seems to instantiate a new Fence, store it (maybe) into some field onto the Door-proxy and then delegate all calls to Paintable-methods on the Door to this internal Fence object. I would like to know, if this suggestion is correct? Unfortunately, there is no detailed description on it in the documentation.

Body:
If you add some more log output to your main class...

// (...)
Paintable doorAsPaintable = (Paintable) context.getBean(Door.class);
Openable doorAsOpenable = (Openable) doorAsPaintable;

Class<?> dynamicProxyClass = doorAsPaintable.getClass();
System.out.println("Dynamic proxy: " + dynamicProxyClass);
System.out.println("Dynamic proxy parent: " + dynamicProxyClass.getSuperclass());
System.out.println("Dynamic proxy interfaces: " + Arrays.asList(dynamicProxyClass.getInterfaces()));
// (...)

... then you will see this in your log output (sorry, I used other package names than you in my sample app):

Dynamic proxy: class spring.aop.q60221207.Door$$EnhancerBySpringCGLIB$$a29f3532
Dynamic proxy parent: class spring.aop.q60221207.Door
Dynamic proxy interfaces: [interface spring.aop.q60221207.Paintable, interface org.springframework.aop.SpringProxy, interface org.springframework.aop.framework.Advised, interface org.springframework.cglib.proxy.Factory]

So you see the dynamic CGLIB proxy extends Door, no surprise here. Then Spring makes the proxy implement a few AOP-related interfaces and also Paintable. That's it, quite simple.

In a debugger you can also see a few fields like CGLIB$CALLBACK_0 to CGLIB$CALLBACK_4. In my local environment #4 is the interesting one. It is a CglibAopProxy$AdvisedDispatcher instance and has a field advised which is a ProxyFactory instance with this value (adding line breaks for readability):

org.springframework.aop.framework.ProxyFactory:
  1 interfaces [spring.aop.q60221207.Paintable];
  1 advisors [org.springframework.aop.aspectj.DeclareParentsAdvisor@797cf65c];
  targetSource [SingletonTargetSource for target object [spring.aop.q60221207.Door@29526c05]];
  proxyTargetClass=true;
  optimize=false;
  opaque=false;
  exposeProxy=false;
  frozen=false

Postscript: Now you know more but actually you really do not need to know because it is about Spring internals. You do not find it in the Spring manual because the internal implementation could theoretically change at any time. And besides, if you switch from Spring AOP to full AspectJ as described in the Spring manual, then all this information is null and void because AspectJ does not use proxies but directly transforms the Java bytecode. Then my answer would look much different.

Update: You asked:

But the question was actually, how Spring knows, what the implementation of the new methods should be. In other words, now that Door implements Paintable, how does Spring determine the implementation of Paintable's methods on the Door class?

It makes the proxy call the corresponding methods of Fence because you specified it as defaultImpl in your aspect. For that purpose Spring creates an internal Fence delegate instance on which to call the method via reflection. You can see that if you debug into a method call like

doorAsPaintable.paint(Color.GREEN);

until you reach method

package org.springframework.aop.support;

class DelegatePerTargetObjectIntroductionInterceptor ...

  public Object invoke(MethodInvocation mi)

For further questions please read the Spring source code.


问:
Get current file name after creating executable
I can get the current directory and the name of the current .go file but if i build a .exe from the file with go build then i still get the .go name.

.../Project/Test/testfile.go

After building testfile.go with go build i have these:

1) .../Project/Test/testfile.go

2) .../Project/Test/main.exe

When i execute main.exe i get testfile But i want to get the main name after executing main.exe

```<code>package main

import (
    "errors"
    "fmt"
    "path/filepath"
    "runtime"
    "strings"
)

func GetFileName() string {
    _, fpath, _, ok := runtime.Caller(0)
    if !ok {
        err := errors.New("failed to get filename")
        panic(err)
    }
    filename := filepath.Base(fpath)
    filename = strings.Replace(filename, ".go", "", 1)
    return filename
}

func main() {
    fmt.Print(GetFileName())
}
</code>```

答: The os package provides os.Args[0] to obtain the executable name, or if you want the whole path you could use os.Executable, as @Peter has suggested

Body:
I can get the current directory and the name of the current .go file but if i build a .exe from the file with go build then i still get the .go name.

.../Project/Test/testfile.go

After building testfile.go with go build i have these:

1) .../Project/Test/testfile.go

2) .../Project/Test/main.exe

When i execute main.exe i get testfile But i want to get the main name after executing main.exe

package main

import (
    "errors"
    "fmt"
    "path/filepath"
    "runtime"
    "strings"
)

func GetFileName() string {
    _, fpath, _, ok := runtime.Caller(0)
    if !ok {
        err := errors.New("failed to get filename")
        panic(err)
    }
    filename := filepath.Base(fpath)
    filename = strings.Replace(filename, ".go", "", 1)
    return filename
}

func main() {
    fmt.Print(GetFileName())
}


问:
How to set the first select option to always be blank
I am using angularjs in a project and in which I am using ng-options for generating <select>.

Initially, when the pages reload and no option element is selected, the HTML generated like below:

```<code><select size="3" ng-model="item" ng-options="s.name for s in itemlist">
<option value="?" selected="selected"></option>
<option value="0">Item 1</option>
<option value="1">Item 2</option>
<option value="2">Item 3</option>
</select>
</code>```

But when I select an element (ex. Item 2) the first blank select is gone. I know its happening as ng-model is being set by select value. But I want first select always blank so that user can reset the filter.

答:
I had same problem and after a lot of googling,I understood the main issue was related to my angular version, if you use Angular 1.6.x, just use the ng-value directive and it will work as expected.

also I set an initial value in my controller, like this :

```<code>$scope.item = 0;
</code>```

Body:
I am using angularjs in a project and in which I am using ng-options for generating <select>.

Initially, when the pages reload and no option element is selected, the HTML generated like below:

<select size="3" ng-model="item" ng-options="s.name for s in itemlist">
<option value="?" selected="selected"></option>
<option value="0">Item 1</option>
<option value="1">Item 2</option>
<option value="2">Item 3</option>
</select>

But when I select an element (ex. Item 2) the first blank select is gone. I know its happening as ng-model is being set by select value. But I want first select always blank so that user can reset the filter.

Body:
I had same problem and after a lot of googling,I understood the main issue was related to my angular version, if you use Angular 1.6.x, just use the ng-value directive and it will work as expected.

also I set an initial value in my controller, like this :

$scope.item = 0;


问:
How to give hyperlink action in UIAlertController?
I'm unable to click hyperlink in UIAlertController. I want to open the external browser on hyperlink click.

```<code>-(void)viewDidAppear:(BOOL) animated {
    NSString *htmlString = @"Welcom to AlertView for more information <A href=\"https://www.google.com\"> Click Here </A>";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                     message:htmlString
                                                              preferredStyle:UIAlertControllerStyleAlert];
    NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
               options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                         NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
    documentAttributes:nil error:nil];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        // OK button tappped.
        [self dismissViewControllerAnimated:YES completion:^{ }];
    }];
    [alert setValue:attributedStr forKey: @"attributedMessage"];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:true completion:nil];
}
</code>```

on click on "Click Here" then should open the external browser. Is possible to get hyperlink click action in UIAlertView?

答:
I think it would be better to add a default action button, maybe with the title "More info", that will take care of opening the url, but you can take a look at this same question.</p>

```<code>    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"Welcome to AlertView" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *linkAction = [UIAlertAction actionWithTitle:@"More info" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString: yourUrl]];
    }];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        // OK button tappped.
        [self dismissViewControllerAnimated:YES completion:^{ }];
    }];
    [alert addAction:linkAction];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:true completion:nil];
</code>```

Body:
I'm unable to click hyperlink in UIAlertController. I want to open the external browser on hyperlink click.

-(void)viewDidAppear:(BOOL) animated {
    NSString *htmlString = @"Welcom to AlertView for more information  Click Here ";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                     message:htmlString
                                                              preferredStyle:UIAlertControllerStyleAlert];
    NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
               options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                         NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
    documentAttributes:nil error:nil];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        // OK button tappped.
        [self dismissViewControllerAnimated:YES completion:^{ }];
    }];
    [alert setValue:attributedStr forKey: @"attributedMessage"];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:true completion:nil];
}

on click on "Click Here" then should open the external browser. Is possible to get hyperlink click action in UIAlertView?

Body:
I think it would be better to add a default action button, maybe with the title "More info", that will take care of opening the url, but you can take a look at this same question.

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"Welcome to AlertView" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *linkAction = [UIAlertAction actionWithTitle:@"More info" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString: yourUrl]];
    }];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        // OK button tappped.
        [self dismissViewControllerAnimated:YES completion:^{ }];
    }];
    [alert addAction:linkAction];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:true completion:nil];


问:
How to redirect a user after a create method laravel6?
I made a register form in the front_page and I want to redirect the user after a successfull registration to /home page, but instead I get an array and the user is not redirected.

```<code>  {"email":"example@example.com","paypal_email":"example@example.com","updated_at":"2020-02-
  14
  08:16:32","created_at":"2020-02-14 08:16:32","id":1}
</code>```

My route:

```<code> Route::post('/', 'Auth\RegisterController@create')->name('auth.register');
</code>```

Register controller:

```<code>      public function create(Request $request)
{
    return User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);

}

  public $redirectTo = '/home';
</code>```

答:
Change this:

```<code>public function create(Request $request)
{
    return User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);

}
</code>```

to this:

```<code>public function create(Request $request) {
    $create = User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);
    if($create){
       return redirect('/home');
    }

    //Return errors here
}
</code>```

To learn more about laravel redirects, click here

Body:
I made a register form in the front_page and I want to redirect the user after a successfull registration to /home page, but instead I get an array and the user is not redirected.

  {"email":"example@example.com","paypal_email":"example@example.com","updated_at":"2020-02-
  14
  08:16:32","created_at":"2020-02-14 08:16:32","id":1}

My route:

 Route::post('/', 'Auth\RegisterController@create')->name('auth.register');

Register controller:

      public function create(Request $request)
{
    return User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);

}

  public $redirectTo = '/home';

Body:
Change this:

public function create(Request $request)
{
    return User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);

}

to this:

public function create(Request $request) {
    $create = User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);
    if($create){
       return redirect('/home');
    }

    //Return errors here
}

To learn more about laravel redirects, click here


问:
Unable to activate Windows Store app - The app didn´t start
I am trying to create a UWP app (for Desktop) in Visual Studio 2017 on Windows 10. Everything works fine, I added some UI elements and I can start the app without problems.

I want to incorporate OpenCV (3.4.9) into my app, which I built using CMake and Visual Studio 2017 (following the steps from https://medium.com/@rabbi.cse.sust.bd/how-to-build-opencv-for-universal-windows-platform-uwp-1a642ec09955)

I have checked the library path for each config (I built one for each x64/Debug, x64/Release, x86/Debug, x86/Release).

The problem starts when I start using OpenCV, eg by including "opencv2/opencv.hpp".

I can still build without errors, but when I try to run the app (Run without Debugging in VS), I get the error:

Unable to activate Windows Store app. The activation request failed with the error: The app didnt start

When running the .exe directly, nothing happens (I had to add some DLLs to the folder first).

I have tried the suggestions from the similar questions here on SO, but without luck.

Rebuilding or changing configuration doesn´t help.

I can start the app when including "opencv2/core.hpp", and do

```<code>cv::Mat img;
</code>```

But if I write

```<code>cv::Mat img(200, 200, CV_8UC3);
</code>```

The same error occurs. Writing

```<code>cv::Point pt(10, 10);
</code>```

on the other hand works fine.

I am running out of ideas for things to try..

答:
Ok, so I found the problem. Actually similar to what others with the same issue found:

Visual Studio was unable to find the DLL files for OpenCV. I did suspect that, so I added the bin folder to my path, and copied the DLL files into the project root as well as "ProjectRoot/x64/Release/ProjectName".

But apparently, the DLL files need to be in

"ProjectRoot/x64/Release/ProjectName/AppX"

for a x64 Release build.

If someone has any idea on why it can´t find them through the PATH or in the project root, please let me know.
I guess the reason is related to the fact that the binaries are dependent on the configuration?

Anyway, I can load an image through OpenCV in my UWP app now, so I´m happy.

Hope this saves someone a headache.

Body:
I am trying to create a UWP app (for Desktop) in Visual Studio 2017 on Windows 10. Everything works fine, I added some UI elements and I can start the app without problems.

I want to incorporate OpenCV (3.4.9) into my app, which I built using CMake and Visual Studio 2017 (following the steps from https://medium.com/@rabbi.cse.sust.bd/how-to-build-opencv-for-universal-windows-platform-uwp-1a642ec09955)

I have checked the library path for each config (I built one for each x64/Debug, x64/Release, x86/Debug, x86/Release).

The problem starts when I start using OpenCV, eg by including "opencv2/opencv.hpp".

I can still build without errors, but when I try to run the app (Run without Debugging in VS), I get the error:

Unable to activate Windows Store app. The activation request failed with the error: The app didnt start

When running the .exe directly, nothing happens (I had to add some DLLs to the folder first).

I have tried the suggestions from the similar questions here on SO, but without luck.

Rebuilding or changing configuration doesn´t help.

I can start the app when including "opencv2/core.hpp", and do

cv::Mat img;

But if I write

cv::Mat img(200, 200, CV_8UC3);

The same error occurs. Writing

cv::Point pt(10, 10);

on the other hand works fine.

I am running out of ideas for things to try..


问:
Caused by: java.lang.NoClassDefFoundError: Ljavax/transaction/TransactionManager;
I read many posts about the error javax/transaction/TransactionManager, but none of those solutions fix my problem.

First thing to say is that I get that error when I deploy my web-application (made with Spring MVC and Hibernate) on the server. On my computer, with Eclipse and Tomcat 7 everything works.

Second thing to say is that on that server I have another web-application that's running under tomcat /root folder (this is a simple java application, that DOESN'T use neither Spring mvc nor Hibernate). The new application that i'm trying to deploy is running under another folder called /prova.

These are all the libraries of my application

Plus, according to what I read on some posts, I added to my lib folder:

1) jta-3.1.2.2.jar

2) hibernate3.3.1-jta-1.1.jar

3) javax.transaction.jar

In my xml file I have this bean that defines the transaction manager

```<code><bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
     <property name="sessionFactory" ref="sessionFactory" />
</bean>
</code>```

Something strange is that in the server log the exact error is

```<code>Caused by: java.lang.NoClassDefFoundError: Ljavax/transaction/TransactionManager;
</code>```

There's a L before javax/transaction/TransactionManager

Any idea?

Thank you

答:
you must add this dependency It is work</p>

```<code>    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
     <version>5.4.2.Final</version>
    </dependency>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I read many posts about the error javax/transaction/TransactionManager, but none of those solutions fix my problem.

First thing to say is that I get that error when I deploy my web-application (made with Spring MVC and Hibernate) on the server. On my computer, with Eclipse and Tomcat 7 everything works.

Second thing to say is that on that server I have another web-application that's running under tomcat /root folder (this is a simple java application, that DOESN'T use neither Spring mvc nor Hibernate). The new application that i'm trying to deploy is running under another folder called /prova.

These are all the libraries of my application

Plus, according to what I read on some posts, I added to my lib folder:

1) jta-3.1.2.2.jar

2) hibernate3.3.1-jta-1.1.jar

3) javax.transaction.jar

In my xml file I have this bean that defines the transaction manager

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
     <property name="sessionFactory" ref="sessionFactory" />
</bean>

Something strange is that in the server log the exact error is

Caused by: java.lang.NoClassDefFoundError: Ljavax/transaction/TransactionManager;

There's a L before javax/transaction/TransactionManager

Any idea?

Thank you

Body:
you must add this dependency It is work

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
     <version>5.4.2.Final</version>
    </dependency>


问:
How do I change the v-progress-loader-circular total time out?
I tried changing the value to 30 seconds and the resetting the time after 30 seconds but the circle length reminds 100. I want it to count up to 30 and 30 to be the maximum count. I have managed to reset it after 30 seconds but the total count remains the same

<v-progress-circular :rotate="-90" :size="100" :width="15" :value="loaderValue" class="mb-2" :color="yellow">

答:
Change the :value property to a number that you multiply with loaderValue to get 100. For my case. I have used a divider like this</p>

```<code>this.divider = 100 / this.loaderValue;
<v-progress-circular :rotate="-90" :size="100" :width="15" :value="divider * loaderValue" class="mb-2" :color="yellow">
</code>```

Body:
Change the :value property to a number that you multiply with loaderValue to get 100. For my case. I have used a divider like this

this.divider = 100 / this.loaderValue;
<v-progress-circular :rotate="-90" :size="100" :width="15" :value="divider * loaderValue" class="mb-2" :color="yellow">


问:
Python - Create a new sublist between two elements in an ordered list
Given two elements in an ordered list, I want to make a  new list consisting of everything between (and including) those elements.
The problem comes if the second point comes before the first point in the list.
right is my existing sorted list of objects. rt is the beginning boundary and rb is the end boundary.
new_right = right[right.index(rt): right.index(rb) + 1]

This snippet works except in the case

right = [a, rb, c, rt, d, e]

where I get [rt, d, e] instead of the wrapped [rt, d, e, a, rb]

Is there a way to do this without creating a complicated method? Some other people's problems were solved by list comprehension. Looking into it, I was able to come up with

```<code>begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = [right[i % r_len] for i in range(begin, r_len + end + 1)]
</code>```

Which looks pretty ugly to me, but it seems to hold up to my tests.
Is there a better way to do this?

EDIT:
There were two working solutions to this.

```<code>rbegin = right.index(rt)
rend = right.index(rb)
if rend >= rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = [right[i % r_len] for i in range(rbegin, r_len + rend + 1)]
</code>```

Which is obscenely complicated compared to:

```<code>if rend > rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = right[rbegin:] + right[:rend + 1]
</code>```

答:
Would simply flipping the slice match your tests like so:</p>

```<code>begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = right[end: begin + 1]
</code>```

Body:
Given two elements in an ordered list, I want to make a  new list consisting of everything between (and including) those elements.
The problem comes if the second point comes before the first point in the list.
right is my existing sorted list of objects. rt is the beginning boundary and rb is the end boundary.
new_right = right[right.index(rt): right.index(rb) + 1]

This snippet works except in the case

right = [a, rb, c, rt, d, e]

where I get [rt, d, e] instead of the wrapped [rt, d, e, a, rb]

Is there a way to do this without creating a complicated method? Some other people's problems were solved by list comprehension. Looking into it, I was able to come up with

begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = [right[i % r_len] for i in range(begin, r_len + end + 1)]

Which looks pretty ugly to me, but it seems to hold up to my tests.
Is there a better way to do this?

EDIT:
There were two working solutions to this.

rbegin = right.index(rt)
rend = right.index(rb)
if rend >= rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = [right[i % r_len] for i in range(rbegin, r_len + rend + 1)]

Which is obscenely complicated compared to:

if rend > rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = right[rbegin:] + right[:rend + 1]

Body:
Would simply flipping the slice match your tests like so:

begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = right[end: begin + 1]


问:
Add FormControl accroding to the data returned from backend but got two different error in Angular app
This is one of the page of my Angular app.

Inside the ngOnInit method, I call the api twice to get different data I need and loop through the data by using forEach method to build reactive form, but somehow, I encountered one of two different error.

This

enter image description here

and this

enter image description here

and sometime there is no error at all.

It would be grateful if someone can tell me what's wrong with my code.

here is part of my code

user-manager.component.ts

```<code>export class UserManagerComponent implements OnInit {
    constructor(
    private fb: FormBuilder
  ) {}
    ngOnInit(): void {
        this.commonData.getDropdownData('menus')
        .pipe(takeWhile(() => this.alive))
        .subscribe(r => {
          if (r.status === 0) {
            this.menuForm = this.fb.group({});
            this.menuList = r.result.menus;
            this.menuList.forEach(i => {
              const control = new FormControl();
             (this.menuForm as FormGroup).setControl(i.MenuId, control);
              i.children.forEach(a => {
                const con = new FormControl();
                (this.menuForm as FormGroup).setControl(a.MenuId, con);
              });
            });
            this.isMenuFormReady = true;
      } else {
        this.toastrService.danger(r.message);
      }
    },
      error => {
        if (!environment.production) {
          this.menuForm = this.fb.group({});
          this.menuList = menuMock.menus;
          this.menuList.forEach(i => {

            const control = new FormControl();

            (this.menuForm as FormGroup).setControl(i.MenuId, control);

            i.children.forEach(a => {
              const con = new FormControl();
              (this.menuForm as FormGroup).setControl(a.MenuId, con);
            });

          });
          this.isMenuFormReady = true;
        }
          console.log(error);
      });

    this.commonData.getDropdownData('permissions')
    .pipe(takeWhile(() => this.alive))
    .subscribe(r => {
      if (r.status === 0) {
        this.permissionsForm = this.fb.group({});
        this.permissionsList = r.result;
        this.permissionsList = this.groupBy(this.permissionsList, function(item) {
          return [item.GroupId];
      });

      this.permissionsList.forEach(i => {

        const id = i[0].GroupId;
        this.permissionsForm.addControl(id, this.fb.group({}));

        i.forEach(a => {
          const con = new FormControl();
          (this.permissionsForm.get(id) as FormGroup).addControl(a.ActionId, con);
        });
      });
      this.isPermissionFormReady = true;

      } else {
        this.toastrService.danger(r.message);
      }
    },
      error => {
        if (!environment.production) {
          this.permissionsForm = this.fb.group({});
          this.permissionsList = userMock.Permission;
          this.permissionsList = this.groupBy(this.permissionsList, function(item) {
            return [item.GroupId];
        });

          this.permissionsList.forEach(i => {

            const id = i[0].GroupId;
            // console.log('id: ', id)
            this.permissionsForm.addControl(id, this.fb.group({}));

            i.forEach(a => {
              const con = new FormControl();
              (this.permissionsForm.get(id) as FormGroup).addControl(a.ActionId, con);
            });
          });
          this.isPermissionFormReady = true;
          // console.log(this.permissionsForm);
        }
          console.log(error);
      });
  }
    groupBy( array , f ) {
        const groups = {};
        array.forEach( function(o) {
            const group = JSON.stringify( f(o) );
            groups[group] = groups[group] || [];
            groups[group].push( o );
        });
        return Object.keys(groups).map( function( group ) {
            return groups[group];
        });
    }
}
</code>```

user-manager.component.html

```<code>      <nb-card>

          <nb-card-header>
            form1
          </nb-card-header>
          <nb-card-body>
              <form [formGroup]="permissionsForm" autocomplete="off" *ngIf="isPermissionFormReady">
            <nb-card *ngFor="let item of permissionsList; let i = index;" [formGroupName]="i">
              <nb-card-header>
                {{item[0].GroupName}}
              </nb-card-header>
              <nb-card-body class="pt-0">
                <div class="row">
                  <div class="col-4 my-1" *ngFor="let permission of item">
                    <label>
                      <input type="checkbox" [formControlName]="permission.ActionId"/>
                      {{permission.ActionName}}
                    </label>
                  </div>
                </div>
              </nb-card-body>
            </nb-card>
          </form>
          </nb-card-body>

        </nb-card>

        <nb-card>
            <nb-card-header>
              form2
            </nb-card-header>
            <nb-card-body>
              <form [formGroup]="menuForm" autocomplete="off" *ngIf="isMenuFormReady">
                <div class="row">
                    <div class="col-4" *ngFor="let menu of menuList" >
                        <nb-card>
                          <nb-card-header>
                            <label>
                              <input type="checkbox" id="{{menu.MenuId}}" [formControlName]="menu.MenuId" (change)="menuClick($event)"/>
                              {{menu.title}}
                            </label>
                          </nb-card-header>
                          <nb-card-body class="pt-0">
                            <div class="row">
                              <div class="col-12 my-1" *ngFor="let item of menu.children">
                                <label>
                                  <input type="checkbox" id="{{item.MenuId}}" [formControlName]="item.MenuId" (change)="menuClick($event)"/>
                                  {{item.title}}
                                </label>
                              </div>
                            </div>
                          </nb-card-body>
                        </nb-card>
                      </div>
                </div>
              </form>
            </nb-card-body>
          </nb-card>
</code>```

答:
There is currently a bug in Chrome 80 which makes Array.reduce not to work according to the spec. So If you are using reactive form in your project you will face browser specific issue like ( form.get('key').value is undefined or valuechanges is undefined even if it exists), which was working fine in chrome 79.  To fix this issue,  add Array.reduce polyfill in your angular project manually as shown below.

Add this to main.ts

```<code>(function () {
 function getChromeVersion() {
 const raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);

 return raw ? parseInt(raw[2], 10) : false;
    }

 const chromeVersion = getChromeVersion();
 if (chromeVersion && chromeVersion >= 80) {
      Array.prototype.reduce = function (callback /*, initialValue*/) {
 'use strict';
 if (this == null) {
 throw new TypeError('Array.prototype.reduce called on null or undefined');
        }
 if (typeof callback !== 'function') {
 throw new TypeError(callback + ' is not a function');
        }
 let t = Object(this), len = t.length >>> 0, k = 0, value;
 if (arguments.length === 2) {
          value = arguments[1];
        } else {
 while (k < len && !(k in t)) {
            k++;
          }
 if (k >= len) {
 throw new TypeError('Reduce of empty array with no initial value');
          }
          value = t[k++];
        }
 for (; k < len; k++) {
 if (k in t) {
            value = callback(value, t[k], k, t);
          }
        }
 return value;
      };
    }
  })();
</code>```

ForMoreInfo

Body:
This is one of the page of my Angular app.

Inside the ngOnInit method, I call the api twice to get different data I need and loop through the data by using forEach method to build reactive form, but somehow, I encountered one of two different error.

This

enter image description here

and this

enter image description here

and sometime there is no error at all.

It would be grateful if someone can tell me what's wrong with my code.

here is part of my code

user-manager.component.ts

export class UserManagerComponent implements OnInit {
    constructor(
    private fb: FormBuilder
  ) {}
    ngOnInit(): void {
        this.commonData.getDropdownData('menus')
        .pipe(takeWhile(() => this.alive))
        .subscribe(r => {
          if (r.status === 0) {
            this.menuForm = this.fb.group({});
            this.menuList = r.result.menus;
            this.menuList.forEach(i => {
              const control = new FormControl();
             (this.menuForm as FormGroup).setControl(i.MenuId, control);
              i.children.forEach(a => {
                const con = new FormControl();
                (this.menuForm as FormGroup).setControl(a.MenuId, con);
              });
            });
            this.isMenuFormReady = true;
      } else {
        this.toastrService.danger(r.message);
      }
    },
      error => {
        if (!environment.production) {
          this.menuForm = this.fb.group({});
          this.menuList = menuMock.menus;
          this.menuList.forEach(i => {

            const control = new FormControl();

            (this.menuForm as FormGroup).setControl(i.MenuId, control);

            i.children.forEach(a => {
              const con = new FormControl();
              (this.menuForm as FormGroup).setControl(a.MenuId, con);
            });

          });
          this.isMenuFormReady = true;
        }
          console.log(error);
      });

    this.commonData.getDropdownData('permissions')
    .pipe(takeWhile(() => this.alive))
    .subscribe(r => {
      if (r.status === 0) {
        this.permissionsForm = this.fb.group({});
        this.permissionsList = r.result;
        this.permissionsList = this.groupBy(this.permissionsList, function(item) {
          return [item.GroupId];
      });

      this.permissionsList.forEach(i => {

        const id = i[0].GroupId;
        this.permissionsForm.addControl(id, this.fb.group({}));

        i.forEach(a => {
          const con = new FormControl();
          (this.permissionsForm.get(id) as FormGroup).addControl(a.ActionId, con);
        });
      });
      this.isPermissionFormReady = true;

      } else {
        this.toastrService.danger(r.message);
      }
    },
      error => {
        if (!environment.production) {
          this.permissionsForm = this.fb.group({});
          this.permissionsList = userMock.Permission;
          this.permissionsList = this.groupBy(this.permissionsList, function(item) {
            return [item.GroupId];
        });

          this.permissionsList.forEach(i => {

            const id = i[0].GroupId;
            // console.log('id: ', id)
            this.permissionsForm.addControl(id, this.fb.group({}));

            i.forEach(a => {
              const con = new FormControl();
              (this.permissionsForm.get(id) as FormGroup).addControl(a.ActionId, con);
            });
          });
          this.isPermissionFormReady = true;
          // console.log(this.permissionsForm);
        }
          console.log(error);
      });
  }
    groupBy( array , f ) {
        const groups = {};
        array.forEach( function(o) {
            const group = JSON.stringify( f(o) );
            groups[group] = groups[group] || [];
            groups[group].push( o );
        });
        return Object.keys(groups).map( function( group ) {
            return groups[group];
        });
    }
}

user-manager.component.html

      <nb-card>

          <nb-card-header>
            form1
          </nb-card-header>
          <nb-card-body>
              <form [formGroup]="permissionsForm" autocomplete="off" *ngIf="isPermissionFormReady">
            <nb-card *ngFor="let item of permissionsList; let i = index;" [formGroupName]="i">
              <nb-card-header>
                {{item[0].GroupName}}
              </nb-card-header>
              <nb-card-body class="pt-0">

                      <input type="checkbox" [formControlName]="permission.ActionId"/>
                      {{permission.ActionName}}

              </nb-card-body>
            </nb-card>
          </form>
          </nb-card-body>

        </nb-card>

        <nb-card>
            <nb-card-header>
              form2
            </nb-card-header>
            <nb-card-body>
              <form [formGroup]="menuForm" autocomplete="off" *ngIf="isMenuFormReady">

                        <nb-card>
                          <nb-card-header>

                              <input type="checkbox" id="{{menu.MenuId}}" [formControlName]="menu.MenuId" (change)="menuClick($event)"/>
                              {{menu.title}}

                          </nb-card-header>
                          <nb-card-body class="pt-0">

                                  <input type="checkbox" id="{{item.MenuId}}" [formControlName]="item.MenuId" (change)="menuClick($event)"/>
                                  {{item.title}}

                          </nb-card-body>
                        </nb-card>

              </form>
            </nb-card-body>
          </nb-card>

Body:
There is currently a bug in Chrome 80 which makes Array.reduce not to work according to the spec. So If you are using reactive form in your project you will face browser specific issue like ( form.get('key').value is undefined or valuechanges is undefined even if it exists), which was working fine in chrome 79.  To fix this issue,  add Array.reduce polyfill in your angular project manually as shown below.

Add this to main.ts

(function () {
 function getChromeVersion() {
 const raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);

 return raw ? parseInt(raw[2], 10) : false;
    }

 const chromeVersion = getChromeVersion();
 if (chromeVersion && chromeVersion >= 80) {
      Array.prototype.reduce = function (callback /*, initialValue*/) {
 'use strict';
 if (this == null) {
 throw new TypeError('Array.prototype.reduce called on null or undefined');
        }
 if (typeof callback !== 'function') {
 throw new TypeError(callback + ' is not a function');
        }
 let t = Object(this), len = t.length >>> 0, k = 0, value;
 if (arguments.length === 2) {
          value = arguments[1];
        } else {
 while (k < len && !(k in t)) {
            k++;
          }
 if (k >= len) {
 throw new TypeError('Reduce of empty array with no initial value');
          }
          value = t[k++];
        }
 for (; k < len; k++) {
 if (k in t) {
            value = callback(value, t[k], k, t);
          }
        }
 return value;
      };
    }
  })();

ForMoreInfo


问:
Sybase - SAP ASE - replication server: routing declaration
I'm trying to declare a routing in SAP Replication Server.

I have:

A server (let's call it S1) with ASE and RS server (let's call it RS1).

A server (let's call it S2) with ASE and RS server (let's call it RS2).

A server (let's call it S3) with ASE server.

I have A replication in RS1 from database in S1 to databases in S1 and S2.

Now I'm trying to add a replication to a database in S3 via RS2: a routing from RS1 to RS2 and a subscription to the DB in S3.

I declared the routing, an agent between the 2 RSSDs.

When I'm trying to set the subscription (in RS2) to the databse in S3 I've got an error - saying that it doesn't know the replication definition.

Anyone familiar with routing declaration?

Thanks.

答:
The critical thing with routes is they both need to be in the same replication system, meaning they must share the SAME primary rep server (known as the ID server) - this contains information about all the replication servers in the replication server setup, or domain as it's known. You can create many replication servers in a domain, but for them to be able to link together via routes they must all use the same ID server.

NOTE: You can't set them up separately and then link them later. When you set up RS2 you have say RS1 is the id server and put in all the required info into rs_init for RS1 as you run through the various rs_init menus to create RS2.

If that's been done already correctly then:

Firstly set up route between RS1 and RS2 (via a 'create route' command here) if you want data to flow in both directions at some point it makes sense to setup routes both ways between RS1 and RS2, as by definition a route is in one direction. This will mean you can set replication up between any of the three ASE instances.

NOTE: You need to check that the route is actually fully up and active (via admin who) - if not then you need to start looking through the rep server errorlogs as to why that's failing e.g. missing entry in interfaces file, login issue etc.

One routes are set-up you can create a subscription replication definition against the source database and a subscription at the target database when these are attached to different replication servers. This can be at the table-level or a database-level replication definition (MSA) depending on what your aim is.