问:
XSL-FO how to propagate page numbering from template to another
It is my first experience in XSL-FO printing.

There are 2 templates each has its own layout.xsl

It is needed to edit the page numbering of second template to be successor to the first one.

Example

template one has 4 pages, then template two should start by page no. 5 not 1!

I have an ideas but still doesn't work; is to create a 3rd template that call these 2 templates

```<code><xsl:template>
        <xsl:call-template name="templateOne" />
        <!-- <xsl:block break-after="page"/> -->
        <xsl:call-template name="templateTwo" />
        <!-- <xsl:block break-after="page"/> -->
</xsl:template>
</code>```

Layout of templateOne:

```<code><xsl:template match="/">
        <fo:root>
            <xsl:call-template name="LayoutMasterSet"/>
            <xsl:variable name="TheVeryLastPage" select="."/>
            <xsl:choose>
                <xsl:when test="$titel='Anwendungsprotokoll'">
                    <fo:page-sequence master-reference="landscape" initial-page-number="1" format="1">
                        <!-- Kopfzeile -->
                        <xsl:call-template name="StandardKopfzeile">
                            <xsl:with-param name="TheVeryLastPage"><xsl:value-of select="$TheVeryLastPage"/></xsl:with-param>
                        </xsl:call-template>
                        <!-- Fusszeile -->
                        <xsl:call-template name="StandardFusszeile">
                            <xsl:with-param name="TheVeryLastPage"><xsl:value-of select="$TheVeryLastPage"/></xsl:with-param>
                        </xsl:call-template>
                        <fo:flow flow-name="xsl-region-body">
                            <fo:block font-size="8pt" line-height="10pt">
                                <xsl:apply-templates select="/*"/>
                            </fo:block>
                            <fo:block id="{generate-id($TheVeryLastPage)}"/>
                        </fo:flow>
                    </fo:page-sequence>
                </xsl:when>
                <xsl:otherwise>
                    <fo:page-sequence master-reference="default-pages" initial-page-number="1" format="1">
                        <!-- Kopfzeile -->
                        <xsl:call-template name="StandardKopfzeile">
                            <xsl:with-param name="TheVeryLastPage"><xsl:value-of select="$TheVeryLastPage"/></xsl:with-param>
                        </xsl:call-template>
                        <!-- Fusszeile -->
                        <xsl:call-template name="StandardFusszeile">
                            <xsl:with-param name="TheVeryLastPage"><xsl:value-of select="$TheVeryLastPage"/></xsl:with-param>
                        </xsl:call-template>
                        <fo:flow flow-name="xsl-region-body">
                            <fo:block font-size="8pt" line-height="10pt">
                                <xsl:apply-templates select="/*"/>
                            </fo:block>
                            <fo:block id="{generate-id($TheVeryLastPage)}"/>
                        </fo:flow>
                    </fo:page-sequence>
                </xsl:otherwise>
            </xsl:choose>
        </fo:root>
    </xsl:template>
</code>```

Layout of templateTwo:

```<code><xsl:template match="/">
        <fo:root xsl:use-attribute-sets="font.arial.8.normal.black">
            <xsl:call-template name="LayoutMasterSet"/>
            <xsl:variable name="TheVeryLastPage" select="."/>
            <fo:page-sequence master-reference="default-pages" initial-page-number="1" format="1">
                <xsl:call-template name="StandardHeader"/>
                <xsl:call-template name="GeneralFooter">
                    <xsl:with-param name="TheVeryLastPage">
                        <xsl:value-of select="$TheVeryLastPage"/>
                    </xsl:with-param>
                </xsl:call-template>
                <xsl:apply-templates select="/*"/>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>
    <!-- ++++++++++++++++++++++++++++++++++Layout Master Set+++++++++++++++++++++++++++++++++++++++++++++ -->
    <xsl:template name="LayoutMasterSet">
        <fo:layout-master-set>
            <fo:simple-page-master master-name="any-page" page-height="297mm" page-width="210mm" margin-top="1.5cm" margin-bottom="1.5cm" margin-left="1.5cm" margin-right="1.5cm">
                <fo:region-body margin-top="2cm" margin-bottom="2cm" column-count="{$columns}"/>
                <fo:region-before extent="2cm" region-name="region-before"/>
                <fo:region-after extent="2cm" region-name="region-after"/>
            </fo:simple-page-master>
            <fo:page-sequence-master master-name="default-pages">
                <fo:repeatable-page-master-alternatives>
                    <fo:conditional-page-master-reference page-position="any" master-reference="any-page"/>
                </fo:repeatable-page-master-alternatives>
            </fo:page-sequence-master>
        </fo:layout-master-set>
    </xsl:template>
</code>```

This idea doesn't work, it gives me:

```<code>saving .xsl. <anonymous development build> javax.xml.transform.TransformerException: org.apache.fop.fo.ValidationException: "{http://www.w3.org/1999/XSL/Format}table" is not a valid child of "fo:page-sequence"!

ERROR |17:33:05,752|DefaultExceptionHandler.logException:75 (WorkerThread 17:31:48)[-1] TRANSFORMATION_ERROR [] <anonymous development build>
de.vodafone.core.exception.BadProcessingException: [-1] TRANSFORMATION_ERROR []
    at de.vodafone.app.epos.shared.print.fop.FopPrintService.addToPageable(FopPrintService.java:165)
    at de.vodafone.app.epos.shared.print.fop.FopPrintService.print(FopPrintService.java:78)
    at de.vodafone.app.epos.shared.print.fop.PrintServiceDelegator.print(PrintServiceDelegator.java:53)
    at de.vodafone.app.epos.shared.print.activity.AbstractPrintAgent.execute(AbstractPrintAgent.java:213)
    at de.vodafone.app.epos.shared.activity.ActivityManager.execute(ActivityManager.java:78)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderFacade.executeActivities(AbstractOrderFacade.java:210)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.SingleCustomerOrderFacade.handleAfterSave(SingleCustomerOrderFacade.java:101)
    at de.vodafone.app.epos.client.plugin.fixednet.activation.mvc.FNActivationFacade.handleAfterSave(FNActivationFacade.java:370)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderFacade.save(AbstractOrderFacade.java:335)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderFacade.save(AbstractOrderFacade.java:298)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderFacade.send(AbstractOrderFacade.java:117)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderController.send(AbstractOrderController.java:943)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderController.onSend(AbstractOrderController.java:861)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderController$10.doExecuteCommand(AbstractOrderController.java:1258)
    at de.vodafone.app.epos.client.framework.ui.action.AbstractWidgetActionUIJob.execute(AbstractWidgetActionUIJob.java:45)
    at de.vodafone.app.epos.client.framework.ui.action.RunnableBuilder$CommandRunnable.run(RunnableBuilder.java:196)
    at de.vodafone.app.epos.client.framework.ui.action.AbstractUIJob.run(AbstractUIJob.java:50)
    at EDU.oswego.cs.dl.util.concurrent.QueuedExecutor$RunLoop.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:748)
Caused by: javax.xml.transform.TransformerException: org.apache.fop.fo.ValidationException: "{http://www.w3.org/1999/XSL/Format}table" is not a valid child of "fo:page-sequence"! (Siehe Position 17:276)
    at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:469)
    at de.vodafone.app.epos.shared.print.fop.FopPrintService.addToPageable(FopPrintService.java:156)
    ... 18 more
Caused by: org.apache.fop.fo.ValidationException: "{http://www.w3.org/1999/XSL/Format}table" is not a valid child of "fo:page-sequence"! (Siehe Position 17:276)
    at org.apache.fop.events.ValidationExceptionFactory.createException(ValidationExceptionFactory.java:38)
    at org.apache.fop.events.EventExceptionManager.throwException(EventExceptionManager.java:54)
    at org.apache.fop.events.DefaultEventBroadcaster$1.invoke(DefaultEventBroadcaster.java:175)
    at com.sun.proxy.$Proxy1.invalidChild(Unknown Source)
    at org.apache.fop.fo.FONode.invalidChildError(FONode.java:534)
    at org.apache.fop.fo.FONode.invalidChildError(FONode.java:517)
    at org.apache.fop.fo.pagination.PageSequence.validateChildNode(PageSequence.java:147)
    at org.apache.fop.fo.FOTreeBuilder$MainFOHandler.startElement(FOTreeBuilder.java:267)
    at org.apache.fop.fo.FOTreeBuilder.startElement(FOTreeBuilder.java:171)
    at org.apache.xalan.transformer.TransformerIdentityImpl.startElement(TransformerIdentityImpl.java:1020)
    at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
    at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:452)
    ... 19 more
</code>```

Cause I am not the one that write these huge templates, I couldn't find the bad location of fo:table inside fo:page-sequence

Moreover, the page number is not propagated. I think to define a param that initially by 1 and setted by the last page of templateOne to be incremented by 1 and initialized the first page of Template 2 just after fixing the previous formation exception.

Your help is really appricated
Thanks a lot
Mariam

答:
To solve the fo:table problem, you need an fo:flow inside your fo:page-sequence (see https://www.w3.org/TR/xsl11/#fo_page-sequence). templateOne has it (but the properties on the fo:block inside the fo:flow could be put on the fo:flow and the fo:block could be omitted). templateTwo does not have an fo:flow inside its fo:page-sequence.

Your other problem is that both templates create an fo:root. fo:root is, as the name implies, the root of the FO document. Since the FO document that you are generating is also an XML document, the document can only have one 'document' element, i.e., one fo:root.

Please see this diagram from Section 6.4.1.6, Pagination Tree Structure, of the XSL 1.1 Recommendation (https://www.w3.org/TR/xsl11/#d0e7181)

However, the diagram fails to show that fo:root may contain multiple fo:page-sequence (see https://www.w3.org/TR/xsl11/#fo_root).

To get templateOne and templateTwo to work together, you should generate one fo:root and one fo:layout-master-set and have templateOne and templateTwo generate content starting at the fo:page-sequence level.  Something like:

```<code>fo:root
  fo:layout-master-set
  fo:page-sequence (generated by templateOne)
  fo:page-sequence (generated by templateTwo)
</code>```

If you do all that, then you will have solved the question in the title. The default value for the initial-page-number property (see https://www.w3.org/TR/xsl11/#initial-page-number) on each fo:page-sequence will make the second fo:page-sequence start with the page number after the last page number of the previous fo:page-sequence.

Another lurking problem is that both templateOne and templateTwo include:

```<code><xsl:apply-templates select="/*"/>
</code>```

If you are processing one source document, then you are going to get two copies of your content. We can't help you with that unless we know more about the structure of the XML that you are trying to process.

Body:
It is my first experience in XSL-FO printing.

There are 2 templates each has its own layout.xsl

It is needed to edit the page numbering of second template to be successor to the first one.

Example

template one has 4 pages, then template two should start by page no. 5 not 1!

I have an ideas but still doesn't work; is to create a 3rd template that call these 2 templates

<xsl:template>
        <xsl:call-template name="templateOne" />

        <xsl:call-template name="templateTwo" />

</xsl:template>

Layout of templateOne:

<xsl:template match="/">
        <fo:root>
            <xsl:call-template name="LayoutMasterSet"/>
            <xsl:variable name="TheVeryLastPage" select="."/>
            <xsl:choose>
                <xsl:when test="$titel='Anwendungsprotokoll'">
                    <fo:page-sequence master-reference="landscape" initial-page-number="1" format="1">

                        <xsl:call-template name="StandardKopfzeile">
                            <xsl:with-param name="TheVeryLastPage"><xsl:value-of select="$TheVeryLastPage"/></xsl:with-param>
                        </xsl:call-template>

                        <xsl:call-template name="StandardFusszeile">
                            <xsl:with-param name="TheVeryLastPage"><xsl:value-of select="$TheVeryLastPage"/></xsl:with-param>
                        </xsl:call-template>
                        <fo:flow flow-name="xsl-region-body">
                            <fo:block font-size="8pt" line-height="10pt">
                                <xsl:apply-templates select="/*"/>
                            </fo:block>
                            <fo:block id="{generate-id($TheVeryLastPage)}"/>
                        </fo:flow>
                    </fo:page-sequence>
                </xsl:when>
                <xsl:otherwise>
                    <fo:page-sequence master-reference="default-pages" initial-page-number="1" format="1">

                        <xsl:call-template name="StandardKopfzeile">
                            <xsl:with-param name="TheVeryLastPage"><xsl:value-of select="$TheVeryLastPage"/></xsl:with-param>
                        </xsl:call-template>

                        <xsl:call-template name="StandardFusszeile">
                            <xsl:with-param name="TheVeryLastPage"><xsl:value-of select="$TheVeryLastPage"/></xsl:with-param>
                        </xsl:call-template>
                        <fo:flow flow-name="xsl-region-body">
                            <fo:block font-size="8pt" line-height="10pt">
                                <xsl:apply-templates select="/*"/>
                            </fo:block>
                            <fo:block id="{generate-id($TheVeryLastPage)}"/>
                        </fo:flow>
                    </fo:page-sequence>
                </xsl:otherwise>
            </xsl:choose>
        </fo:root>
    </xsl:template>

Layout of templateTwo:

<xsl:template match="/">
        <fo:root xsl:use-attribute-sets="font.arial.8.normal.black">
            <xsl:call-template name="LayoutMasterSet"/>
            <xsl:variable name="TheVeryLastPage" select="."/>
            <fo:page-sequence master-reference="default-pages" initial-page-number="1" format="1">
                <xsl:call-template name="StandardHeader"/>
                <xsl:call-template name="GeneralFooter">
                    <xsl:with-param name="TheVeryLastPage">
                        <xsl:value-of select="$TheVeryLastPage"/>
                    </xsl:with-param>
                </xsl:call-template>
                <xsl:apply-templates select="/*"/>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>

    <xsl:template name="LayoutMasterSet">
        <fo:layout-master-set>
            <fo:simple-page-master master-name="any-page" page-height="297mm" page-width="210mm" margin-top="1.5cm" margin-bottom="1.5cm" margin-left="1.5cm" margin-right="1.5cm">
                <fo:region-body margin-top="2cm" margin-bottom="2cm" column-count="{$columns}"/>
                <fo:region-before extent="2cm" region-name="region-before"/>
                <fo:region-after extent="2cm" region-name="region-after"/>
            </fo:simple-page-master>
            <fo:page-sequence-master master-name="default-pages">
                <fo:repeatable-page-master-alternatives>
                    <fo:conditional-page-master-reference page-position="any" master-reference="any-page"/>
                </fo:repeatable-page-master-alternatives>
            </fo:page-sequence-master>
        </fo:layout-master-set>
    </xsl:template>

This idea doesn't work, it gives me:

saving .xsl. <anonymous development build> javax.xml.transform.TransformerException: org.apache.fop.fo.ValidationException: "{http://www.w3.org/1999/XSL/Format}table" is not a valid child of "fo:page-sequence"!

ERROR |17:33:05,752|DefaultExceptionHandler.logException:75 (WorkerThread 17:31:48)[-1] TRANSFORMATION_ERROR [] <anonymous development build>
de.vodafone.core.exception.BadProcessingException: [-1] TRANSFORMATION_ERROR []
    at de.vodafone.app.epos.shared.print.fop.FopPrintService.addToPageable(FopPrintService.java:165)
    at de.vodafone.app.epos.shared.print.fop.FopPrintService.print(FopPrintService.java:78)
    at de.vodafone.app.epos.shared.print.fop.PrintServiceDelegator.print(PrintServiceDelegator.java:53)
    at de.vodafone.app.epos.shared.print.activity.AbstractPrintAgent.execute(AbstractPrintAgent.java:213)
    at de.vodafone.app.epos.shared.activity.ActivityManager.execute(ActivityManager.java:78)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderFacade.executeActivities(AbstractOrderFacade.java:210)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.SingleCustomerOrderFacade.handleAfterSave(SingleCustomerOrderFacade.java:101)
    at de.vodafone.app.epos.client.plugin.fixednet.activation.mvc.FNActivationFacade.handleAfterSave(FNActivationFacade.java:370)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderFacade.save(AbstractOrderFacade.java:335)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderFacade.save(AbstractOrderFacade.java:298)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderFacade.send(AbstractOrderFacade.java:117)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderController.send(AbstractOrderController.java:943)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderController.onSend(AbstractOrderController.java:861)
    at de.vodafone.app.epos.client.plugin.order.manager.common.presentation.AbstractOrderController$10.doExecuteCommand(AbstractOrderController.java:1258)
    at de.vodafone.app.epos.client.framework.ui.action.AbstractWidgetActionUIJob.execute(AbstractWidgetActionUIJob.java:45)
    at de.vodafone.app.epos.client.framework.ui.action.RunnableBuilder$CommandRunnable.run(RunnableBuilder.java:196)
    at de.vodafone.app.epos.client.framework.ui.action.AbstractUIJob.run(AbstractUIJob.java:50)
    at EDU.oswego.cs.dl.util.concurrent.QueuedExecutor$RunLoop.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:748)
Caused by: javax.xml.transform.TransformerException: org.apache.fop.fo.ValidationException: "{http://www.w3.org/1999/XSL/Format}table" is not a valid child of "fo:page-sequence"! (Siehe Position 17:276)
    at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:469)
    at de.vodafone.app.epos.shared.print.fop.FopPrintService.addToPageable(FopPrintService.java:156)
    ... 18 more
Caused by: org.apache.fop.fo.ValidationException: "{http://www.w3.org/1999/XSL/Format}table" is not a valid child of "fo:page-sequence"! (Siehe Position 17:276)
    at org.apache.fop.events.ValidationExceptionFactory.createException(ValidationExceptionFactory.java:38)
    at org.apache.fop.events.EventExceptionManager.throwException(EventExceptionManager.java:54)
    at org.apache.fop.events.DefaultEventBroadcaster$1.invoke(DefaultEventBroadcaster.java:175)
    at com.sun.proxy.$Proxy1.invalidChild(Unknown Source)
    at org.apache.fop.fo.FONode.invalidChildError(FONode.java:534)
    at org.apache.fop.fo.FONode.invalidChildError(FONode.java:517)
    at org.apache.fop.fo.pagination.PageSequence.validateChildNode(PageSequence.java:147)
    at org.apache.fop.fo.FOTreeBuilder$MainFOHandler.startElement(FOTreeBuilder.java:267)
    at org.apache.fop.fo.FOTreeBuilder.startElement(FOTreeBuilder.java:171)
    at org.apache.xalan.transformer.TransformerIdentityImpl.startElement(TransformerIdentityImpl.java:1020)
    at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
    at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:452)
    ... 19 more

Cause I am not the one that write these huge templates, I couldn't find the bad location of fo:table inside fo:page-sequence

Moreover, the page number is not propagated. I think to define a param that initially by 1 and setted by the last page of templateOne to be incremented by 1 and initialized the first page of Template 2 just after fixing the previous formation exception.

Your help is really appricated
Thanks a lot
Mariam

Body:
To solve the fo:table problem, you need an fo:flow inside your fo:page-sequence (see https://www.w3.org/TR/xsl11/#fo_page-sequence). templateOne has it (but the properties on the fo:block inside the fo:flow could be put on the fo:flow and the fo:block could be omitted). templateTwo does not have an fo:flow inside its fo:page-sequence.

Your other problem is that both templates create an fo:root. fo:root is, as the name implies, the root of the FO document. Since the FO document that you are generating is also an XML document, the document can only have one 'document' element, i.e., one fo:root.

Please see this diagram from Section 6.4.1.6, Pagination Tree Structure, of the XSL 1.1 Recommendation (https://www.w3.org/TR/xsl11/#d0e7181)

However, the diagram fails to show that fo:root may contain multiple fo:page-sequence (see https://www.w3.org/TR/xsl11/#fo_root).

To get templateOne and templateTwo to work together, you should generate one fo:root and one fo:layout-master-set and have templateOne and templateTwo generate content starting at the fo:page-sequence level.  Something like:

fo:root
  fo:layout-master-set
  fo:page-sequence (generated by templateOne)
  fo:page-sequence (generated by templateTwo)

If you do all that, then you will have solved the question in the title. The default value for the initial-page-number property (see https://www.w3.org/TR/xsl11/#initial-page-number) on each fo:page-sequence will make the second fo:page-sequence start with the page number after the last page number of the previous fo:page-sequence.

Another lurking problem is that both templateOne and templateTwo include:

<xsl:apply-templates select="/*"/>

If you are processing one source document, then you are going to get two copies of your content. We can't help you with that unless we know more about the structure of the XML that you are trying to process.


来源: stackexchange

问:
How to implement sign out function in the new navigation drawer in android studio?
I would like to implement the sign out method in my project. i watch all youtube tutorial but seems like the navigation drawer is the update version. and i'm clueless on how to implement those sign out coding into my coding.

the newest version of the navigation drawer already built in with the ui package folder. So i'm not quite sure on how to implement those tutorial code  because most of the tutorial code have this code.
 below is the tutorial code and i don't know on how to implement the sign out method into my home.java code. thank you

```<code> @SuppressWarnings("StatementWithEmptyBody")
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            // Handle navigation view item clicks here.
            int id = item.getItemId();

            if (id == R.id.nav_home) {

                getSupportActionBar().setTitle("Home");
                getSupportFragmentManager().beginTransaction().replace(R.id.container,new HomeFragment()).commit();

            } else if (id == R.id.nav_profile) {

                getSupportActionBar().setTitle("Profile");
                getSupportFragmentManager().beginTransaction().replace(R.id.container,new ProfileFragment()).commit();

            } else if (id == R.id.nav_settings) {

                getSupportActionBar().setTitle("Settings");
                getSupportFragmentManager().beginTransaction().replace(R.id.container,new SettingsFragment()).commit();

            }
            else if (id == R.id.nav_signout) {

                FirebaseAuth.getInstance().signOut();
                Intent loginActivity = new Intent(getApplicationContext(),LoginActivity.class);
                startActivity(loginActivity);
                finish();

            }

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }

</code>```

this is my home.java code

```<code>package com.example.guru;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import androidx.drawerlayout.widget.DrawerLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.Menu;
import android.widget.TextView;

public class Home extends AppCompatActivity {

    FirebaseAuth firebaseAuth;
    FirebaseUser currentUser;
    DatabaseReference databaseReference;

    private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //ini
        firebaseAuth = FirebaseAuth.getInstance();
        currentUser = firebaseAuth.getCurrentUser();
        databaseReference = FirebaseDatabase.getInstance().getReference("Customer");

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = findViewById(R.id.drawer_layout);

        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_profile, R.id.nav_orders,R.id.nav_logout)
                .setDrawerLayout(drawer)
                .build();

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        updateNavHeader();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    public void updateNavHeader() {
        NavigationView navigationView = findViewById(R.id.nav_view);
        View headerView= navigationView.getHeaderView(0);
        TextView navName= headerView.findViewById(R.id.txtName);
        TextView navEmail=headerView.findViewById(R.id.txtEmail);

        navName.setText(currentUser.getDisplayName());
        navEmail.setText(currentUser.getEmail());

    }
}
</code>```

LogoutFragment

```<code>import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.guru.R;

public class LogoutFragment extends Fragment {

    private LogoutViewModel logoutViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        logoutViewModel =
                ViewModelProviders.of(this).get(LogoutViewModel.class);
        View root = inflater.inflate(R.layout.fragment_logout, container, false);
        final TextView textView = root.findViewById(R.id.text_logout);

        logoutViewModel.getText().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
}

</code>```

and this is my LogoutViewModel

```<code>package com.example.guru.ui.Logout;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class LogoutViewModel extends ViewModel {

    private MutableLiveData<String> mText;

    public LogoutViewModel() {
        mText = new MutableLiveData<>();
        mText.setValue("logout");
    }

    public LiveData<String> getText() {
        return mText;
    }
}

</code>```

答:
Feels like there should be a built in solution but so far I have solved it like this.
I simply add a click listener on that menu option, in my case my logout button:

In Java -->

```<code>NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.getMenu().findItem(R.id.logout).setOnMenuItemClickListener(menuItem -> {
    logout();
    return true;
});
</code>```

In Kotlin -->

```<code>navView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener({ menuItem ->
                logoutDialog()
                true
            })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to implement the sign out method in my project. i watch all youtube tutorial but seems like the navigation drawer is the update version. and i'm clueless on how to implement those sign out coding into my coding.

the newest version of the navigation drawer already built in with the ui package folder. So i'm not quite sure on how to implement those tutorial code  because most of the tutorial code have this code.
 below is the tutorial code and i don't know on how to implement the sign out method into my home.java code. thank you

 @SuppressWarnings("StatementWithEmptyBody")
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            // Handle navigation view item clicks here.
            int id = item.getItemId();

            if (id == R.id.nav_home) {

                getSupportActionBar().setTitle("Home");
                getSupportFragmentManager().beginTransaction().replace(R.id.container,new HomeFragment()).commit();

            } else if (id == R.id.nav_profile) {

                getSupportActionBar().setTitle("Profile");
                getSupportFragmentManager().beginTransaction().replace(R.id.container,new ProfileFragment()).commit();

            } else if (id == R.id.nav_settings) {

                getSupportActionBar().setTitle("Settings");
                getSupportFragmentManager().beginTransaction().replace(R.id.container,new SettingsFragment()).commit();

            }
            else if (id == R.id.nav_signout) {

                FirebaseAuth.getInstance().signOut();
                Intent loginActivity = new Intent(getApplicationContext(),LoginActivity.class);
                startActivity(loginActivity);
                finish();

            }

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }

this is my home.java code

package com.example.guru;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import androidx.drawerlayout.widget.DrawerLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.Menu;
import android.widget.TextView;

public class Home extends AppCompatActivity {

    FirebaseAuth firebaseAuth;
    FirebaseUser currentUser;
    DatabaseReference databaseReference;

    private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //ini
        firebaseAuth = FirebaseAuth.getInstance();
        currentUser = firebaseAuth.getCurrentUser();
        databaseReference = FirebaseDatabase.getInstance().getReference("Customer");

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = findViewById(R.id.drawer_layout);

        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_profile, R.id.nav_orders,R.id.nav_logout)
                .setDrawerLayout(drawer)
                .build();

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        updateNavHeader();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    public void updateNavHeader() {
        NavigationView navigationView = findViewById(R.id.nav_view);
        View headerView= navigationView.getHeaderView(0);
        TextView navName= headerView.findViewById(R.id.txtName);
        TextView navEmail=headerView.findViewById(R.id.txtEmail);

        navName.setText(currentUser.getDisplayName());
        navEmail.setText(currentUser.getEmail());

    }
}

LogoutFragment

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.guru.R;

public class LogoutFragment extends Fragment {

    private LogoutViewModel logoutViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        logoutViewModel =
                ViewModelProviders.of(this).get(LogoutViewModel.class);
        View root = inflater.inflate(R.layout.fragment_logout, container, false);
        final TextView textView = root.findViewById(R.id.text_logout);

        logoutViewModel.getText().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
}

and this is my LogoutViewModel

package com.example.guru.ui.Logout;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class LogoutViewModel extends ViewModel {

    private MutableLiveData<String> mText;

    public LogoutViewModel() {
        mText = new MutableLiveData<>();
        mText.setValue("logout");
    }

    public LiveData<String> getText() {
        return mText;
    }
}

Body:
Feels like there should be a built in solution but so far I have solved it like this.
I simply add a click listener on that menu option, in my case my logout button:

In Java -->

NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.getMenu().findItem(R.id.logout).setOnMenuItemClickListener(menuItem -> {
    logout();
    return true;
});

In Kotlin -->

navView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener({ menuItem ->
                logoutDialog()
                true
            })


问:
Linux Pipe viewer, how to split the pipe
I'm trying to extract large .tar file using pv.

```<code>pv large_file.tar.gz | tar -xcf /../MyFolder.
</code>```

The pv command works like expected,showing the progress in the console.

I'm trying to split the stdout, to show the progress both in the console and save the same standout, to a file.

I tried doing so with tee, but couldn't make it work.

```<code>pv large_file.tar.gz | tee /tmp/strout.log | tar -xcf /../MyFolder
</code>```

Any suggestions how can i display the progress to the console an in the same time save it to a file?

Thanks!

答:
Not sure that your original command works, as there are several errors in the options given to tar.

Given that ../MyFolder exists, your first command need to be

    pv large_file.tar.gz | tar -xz -C ../MyFolder
```

<p>If you insert tee call between <code>pv</code> and <code>tar</code> calls, then the whole chain works.</p>

<pre class="lang-sh prettyprint-override"><code>    pv large_file.tar.gz | tee /tmp/strout.log | tar -xz -C ../MyFolder
</code>```

However i'm not sure it does what you expect. If you pipe pv output to tee, tee will pipe it to tar, and dump the same contents as the original tar to /tmp/strout.log, resulting in your tar extracted to ../MyFolder and copied to /tmp/strout.log.

EDIT

As suggested by @DownloadPizza, you can use process substitution (see How do I write stderr to a file while using "tee" with a pipe?). By using -f flag with pv, your command will become

    pv -f large_file.tar.gz 2> >(tee /tmp/strout.log) > >(tar -xz -C ../MyFolder)
```

and will produce expected output.

Body:
I'm trying to extract large .tar file using pv.

pv large_file.tar.gz | tar -xcf /../MyFolder.

The pv command works like expected,showing the progress in the console.

I'm trying to split the stdout, to show the progress both in the console and save the same standout, to a file.

I tried doing so with tee, but couldn't make it work.

pv large_file.tar.gz | tee /tmp/strout.log | tar -xcf /../MyFolder

Any suggestions how can i display the progress to the console an in the same time save it to a file?

Thanks!

Body:
Not sure that your original command works, as there are several errors in the options given to tar.

Given that ../MyFolder exists, your first command need to be

    pv large_file.tar.gz | tar -xz -C ../MyFolder

If you insert tee call between pv and tar calls, then the whole chain works.

    pv large_file.tar.gz | tee /tmp/strout.log | tar -xz -C ../MyFolder

However i'm not sure it does what you expect. If you pipe pv output to tee, tee will pipe it to tar, and dump the same contents as the original tar to /tmp/strout.log, resulting in your tar extracted to ../MyFolder and copied to /tmp/strout.log.

EDIT

As suggested by @DownloadPizza, you can use process substitution (see How do I write stderr to a file while using "tee" with a pipe?). By using -f flag with pv, your command will become

    pv -f large_file.tar.gz 2> >(tee /tmp/strout.log) > >(tar -xz -C ../MyFolder)

and will produce expected output.


问:
Error:expected expression before '=' token
I am getting an error as expected expression before '=' token.</p>

```<code>#define RMH_MAX_UNENCODED_LENGTH= (RMH_MESSAGE_MAX_SIZE - RMH_ENCODED_MSG_OVERHEAD); // RMH_MAX_UNENCODED_LENGTH =4064

#define RMH_MAX_ENCODED_LENGTH = (3*sizeof(RMH_MAX_UNENCODED_LENGTH) / 4);//RMH_MAX_ENCODED_LENGTH =4;

int k = RMH_MAX_UNENCODED_LENGTH; //Error:expected expression before '=' token
NSLog(@"f:%d",k);
</code>```

答:
You don't want an "=" or a ";" in those #define statements.  The syntax is...

```<code>#define symbol value
</code>```

It's a good idea to put parentheses as you've done.

This is just plain C, no "Ojbective" stuff here.  You might want to pick up a book on C to learn things like this.

ContentLicense: CC BY-SA 3.0

Body:
I am getting an error as expected expression before '=' token.

#define RMH_MAX_UNENCODED_LENGTH= (RMH_MESSAGE_MAX_SIZE - RMH_ENCODED_MSG_OVERHEAD); // RMH_MAX_UNENCODED_LENGTH =4064

#define RMH_MAX_ENCODED_LENGTH = (3*sizeof(RMH_MAX_UNENCODED_LENGTH) / 4);//RMH_MAX_ENCODED_LENGTH =4;

int k = RMH_MAX_UNENCODED_LENGTH; //Error:expected expression before '=' token
NSLog(@"f:%d",k);

Body:
You don't want an "=" or a ";" in those #define statements.  The syntax is...

#define symbol value

It's a good idea to put parentheses as you've done.

This is just plain C, no "Ojbective" stuff here.  You might want to pick up a book on C to learn things like this.


问:
Adding polylines to map error Failed resolution of: Ljava/time/ZonedDateTime
I am trying to add polylines to a map between the current location and a marker added dynamically to the map. The way it should work it's when the InfoWindow from the marker it's pressed, a dialog asking if you wanna travel to that point opens, and when the "Yes" option is pressed, it should add the polyline to that point.

OnInfoWindowClick :

```<code>public void onInfoWindowClick(final Marker marker1) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Doriți să mergeți la această alertă?")
            .setCancelable(true)
            .setPositiveButton("Da", new DialogInterface.OnClickListener() {
                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    ScoateMarkerRute();
                    markerSelectat=marker1;
                    layout_confirmare.setVisibility(GONE);
                    layout_validare.setVisibility(GONE);
                    calculateDirections(marker1);
                    dialog.dismiss();
                }
            })
            .setNegativeButton("Nu", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}
</code>```

calculateDirections(); :

```<code>private void calculateDirections(Marker marker){
    Log.d(TAG, "calculateDirections: calculating directions.");

    com.google.maps.model.LatLng destinatie = new com.google.maps.model.LatLng(
            marker.getPosition().latitude,
            marker.getPosition().longitude
    );
    DirectionsApiRequest directions = new DirectionsApiRequest(mGeoApiContext);

    directions.alternatives(true);
    directions.origin(
            new com.google.maps.model.LatLng(
                    locatie_user.latitude,
                    locatie_user.longitude
            )
    );
    Log.d(TAG, "calculateDirections: destination: " + destinatie.toString());
    directions.destination(destinatie).setCallback(new PendingResult.Callback<DirectionsResult>() {
        @Override
        public void onResult(DirectionsResult result) {
            Log.d(TAG, "calculateDirections: routes: " + result.routes[0].toString());
            Log.d(TAG, "calculateDirections: duration: " + result.routes[0].legs[0].duration);
            Log.d(TAG, "calculateDirections: distance: " + result.routes[0].legs[0].distance.inMeters);
            Log.d(TAG, "calculateDirections: geocodedWayPoints: " + result.geocodedWaypoints[0].toString());
            addPolylinesToMap(result);
        }

        @Override
        public void onFailure(Throwable e) {
            Log.e(TAG, "calculateDirections: Failed to get directions: " + e.getMessage() );

        }
    });
}
</code>```

addPolylinesToMap :

```<code>private void addPolylinesToMap(final DirectionsResult result){
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "run: result routes: " + result.routes.length);
            if(mPolylinesData.size()>0){
                for(PolylineData polylineData: mPolylinesData){
                    polylineData.getPolyline().remove();
                }
                mPolylinesData.clear();
                mPolylinesData= new ArrayList<>();
            }
            for(DirectionsRoute route: result.routes){
                Log.d(TAG, "run: leg: " + route.legs[0].toString());
                List<com.google.maps.model.LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());

                List<LatLng> newDecodedPath = new ArrayList<>();

                // This loops through all the LatLng coordinates of ONE polyline.
                for(com.google.maps.model.LatLng latLng: decodedPath){
                Log.d(TAG, "run: latlng: " + latLng.toString());

                newDecodedPath.add(new LatLng(
                            latLng.lat,
                            latLng.lng
                    ));
                }
                Polyline polyline = mMap.addPolyline(new PolylineOptions().addAll(newDecodedPath));
                polyline.setColor(ContextCompat.getColor(Harta.this, R.color.scope_systems_gri));
                polyline.setWidth(25);
                polyline.setClickable(true);
                polyline.setTag("A");
                mPolylinesData.add(new PolylineData(polyline, route.legs[0]));
                onPolylineClick(polyline);
                zoomRoute(polyline.getPoints());
                markerSelectat.setVisible(false);
            }
        }
    });
}
</code>```

When I implemented this method of adding polylines, I used a map full of markers and actually worked. When I changed and added only 1 marker, the app kept crashing with the error :

```<code>> > java.lang.NoClassDefFoundError: Failed resolution of: Ljava/time/ZonedDateTime;
>         at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:241)
>         at com.google.maps.internal.OkHttpPendingResult.onResponse(OkHttpPendingResult.java:207)
>         at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
>         at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
>         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
>         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
>         at java.lang.Thread.run(Thread.java:761)
>      Caused by: java.lang.ClassNotFoundException: Didn't find class "java.time.ZonedDateTime" on path: DexPathList[[zip file
> "/data/app/com.example.aplicatieprimarie-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.aplicatieprimarie-2/lib/x86,
> /system/lib, /vendor/lib]]
>         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
>         at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:241)
>         at com.google.maps.internal.OkHttpPendingResult.onResponse(OkHttpPendingResult.java:207)
>         at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
>         at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
>         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
>         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
>         at java.lang.Thread.run(Thread.java:761)
</code>```

EDIT: added build.gradle

I have updated:
-'com.google.android.libraries.places:places-compat:2.1.0' to 'com.google.android.libraries.places:places-compat:2.1.1'
and now after syncing, when I try to run I get the following error:

Caused by: com.android.tools.r8.utils.AbortException: Error: null, Cannot fit requested classes in a single dex file (# methods: 66003 > 65536)

build.gradle(app):

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.aplicatieprimarie"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.facebook.android:facebook-android-sdk:5.9.0'
    implementation "com.google.android.gms:play-services-location:17.0.0"
    implementation 'de.hdodenhof:circleimageview:3.0.1'
    implementation 'com.github.bumptech.glide:glide:4.10.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
    implementation 'com.google.android.gms:play-services-auth:17.0.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment:2.2.1'
    implementation 'androidx.navigation:navigation-ui:2.2.1'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.android.libraries.places:places-compat:2.2.0'
    implementation 'androidx.biometric:biometric:1.0.1'
    implementation 'com.google.maps:google-maps-services:0.10.2'
    implementation 'org.slf4j:slf4j-simple:1.7.25'
}
</code>```

答:
https://developer.android.com/reference/java/time/ZonedDateTime

ZonedDateTime was added at API level 26 (see top right on the image), your minimum is API 16. The error is saying that the class ZonedDateTime cannot be found in the version of Android you are running.

This question recommends some ways to use alternatives: ZonedDateTime to Date before Java 8 in early Android

Caused by: com.android.tools.r8.utils.AbortException: Error: null, Cannot fit requested classes in a single dex file (# methods: 66003 > 65536)

This is saying you have reached the dex file limit. You need to enable multi-dex:

https://developer.android.com/studio/build/multidex

```<code>dependencies {
    def multidex_version = "2.0.1"
    implementation 'androidx.multidex:multidex:$multidex_version'
}
</code>```

Then override your application:

```<code>class MyApplication : MultiDexApplication() {...}
</code>```

(Your app is squashed into files called dex files, each dex file can have a maximum of 65536 declared java methods, if you have more methods than 65536 you need another dex file to contain them.)

Body:
I am trying to add polylines to a map between the current location and a marker added dynamically to the map. The way it should work it's when the InfoWindow from the marker it's pressed, a dialog asking if you wanna travel to that point opens, and when the "Yes" option is pressed, it should add the polyline to that point.

OnInfoWindowClick :

public void onInfoWindowClick(final Marker marker1) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Doriți să mergeți la această alertă?")
            .setCancelable(true)
            .setPositiveButton("Da", new DialogInterface.OnClickListener() {
                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    ScoateMarkerRute();
                    markerSelectat=marker1;
                    layout_confirmare.setVisibility(GONE);
                    layout_validare.setVisibility(GONE);
                    calculateDirections(marker1);
                    dialog.dismiss();
                }
            })
            .setNegativeButton("Nu", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

calculateDirections(); :

private void calculateDirections(Marker marker){
    Log.d(TAG, "calculateDirections: calculating directions.");

    com.google.maps.model.LatLng destinatie = new com.google.maps.model.LatLng(
            marker.getPosition().latitude,
            marker.getPosition().longitude
    );
    DirectionsApiRequest directions = new DirectionsApiRequest(mGeoApiContext);

    directions.alternatives(true);
    directions.origin(
            new com.google.maps.model.LatLng(
                    locatie_user.latitude,
                    locatie_user.longitude
            )
    );
    Log.d(TAG, "calculateDirections: destination: " + destinatie.toString());
    directions.destination(destinatie).setCallback(new PendingResult.Callback<DirectionsResult>() {
        @Override
        public void onResult(DirectionsResult result) {
            Log.d(TAG, "calculateDirections: routes: " + result.routes[0].toString());
            Log.d(TAG, "calculateDirections: duration: " + result.routes[0].legs[0].duration);
            Log.d(TAG, "calculateDirections: distance: " + result.routes[0].legs[0].distance.inMeters);
            Log.d(TAG, "calculateDirections: geocodedWayPoints: " + result.geocodedWaypoints[0].toString());
            addPolylinesToMap(result);
        }

        @Override
        public void onFailure(Throwable e) {
            Log.e(TAG, "calculateDirections: Failed to get directions: " + e.getMessage() );

        }
    });
}

addPolylinesToMap :

private void addPolylinesToMap(final DirectionsResult result){
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "run: result routes: " + result.routes.length);
            if(mPolylinesData.size()>0){
                for(PolylineData polylineData: mPolylinesData){
                    polylineData.getPolyline().remove();
                }
                mPolylinesData.clear();
                mPolylinesData= new ArrayList<>();
            }
            for(DirectionsRoute route: result.routes){
                Log.d(TAG, "run: leg: " + route.legs[0].toString());
                List<com.google.maps.model.LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());

                List<LatLng> newDecodedPath = new ArrayList<>();

                // This loops through all the LatLng coordinates of ONE polyline.
                for(com.google.maps.model.LatLng latLng: decodedPath){
                Log.d(TAG, "run: latlng: " + latLng.toString());

                newDecodedPath.add(new LatLng(
                            latLng.lat,
                            latLng.lng
                    ));
                }
                Polyline polyline = mMap.addPolyline(new PolylineOptions().addAll(newDecodedPath));
                polyline.setColor(ContextCompat.getColor(Harta.this, R.color.scope_systems_gri));
                polyline.setWidth(25);
                polyline.setClickable(true);
                polyline.setTag("A");
                mPolylinesData.add(new PolylineData(polyline, route.legs[0]));
                onPolylineClick(polyline);
                zoomRoute(polyline.getPoints());
                markerSelectat.setVisible(false);
            }
        }
    });
}

When I implemented this method of adding polylines, I used a map full of markers and actually worked. When I changed and added only 1 marker, the app kept crashing with the error :

> > java.lang.NoClassDefFoundError: Failed resolution of: Ljava/time/ZonedDateTime;
>         at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:241)
>         at com.google.maps.internal.OkHttpPendingResult.onResponse(OkHttpPendingResult.java:207)
>         at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
>         at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
>         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
>         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
>         at java.lang.Thread.run(Thread.java:761)
>      Caused by: java.lang.ClassNotFoundException: Didn't find class "java.time.ZonedDateTime" on path: DexPathList[[zip file
> "/data/app/com.example.aplicatieprimarie-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.aplicatieprimarie-2/lib/x86,
> /system/lib, /vendor/lib]]
>         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
>         at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:241)
>         at com.google.maps.internal.OkHttpPendingResult.onResponse(OkHttpPendingResult.java:207)
>         at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
>         at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
>         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
>         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
>         at java.lang.Thread.run(Thread.java:761)

EDIT: added build.gradle

I have updated:
-'com.google.android.libraries.places:places-compat:2.1.0' to 'com.google.android.libraries.places:places-compat:2.1.1'
and now after syncing, when I try to run I get the following error:

Caused by: com.android.tools.r8.utils.AbortException: Error: null, Cannot fit requested classes in a single dex file (# methods: 66003 > 65536)

build.gradle(app):

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.aplicatieprimarie"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.facebook.android:facebook-android-sdk:5.9.0'
    implementation "com.google.android.gms:play-services-location:17.0.0"
    implementation 'de.hdodenhof:circleimageview:3.0.1'
    implementation 'com.github.bumptech.glide:glide:4.10.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
    implementation 'com.google.android.gms:play-services-auth:17.0.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment:2.2.1'
    implementation 'androidx.navigation:navigation-ui:2.2.1'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.android.libraries.places:places-compat:2.2.0'
    implementation 'androidx.biometric:biometric:1.0.1'
    implementation 'com.google.maps:google-maps-services:0.10.2'
    implementation 'org.slf4j:slf4j-simple:1.7.25'
}

Body:
https://developer.android.com/reference/java/time/ZonedDateTime

ZonedDateTime was added at API level 26 (see top right on the image), your minimum is API 16. The error is saying that the class ZonedDateTime cannot be found in the version of Android you are running.

This question recommends some ways to use alternatives: ZonedDateTime to Date before Java 8 in early Android

Caused by: com.android.tools.r8.utils.AbortException: Error: null, Cannot fit requested classes in a single dex file (# methods: 66003 > 65536)

This is saying you have reached the dex file limit. You need to enable multi-dex:

https://developer.android.com/studio/build/multidex

dependencies {
    def multidex_version = "2.0.1"
    implementation 'androidx.multidex:multidex:$multidex_version'
}

Then override your application:

class MyApplication : MultiDexApplication() {...}

(Your app is squashed into files called dex files, each dex file can have a maximum of 65536 declared java methods, if you have more methods than 65536 you need another dex file to contain them.)


问:
How to replace NAs with values from another column in data.table (Example given)?
DT is data.table and I want to replace NAs with values from visits column and Expected_DT is desired DT.

```<code>DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(NA,45,56,78),visits=c(14,45,56,78))

name hour count visits
1:    x    1    NA     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78
</code>```

This is what I want

```<code>Expected_DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(14,45,56,78),visits=c(14,45,56,78))

   name hour count visits
1:    x    1    14     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78
</code>```

答:
Some base R solutions

using ifelse

```<code>DT <- within(DT, count <- ifelse(is.na(count),visits,count))
</code>```

using rowSums

```<code>DT <- within(DT, count <- rowSums(cbind(is.na(count)*visits,count),na.rm = TRUE))
</code>```

Body:
DT is data.table and I want to replace NAs with values from visits column and Expected_DT is desired DT.

DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(NA,45,56,78),visits=c(14,45,56,78))

name hour count visits
1:    x    1    NA     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78

This is what I want

Expected_DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(14,45,56,78),visits=c(14,45,56,78))

   name hour count visits
1:    x    1    14     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78

Body:
Some base R solutions

using ifelse

DT <- within(DT, count <- ifelse(is.na(count),visits,count))

using rowSums

DT <- within(DT, count <- rowSums(cbind(is.na(count)*visits,count),na.rm = TRUE))


问:
C++ How is release-and-acquire achieved on x86 only using MOV?
This question is a follow-up/clarification to this:

Does the MOV x86 instruction implement a C++11 memory_order_release atomic store?

This states the MOV assembly instruction is sufficient to perform acquire-release semantics on x86. We do not need LOCK, fences or xchg etc. However, I am struggling to understand how this works.

Intel doc Vol 3A Chapter 8 states:

https://software.intel.com/sites/default/files/managed/7c/f1/253668-sdm-vol-3a.pdf

In a single-processor (core) system....

Reads are not reordered with other reads.

Writes are not reordered with older reads.

Writes to memory are not reordered with other writes, with the following exceptions:

but this is for a single core. The multi-core section does not seem to mention how loads are enforced:

In a multiple-processor system, the following ordering principles apply:

Individual processors use the same ordering principles as in a single-processor system.

Writes by a single processor are observed in the same order by all processors.

Writes from an individual processor are NOT ordered with respect to the writes from other processors.

Memory ordering obeys causality (memory ordering respects transitive visibility).

Any two stores are seen in a consistent order by processors other than those performing the stores

Locked instructions have a total order.

So how can MOV alone can facilitate acquire-release?

答:
but this is for a single core.   The multi-core section does not seem to mention how loads are enforced:

The first bullet point in that section is key: Individual processors use the same ordering principles as in a single-processor system.  The implicit part of that statement is ... when loading/storing from cache-coherent shared memory.  i.e. multi-processor systems don't introduce new ways for reordering, they just mean the possible observers now include code on other cores instead of just DMA / IO devices.

The model for reordering of access to shared memory is the single-core model, i.e. program order + a store buffer = basically acq_rel.  Actually slightly stronger than acq_rel, which is fine.

The only reordering that happens is local, within each CPU core.  Once a store becomes globally visible, it becomes visible to all other cores at the same time, and didn't become visible to any cores before that.  (Except to the core doing the store, via store forwarding.)  That's why only local barriers are sufficient to recover sequential consistency on top of a SC + store-buffer model.  (For x86, just mo_seq_cst just needs mfence after SC stores, to drain the store buffer before any further loads can execute.
mfence and locked instructions (which are also full barriers) don't have to bother other cores, just make this one wait).

One key point to understand is that there is a coherent shared view of memory (through coherent caches) that all processors share.  The very top of chapter 8 of Intel's SDM defines some of this background:

These multiprocessing mechanisms have the following characteristics:

To maintain system memory coherency — When two or more processors are attempting simultaneously to
access the same address in system memory, some communication mechanism or memory access protocol
must be available to promote data coherency and, in some instances, to allow one processor to temporarily lock
a memory location.

To maintain cache consistency — When one processor accesses data cached on another processor, it must not
receive incorrect data. If it modifies data, all other processors that access that data must receive the modified
data.

To allow predictable ordering of writes to memory — In some circumstances, it is important that memory writes
be observed externally in precisely the same order as programmed.

[...]

The caching mechanism and cache consistency of Intel 64 and IA-32 processors are discussed in Chapter 11.

(CPUs use some variant of MESI; Intel in practice uses MESIF, AMD in practice uses MOESI.)

The same chapter also includes some litmus tests that help illustrate / define the memory model.  The parts you quoted aren't really a strictly formal definition of the memory model.  But the section 8.2.3.2 Neither Loads Nor Stores Are Reordered with Like Operations shows that loads aren't reordered with loads.  Another section also shows that LoadStore reordering is forbidden.  Acq_rel is basically blocking all reordering except StoreLoad, and that's what x86 does.  (https://preshing.com/20120913/acquire-and-release-semantics/ and https://preshing.com/20120930/weak-vs-strong-memory-models/)

Related:

how are barriers/fences and acquire, release semantics implemented microarchitecturally?

x86 mfence and C++ memory barrier - asking why no barriers are needed for acq_rel, but coming at it from a different angle (wondering about how data ever becomes visible to other cores).

How do memory_order_seq_cst and memory_order_acq_rel differ? (seq_cst requires flushing the store buffer).

C11 Atomic Acquire/Release and x86_64 lack of load/store coherence?

Globally Invisible load instructions program-order + store buffer isn't exactly the same as acq_rel, especially once you consider a load that only partially overlaps a recent store.

x86-TSO: A Rigorous and Usable Programmer’s Model for x86 Multiprocessors  - a formal memory model for x86.

Other ISAs

In general, most weaker memory HW models also only allow local reordering so barriers are still only local within a CPU core, just making (some part of) that core wait until some condition.  (e.g. x86 mfence blocks later loads and stores from executing until the store buffer drains.  Other ISAs also benefit from light-weight barriers for efficiency for stuff that x86 enforces between every memory operation, e.g. blocking LoadLoad and LoadStore reordering.  https://preshing.com/20120930/weak-vs-strong-memory-models/)

A few ISAs (only PowerPC these days) allow stores to become visible to some other cores before becoming visible to all, allowing IRIW reordering.  Note that mo_acq_rel in C++ allows IRIW reordering; only seq_cst forbids it.  Most HW memory models are slightly stronger than ISO C++ and make it impossible, so all cores agree on the global order of stores.


问:
Flutter Google Sign In - This App isn't verified error
I'm getting a 'This app isn't verified' error when I use the Flutter google_sign_in plug in. I want to get authorisation to Google Drive so added it to the google sign-in scope:

```<code>scopes: ['email', 'https://www.googleapis.com/auth/drive'],
</code>```

And it is the request for the drive scope that is causing the error screen to come up ( I tested it with just email and works fine).
If I look at the docs it seems that Google are saying I have to verify the app, however this is a test app to see if I can get the functionality that a client has requested working with Google Drive and won't ever be promoted.
Does anyone know how I can remove this error message for test purposes only?

Many thanks

Here's the actual screen with the error:

答:
The above warning shows when the app isn't verified. Google consents user that the app is not verifed yet and you are sharing sensitive data to it.

We can proceed and complete our flow by clicking the Advanced at bottom left. Once app is verfied this warning will be removed automatically.

Anyone can follow instruction listed on here

https://support.google.com/cloud/answer/7454865?hl=en

Body:
I'm getting a 'This app isn't verified' error when I use the Flutter google_sign_in plug in. I want to get authorisation to Google Drive so added it to the google sign-in scope:

scopes: ['email', 'https://www.googleapis.com/auth/drive'],

And it is the request for the drive scope that is causing the error screen to come up ( I tested it with just email and works fine).
If I look at the docs it seems that Google are saying I have to verify the app, however this is a test app to see if I can get the functionality that a client has requested working with Google Drive and won't ever be promoted.
Does anyone know how I can remove this error message for test purposes only?

Many thanks

Here's the actual screen with the error:


问:
Advanced options concatenation in buildroot package .mk file
I'm creating a buildroot package for xmms2 which uses waf build system.
For the configuration step I need to pass the parameters based on the config selection. Actually it's one parameter which has comma separated values. It should look like this:

```<code>--with-optionals medialib-updater,s4
</code>```

I don't see the way to generate that value. Here is what tried:

```<code>################################################################################
#
# xmms2
#
################################################################################

XMMS2_VERSION = c081011ddc280908678709d1e80f7ec57efa7b82
XMMS2_SITE = https://github.com/Gamadril/xmms2-devel
XMMS2_SITE_METHOD = git
XMMS2_GIT_SUBMODULES = YES

XMMS2_LICENSE = LGPL-2.1
XMMS2_LICENSE_FILES = COPYING

XMMS2_INSTALL_STAGING = YES

XMMS2_CONF_OPTS = --with-optionals medialib-updater

ifeq ($(BR2_PACKAGE_XMMS2_DB_S4),y)
XMMS2_CONF_OPTS += ,s4
endif

$(eval $(waf-package))
</code>```

The result is: --with-optionals medialib-updater ,s4 - with a space between.
How to get rid of that space? So actually how to concatenate some strings with a separator?

答:
In make, the += operator always adds a space. You can append without space by using expansion:

```<code>XMMS2_CONF_OPTS := "$(XMMS2_CONF_OPTS),s4"
</code>```

Body:
I'm creating a buildroot package for xmms2 which uses waf build system.
For the configuration step I need to pass the parameters based on the config selection. Actually it's one parameter which has comma separated values. It should look like this:

--with-optionals medialib-updater,s4

I don't see the way to generate that value. Here is what tried:

################################################################################
#
# xmms2
#
################################################################################

XMMS2_VERSION = c081011ddc280908678709d1e80f7ec57efa7b82
XMMS2_SITE = https://github.com/Gamadril/xmms2-devel
XMMS2_SITE_METHOD = git
XMMS2_GIT_SUBMODULES = YES

XMMS2_LICENSE = LGPL-2.1
XMMS2_LICENSE_FILES = COPYING

XMMS2_INSTALL_STAGING = YES

XMMS2_CONF_OPTS = --with-optionals medialib-updater

ifeq ($(BR2_PACKAGE_XMMS2_DB_S4),y)
XMMS2_CONF_OPTS += ,s4
endif

$(eval $(waf-package))

The result is: --with-optionals medialib-updater ,s4 - with a space between.
How to get rid of that space? So actually how to concatenate some strings with a separator?

Body:
In make, the += operator always adds a space. You can append without space by using expansion:

XMMS2_CONF_OPTS := "$(XMMS2_CONF_OPTS),s4"


问:
Pythonic way to iterate through the input which can be a string, list or dict
I'm new to programming and have a requirement wherein I have to iterate through the elements of an input. The input can be a string, a list (mostly) or a dict. I wrote some code to check if the given input is a string or a list or a dict etc., but I'm wondering if there is an easier way to do it.

For example, I check as follows:

```<code> if isinstance(vlan, list):
      for i in  vlan:
          <<do some operation here>>
 if isinstance(vlan, string):
      <<do some operation here>>
 if isinstance(vlan, dict):
      for i in vlan.keys()
         <<do some operation here>>
</code>```

This operation I have to carry out a lot of times (although I can write a function do expand and send the elements I'm just wondering if there is any alternate to it).

答:
Given this:

This operation i have to carry out a lot of times

I take it that your question is about how to avoid repeating this code pattern in multiple functions. The answer more or less depends on concrete use cases - and specially if the "do_some_operation_here" is the same for all three types or not.

In the first case, a simple generic wrapper around map(func, iterable) is the obvious simple solution:

```<code>def mapply(func, iterable):
    # first weed out the special case
    if isinstance(iterable, str):
       iterable = [iterable]
    return map(func, iterable)
</code>```

But I assume your use case is a bit more complicated with slight type-specific variations in the "do_some_op" part. In this case, the template method pattern might be a good fit:

```<code>import abc

class BaseMapper(metaclass=abc.ABCMeta):
    def apply(self, obj):
        if instance(obj, list):
            return self._apply_list(obj)
        if isinstance(obj, str)
            return self._apply_str(obj)
        if isinstance(obj, dict):
            return self._apply_dict(obj)

     @abc.abstractmethod
     def _apply_list(self, obj):
         # handle a list
     @abc.abstractmethod
     def _apply_dict(self, obj):
         # handle a dict

     @abc.abstractmethod
     def _apply_str(self, obj):
         # handle a str
</code>```

Then you just have to subclass this and implement the abstract methods.

Body:
I'm new to programming and have a requirement wherein I have to iterate through the elements of an input. The input can be a string, a list (mostly) or a dict. I wrote some code to check if the given input is a string or a list or a dict etc., but I'm wondering if there is an easier way to do it.

For example, I check as follows:

 if isinstance(vlan, list):
      for i in  vlan:
          <<do some operation here>>
 if isinstance(vlan, string):
      <<do some operation here>>
 if isinstance(vlan, dict):
      for i in vlan.keys()
         <<do some operation here>>

This operation I have to carry out a lot of times (although I can write a function do expand and send the elements I'm just wondering if there is any alternate to it).

Body:
Given this:

This operation i have to carry out a lot of times

I take it that your question is about how to avoid repeating this code pattern in multiple functions. The answer more or less depends on concrete use cases - and specially if the "do_some_operation_here" is the same for all three types or not.

In the first case, a simple generic wrapper around map(func, iterable) is the obvious simple solution:

def mapply(func, iterable):
    # first weed out the special case
    if isinstance(iterable, str):
       iterable = [iterable]
    return map(func, iterable)

But I assume your use case is a bit more complicated with slight type-specific variations in the "do_some_op" part. In this case, the template method pattern might be a good fit:

import abc

class BaseMapper(metaclass=abc.ABCMeta):
    def apply(self, obj):
        if instance(obj, list):
            return self._apply_list(obj)
        if isinstance(obj, str)
            return self._apply_str(obj)
        if isinstance(obj, dict):
            return self._apply_dict(obj)

     @abc.abstractmethod
     def _apply_list(self, obj):
         # handle a list
     @abc.abstractmethod
     def _apply_dict(self, obj):
         # handle a dict

     @abc.abstractmethod
     def _apply_str(self, obj):
         # handle a str

Then you just have to subclass this and implement the abstract methods.


问:
Generating random numbers from a list while adding/removing terms
I'm writing a program where I have a "group" of 6 people trying to guess a number between 1 and 6. If the first person gets it right then 1 is added to their score, but if not the second person takes a guess. If they are right then 1 is added to their score and so on. However, the second person cannot guess the same number as the first person - this is the problem I've been having trouble with. For some reason I'm getting

TypeError: object of type 'NoneType' has no len()

I thought NoneType was some kind of variable thing but I'm not really sure. I'm not using the function len either. The code is below.

```<code>a = [1, 2, 3, 4, 5, 6]
judge = random.choice(a)
p1guess = random.choice(a)
a = a.remove(p1guess)
p2guess = random.choice(a)
a = a.remove(p2guess)
p3guess = random.choice(a)
a = a.remove(p3guess)
p4guess = random.choice(a)
a = a.remove(p4guess)
p5guess = random.choice(a)
a = a.remove(p5guess)
p6guess = random.choice(a)
</code>```

答:
remove returns none and does the removal in place, don't reassign it back to a.

```<code>...
p1guess = random.choice(a)
a.remove(p1guess)
p2guess = random.choice(a)
...
</code>```

Otherwise, you can just shuffle a and assign them all at once,

```<code>a = [1, 2, 3, 4, 5, 6]
random.shuffle(a)
judge = random.choice(a)

p1guess, p2guess, p3guess, p4guess, p5guess, p6guess = a
</code>```

Body:
I'm writing a program where I have a "group" of 6 people trying to guess a number between 1 and 6. If the first person gets it right then 1 is added to their score, but if not the second person takes a guess. If they are right then 1 is added to their score and so on. However, the second person cannot guess the same number as the first person - this is the problem I've been having trouble with. For some reason I'm getting

TypeError: object of type 'NoneType' has no len()

I thought NoneType was some kind of variable thing but I'm not really sure. I'm not using the function len either. The code is below.

a = [1, 2, 3, 4, 5, 6]
judge = random.choice(a)
p1guess = random.choice(a)
a = a.remove(p1guess)
p2guess = random.choice(a)
a = a.remove(p2guess)
p3guess = random.choice(a)
a = a.remove(p3guess)
p4guess = random.choice(a)
a = a.remove(p4guess)
p5guess = random.choice(a)
a = a.remove(p5guess)
p6guess = random.choice(a)

Body:
remove returns none and does the removal in place, don't reassign it back to a.

...
p1guess = random.choice(a)
a.remove(p1guess)
p2guess = random.choice(a)
...

Otherwise, you can just shuffle a and assign them all at once,

a = [1, 2, 3, 4, 5, 6]
random.shuffle(a)
judge = random.choice(a)

p1guess, p2guess, p3guess, p4guess, p5guess, p6guess = a


问:
Log parsing using RegEx
I want to parse the following logs in particular classes.

```<code>2019-11-14T04:24:04.072Z  INFO MessagingObjectFactoryImpl-4-2 ExporterLastAckServiceImpl - - [nsx@6876 comp="nsx-manager" level="INFO" subcomp="manager"] Found exporter with elaId = Node#a3844284-e626-11e9-a87b-005056bcc0c6#AggSvc-L2-Bridging, returning lastAck = 16507
2019-11-14T04:23:08.362Z  INFO ActivityEventRecovery-1 ActivityCacheManager - - [nsx@6876 comp="nsx-manager" level="INFO" subcomp="manager"] Handling activity 92d6a146-fa12-4889-a0ff-441087e047d0 completion event for 1
2019-11-14T04:23:08.362Z  DEBUG ActivityEventRecovery-1 ActivityCacheManager - - [nsx@6876 comp="nsx-manager" level="INFO" subcomp="manager"] Handling activity 92d6a146-fa12-4889-a0ff-441087e047d0 completion event for 1
</code>```

I tried

```<code>(?<timestamp>\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ)\s+(?<level>INFO|WARN|DEBUG|ERROR|FATAL|TRACE)\s+(?<text>.*?\s.*?)\-\s+\-\s\[(?<class>.*?)\]\s+(?<Message>.*? |\Z)
</code>```

I am getting everything with this except Message class.
How should I write Message class Regex?

Here's the link https://regex101.com/r/LJnVrS/86

答:
.*? will match as few characters as possible, until you get to a space. Because it looks like the matches all end at the end of a line, instead, just continue matching whatever you can until you get to the end of the line. Remove the s flag, and use:

```<code>(?<Message>.*)
</code>```

(no need for \Z)

https://regex101.com/r/LJnVrS/87

Title: Log parsing using RegEx

Body:
I want to parse the following logs in particular classes.

2019-11-14T04:24:04.072Z  INFO MessagingObjectFactoryImpl-4-2 ExporterLastAckServiceImpl - - [nsx@6876 comp="nsx-manager" level="INFO" subcomp="manager"] Found exporter with elaId = Node#a3844284-e626-11e9-a87b-005056bcc0c6#AggSvc-L2-Bridging, returning lastAck = 16507
2019-11-14T04:23:08.362Z  INFO ActivityEventRecovery-1 ActivityCacheManager - - [nsx@6876 comp="nsx-manager" level="INFO" subcomp="manager"] Handling activity 92d6a146-fa12-4889-a0ff-441087e047d0 completion event for 1
2019-11-14T04:23:08.362Z  DEBUG ActivityEventRecovery-1 ActivityCacheManager - - [nsx@6876 comp="nsx-manager" level="INFO" subcomp="manager"] Handling activity 92d6a146-fa12-4889-a0ff-441087e047d0 completion event for 1

I tried

(?<timestamp>\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ)\s+(?<level>INFO|WARN|DEBUG|ERROR|FATAL|TRACE)\s+(?<text>.*?\s.*?)\-\s+\-\s\[(?<class>.*?)\]\s+(?<Message>.*? |\Z)

I am getting everything with this except Message class.
How should I write Message class Regex?

Here's the link https://regex101.com/r/LJnVrS/86

Body:
.*? will match as few characters as possible, until you get to a space. Because it looks like the matches all end at the end of a line, instead, just continue matching whatever you can until you get to the end of the line. Remove the s flag, and use:

(?<Message>.*)

(no need for \Z)

https://regex101.com/r/LJnVrS/87


问:
How can I use formdata in upload file on vuetify?
I try like this : https://codepen.io/positivethinking639/pen/OJVRjGL?editors=1010

My code :

```<code><v-form>
  <v-file-input multiple
                v-model="documents"
                label="File input"></v-file-input>
  <v-btn color="success" @click="submit()">
    test
  </v-btn>
</v-form>
</code>```

but it does not works

if I upload file and click button test, the formdata empty on the console

How can I solve this problem?

答:
You can't print formData directly on the console.

Try this.

```<code>// Display the key/value pairs
for (var pair of formData.entries()) {
    console.log(pair[0]+ ', ' + pair[1]);
}
</code>```

Codepen - https://codepen.io/positivethinking639/pen/OJVRjGL?editors=1010

Body:
I try like this : https://codepen.io/positivethinking639/pen/OJVRjGL?editors=1010

My code :

<v-form>
  <v-file-input multiple
                v-model="documents"
                label="File input"></v-file-input>
  <v-btn color="success" @click="submit()">
    test
  </v-btn>
</v-form>

but it does not works

if I upload file and click button test, the formdata empty on the console

How can I solve this problem?

Body:
You can't print formData directly on the console.

Try this.

// Display the key/value pairs
for (var pair of formData.entries()) {
    console.log(pair[0]+ ', ' + pair[1]);
}

Codepen - https://codepen.io/positivethinking639/pen/OJVRjGL?editors=1010


问:
Show alert icon in the field in Odoo?
I wanted to show an alert icon in partner_id(Customer) field if the Tax ID of partner_id is empty. This icon should be similar to the icon we see in Invoice Date if a future date is given.

Conditions when  icon should be shown

if partner_id's type is individual and has parent_id(Company) then Tax ID should be chosen from parent_id not from parntner_id. So, if the Tax ID of parent_id is empty, the alert icon should be shown.

if partner_id is individual and has no parent_id(company) then Tax ID should be chosen from partner_id. And if it is empty, an alert icon should be shown.

if partner_id is company type and has no Tax ID, an icon should be shown.

How can I achieve such feature?

答:
You can add an onchange method, if you change the partner the icon is displayed
but if you want like the date icon it's a bit long because it's a widget

good for the method it's like this

```<code>class AccountInvoice(models.Model):
    _inherit = 'account.invoice'

    @api.onchange('partner_id')
    def tax_check(self):
        if self.partner_id.parent_id and self.partner_id.company_type == 'person':
            if not self.partner_id.parent_id.vat :
              #  display your icon
            else:
               # chose the tax for parent_id
        elif not self.partner_id.parent_id and self.partner_id.company_type == 'person':
            if self.partner_id.vat :
                # chose the tax in partner_id
            else:
                #  afficher votre icone
        elif not self.partner_id.vat and self.partner_id.company_type == 'company':
            #  display your icon
</code>```

you want to display the TaxID in the report ?

Title: Show alert icon in the field in Odoo?

Body:
You can add an onchange method, if you change the partner the icon is displayed
but if you want like the date icon it's a bit long because it's a widget

good for the method it's like this

class AccountInvoice(models.Model):
    _inherit = 'account.invoice'

    @api.onchange('partner_id')
    def tax_check(self):
        if self.partner_id.parent_id and self.partner_id.company_type == 'person':
            if not self.partner_id.parent_id.vat :
              #  display your icon
            else:
               # chose the tax for parent_id
        elif not self.partner_id.parent_id and self.partner_id.company_type == 'person':
            if self.partner_id.vat :
                # chose the tax in partner_id
            else:
                #  afficher votre icone
        elif not self.partner_id.vat and self.partner_id.company_type == 'company':
            #  display your icon

you want to display the TaxID in the report ?


问:
GCP, despite existing forwarding rule no external IP on IIS
I have a virutal windows server machine running on GCP.

On that machine I have an IIS with several web sites.

Untill recent windows update and restart in Site Binding I was able to see the external IP from the forwarding rule, like this:

Example from another, working server

But now the external IP is not listed, despite the forwarding rule exists:

The real state of the server in question

And because of this my sites are not working.

I've tried to deleting and creating forwarding rules via GCP Shell using gcloud compute forwarding-rules delete ... and gcloud compute forwarding-rules create ... to no avail.

With and without restarts after executing each of these commands or ageter both in a row.

Thank you for any help.

答:
The problem was resolved with GCP support.
There's a service GCEAgent (Google Compute Engine Agent).
It was stopped despite its startup type is automatic.
Starting the service brought all forwarded IP addresses back to IIS site binding window.</p>


问:
Postgres query nested JSONB
I have a JSONB column containing list of objects.>

Here's the table schema:

```<code>column Name | Datatype
---------------------
timestamp   | timestamp
  data      | JSONB
</code>```

Sample Data

1.

```<code>timestamp : 2020-02-02 19:01:21.571429+00
</code>```

```<code>data : [
  {
    "tracker_id": "5",
    "position": 1
  },
  {
    "tracker_id": "11",
    "position": 2
  },
  {
    "tracker_id": "4",
    "position": 1
  }
]
</code>```

2.

```<code>timestamp : 2020-02-02 19:01:23.571429+00
</code>```

```<code>data : [
  {
    "tracker_id": "7",
    "position": 3
  },
  {
    "tracker_id": "4",
    "position": 2
  }
]
</code>```

3.

```<code>timestamp : 2020-02-02 19:02:23.571429+00
</code>```

```<code>data : [
  {
    "tracker_id": "5",
    "position": 2
  },
  {
    "tracker_id": "4",
    "position": 1
  }
]
</code>```

I need to find the count of the transitions of tracker_id from position: 1 to position: 2

Here, the output will be 2, since tracker_id 4 and 5 changed their position from 1 to 2.

Note

The transition should be in ascending order depending on the timestamp

The position change need not to be in the consecutive records.

I'm using timescaledb extension

So far I've tried querying the objects in the list od individual record, but I'm not sure how to merge the list objects of each record and query them.

What would be the query for this? Should I write down a stored procedure instead?

答:
I don't use timescaledb extension so I would choose pure SQL solution based on unnesting json:</p>

```<code>with t (timestamp,data) as (values
  (timestamp '2020-02-02 19:01:21.571429+00', '[
  {
    "tracker_id": "5",
    "position": 1
  },
  {
    "tracker_id": "11",
    "position": 2
  },
  {
    "tracker_id": "4",
    "position": 1
  }
]'::jsonb),
  (timestamp '2020-02-02 19:01:23.571429+00', '[
  {
    "tracker_id": "7",
    "position": 3
  },
  {
    "tracker_id": "4",
    "position": 2
  }
]
'::jsonb),
  (timestamp '2020-02-02 19:02:23.571429+00', '[
  {
    "tracker_id": "5",
    "position": 2
  },
  {
    "tracker_id": "4",
    "position": 1
  }
]
'::jsonb)
), unnested as (
  select t.timestamp, r.tracker_id, r.position
  from t
  cross join lateral jsonb_to_recordset(t.data) AS r(tracker_id text, position int)
)
select count(*)
from unnested u1
join unnested u2
  on u1.tracker_id = u2.tracker_id
 and u1.position = 1
 and u2.position = 2
 and u1.timestamp < u2.timestamp;
</code>```

Title: Postgres query nested JSONB

Body:
I have a JSONB column containing list of objects.>

Here's the table schema:

column Name | Datatype
---------------------
timestamp   | timestamp
  data      | JSONB

Sample Data

1.

timestamp : 2020-02-02 19:01:21.571429+00

data : [
  {
    "tracker_id": "5",
    "position": 1
  },
  {
    "tracker_id": "11",
    "position": 2
  },
  {
    "tracker_id": "4",
    "position": 1
  }
]

2.

timestamp : 2020-02-02 19:01:23.571429+00

data : [
  {
    "tracker_id": "7",
    "position": 3
  },
  {
    "tracker_id": "4",
    "position": 2
  }
]

3.

timestamp : 2020-02-02 19:02:23.571429+00

data : [
  {
    "tracker_id": "5",
    "position": 2
  },
  {
    "tracker_id": "4",
    "position": 1
  }
]

I need to find the count of the transitions of tracker_id from position: 1 to position: 2

Here, the output will be 2, since tracker_id 4 and 5 changed their position from 1 to 2.

Note

The transition should be in ascending order depending on the timestamp

The position change need not to be in the consecutive records.

I'm using timescaledb extension

So far I've tried querying the objects in the list od individual record, but I'm not sure how to merge the list objects of each record and query them.

What would be the query for this? Should I write down a stored procedure instead?

Body:
I don't use timescaledb extension so I would choose pure SQL solution based on unnesting json:

with t (timestamp,data) as (values
  (timestamp '2020-02-02 19:01:21.571429+00', '[
  {
    "tracker_id": "5",
    "position": 1
  },
  {
    "tracker_id": "11",
    "position": 2
  },
  {
    "tracker_id": "4",
    "position": 1
  }
]'::jsonb),
  (timestamp '2020-02-02 19:01:23.571429+00', '[
  {
    "tracker_id": "7",
    "position": 3
  },
  {
    "tracker_id": "4",
    "position": 2
  }
]
'::jsonb),
  (timestamp '2020-02-02 19:02:23.571429+00', '[
  {
    "tracker_id": "5",
    "position": 2
  },
  {
    "tracker_id": "4",
    "position": 1
  }
]
'::jsonb)
), unnested as (
  select t.timestamp, r.tracker_id, r.position
  from t
  cross join lateral jsonb_to_recordset(t.data) AS r(tracker_id text, position int)
)
select count(*)
from unnested u1
join unnested u2
  on u1.tracker_id = u2.tracker_id
 and u1.position = 1
 and u2.position = 2
 and u1.timestamp < u2.timestamp;