答:
This implementation will do the text and context switching you desire.</p>

```<code>function action(mouseevent) {
  const button = mouseevent.target;
  let element = document.getElementById('form');
  if(element.firstChild) {
    while (element.firstChild) {
      element.removeChild(element.firstChild);
    }
    button.innerHTML = 'Add form';
    button.classList.remove('btn-danger');
    button.classList.add('btn-success');
  } else {
    document.getElementById('form').innerHTML = inner_form;
    button.innerHTML = 'Delete Form';
    button.classList.add('btn-danger');
    button.classList.remove('btn-success');
  }
}
</code>```

Title: Reuse function to delete an item

Body:
This implementation will do the text and context switching you desire.

function action(mouseevent) {
  const button = mouseevent.target;
  let element = document.getElementById('form');
  if(element.firstChild) {
    while (element.firstChild) {
      element.removeChild(element.firstChild);
    }
    button.innerHTML = 'Add form';
    button.classList.remove('btn-danger');
    button.classList.add('btn-success');
  } else {
    document.getElementById('form').innerHTML = inner_form;
    button.innerHTML = 'Delete Form';
    button.classList.add('btn-danger');
    button.classList.remove('btn-success');
  }
}


来源: stackexchange

问:
How to have Google Form retrieve data from a Google Sheet based on user input?
I work for a local school district and have been tasked with creating registration forms for our All-County band/orchestra ensemble auditions. My desired outcome is to be able to have a student enter his/her school ID number into a Google Form and for his name and other demographic information to pre-populate from another Google Sheet.  I know that I can achieve this outcome with add-ons like FormRanger, but we are a district of over 35,000 students which I'm afraid would break the add-on, or at the least take forever to load.  </p>

<p>Is this possible even?  I am pretty much a novice when it comes to google scripts, but and savvy enough to be able to search and follow directions.  </p>

答:
That isn't possible by using Google Forms but you could create URL that will pre-fill the form.

One way, is that you create a pre-filled form URL for each student, then send the corresponding URL to each student but maybe you will have more control over the process if you create a web application instead of using Google Forms.

To create this web application you could use Google Apps Script but you should learn about HTML, CSS and JavaScript.

ContentLicense: CC BY-SA 4.0

Body:
I work for a local school district and have been tasked with creating registration forms for our All-County band/orchestra ensemble auditions. My desired outcome is to be able to have a student enter his/her school ID number into a Google Form and for his name and other demographic information to pre-populate from another Google Sheet.  I know that I can achieve this outcome with add-ons like FormRanger, but we are a district of over 35,000 students which I'm afraid would break the add-on, or at the least take forever to load.

Is this possible even?  I am pretty much a novice when it comes to google scripts, but and savvy enough to be able to search and follow directions.


问:
Amend node item where item is greater than or less than an integer?
I need to output/amend item(s) in an XML where an item

<TrackNumber> matches number 2 onwards (to infinity) integer value

read from XML is greater than, less than, less than or equal to a    specified integer value

Criteria: For items matching TrackNumber 2 onwards (to infinity):

```<code>FOR <ScannedTrack>
WHERE <TrackNumber>2 (and onwards)
IF <Codec>2048</Codec>
AND <Bitrate> is <= LESS THAN OR EQUAL TO <Bitrate>192000</Bitrate>

OUTPUT/WRITE <Encoder> item as:
<Encoder>Ac3Passthrough</Encoder>
AND DELETE element/node <MixDown>

FOR <ScannedTrack>
<TrackNumber>2 (and onwards)
IF <Codec>2048</Codec> or <Codec>16777216</Codec> or <Codec>262144</Codec> or <Codec>8192</Codec> or <Codec>4444</Codec>
AND <Bitrate> is > GREATER THAN <Bitrate>192000</Bitrate>

OUTPUT/WRITE the following to each specific item:
<AudioTrack>
<MixDown>stereo</MixDown>
<Encoder>Ac3</Encoder>
<Bitrate>192</Bitrate>
</code>```

NOTE: The elements <MixDown>, <Encoder> and <Bitrate> contain existing values already, so replace/overwrite these with the output/write values shown above if match conditions.

Can someone please help me with scripting - VBScript, XSLT or Batch with Regex to help achieve the required output?

I have tried to have a go with the XSL stylesheet code below, but I think some of my syntax is incorrect, could use some help:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

        <xsl:mode on-no-match="shallow-copy"/>

        <xsl:template match="AudioTrack[ScannedTrack/TrackNumber = (>= '2')]">
            <xsl:template match="AudioTrack[ScannedTrack[Codec = (2048)] and [Bitrate (<=192000)]/Encoder">
                <xsl:copy>Ac3Passthrough</xsl:copy>
            </xsl:template>

            <xsl:template match="AudioTrack[ScannedTrack/TrackNumber = (>= '2')]">
                <xsl:template match="AudioTrack[ScannedTrack[Codec = (2048, 262144, 8192, 4444, 16777216)] and [Bitrate = (>192000)]/MixDown/Encoder/Bitrate">
                    <xsl:copy>Stereo</xsl:copy>
                    <xsl:copy>Ac3</xsl:copy>
                    <xsl:copy>192</xsl:copy>
                </xsl:template>

            </xsl:stylesheet>
</code>```

Here is the example XML file to test with:

```<code><?xml version="1.0"?>
<ArrayOfQueueTask xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <QueueTask>
        <Task>
            <AudioTracks>
                <AudioTrack>
                    <MixDown>5point1</MixDown>
                    <Encoder>EAc3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>448</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>1</TrackNumber>
                        <Description>English (E-AC3) (5.1 ch)</Description>
                        <Codec>16777216</Codec>
                        <Bitrate>448000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>5point1</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>2</TrackNumber>
                        <Description>English (AC3) (5.1 ch)</Description>
                        <Codec>2048</Codec>
                        <Bitrate>192000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>EAc3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>224</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>3</TrackNumber>
                        <Description>English (E-AC3) (5.1 ch)</Description>
                        <Codec>16777216</Codec>
                        <Bitrate>224000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>5point1</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>128</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>4</TrackNumber>
                        <Description>English (AC3) (5.1 ch)</Description>
                        <Codec>2048</Codec>
                        <Bitrate>224000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>5point1</MixDown>
                    <Encoder>ffaac</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>256</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>5</TrackNumber>
                        <Description>English (DTS-HD MA) (5.1 ch)</Description>
                        <Codec>262144</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Lame</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>256</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>6</TrackNumber>
                        <Description>English (DTS) (5.1 ch)</Description>
                        <Codec>8192</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>ffaac</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>160</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>7</TrackNumber>
                        <Description>TrueHD 5.1</Description>
                        <Codec>4444</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
            </AudioTracks>
        </Task>
    </QueueTask>
</ArrayOfQueueTask>
</code>```

And here is the expected output XML after transformations applied:

```<code><?xml version="1.0"?>
<ArrayOfQueueTask xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <QueueTask>
        <Task>
            <AudioTracks>
                <AudioTrack>
                    <MixDown>5point1</MixDown>
                    <Encoder>EAc3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>448</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>1</TrackNumber>
                        <Description>English (E-AC3) (5.1 ch)</Description>
                        <Codec>16777216</Codec>
                        <Bitrate>448000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <Encoder>Ac3Passthrough</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>2</TrackNumber>
                        <Description>English (AC3) (5.1 ch)</Description>
                        <Codec>2048</Codec>
                        <Bitrate>192000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>3</TrackNumber>
                        <Description>English (E-AC3) (5.1 ch)</Description>
                        <Codec>16777216</Codec>
                        <Bitrate>224000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>4</TrackNumber>
                        <Description>English (AC3) (5.1 ch)</Description>
                        <Codec>2048</Codec>
                        <Bitrate>224000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>5</TrackNumber>
                        <Description>English (DTS-HD MA) (5.1 ch)</Description>
                        <Codec>262144</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>6</TrackNumber>
                        <Description>English (DTS) (5.1 ch)</Description>
                        <Codec>8192</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>7</TrackNumber>
                        <Description>TrueHD 5.1</Description>
                        <Codec>4444</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
            </AudioTracks>
        </Task>
    </QueueTask>
</ArrayOfQueueTask>
</code>```

Order of Original XML File:

```<code><?xml version="1.0"?>
<ArrayOfQueueTask xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <QueueTask>
        <Task>
            <AudioTracks>
                <AudioTrack>
                    <IsNotifying>true</IsNotifying>
                    <DRC>0</DRC>
                    <Gain>0</Gain>
                    <MixDown>5point1</MixDown>
                    <Encoder>Ac3</Encoder>
                    <SampleRate>0</SampleRate>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>448</Bitrate>
                    <Quality>-1</Quality>
                    <TrackName/>
                    <IsDefault>false</IsDefault>
                    <SampleRateDisplayValue>Auto</SampleRateDisplayValue>
                    <ScannedTrack>
                        <TrackNumber>1</TrackNumber>
                        <Language>English</Language>
                        <LanguageCode>eng</LanguageCode>
                        <Description>English (E-AC3) (5.1 ch)</Description>
                        <Codec>16777216</Codec>
                        <SampleRate>48000</SampleRate>
                        <Bitrate>224000</Bitrate>
                        <ChannelLayout>128000</ChannelLayout>
                    </ScannedTrack>
                </AudioTrack>
            </AudioTracks>
        </Task>
    </QueueTask>
</ArrayOfQueueTask>
</code>```

答:
This is very difficult and time-consuming to follow. AFAICT, you want to do:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 1 and ScannedTrack/Codec = 2048 and ScannedTrack/Bitrate <= 192000]">
    <xsl:copy>
        <Encoder>Ac3Passthrough</Encoder>
        <xsl:apply-templates select="*[not(self::MixDown or self::Encoder)]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 1 and (ScannedTrack/Codec = 2048 or ScannedTrack/Codec = 262144 or ScannedTrack/Codec = 8192 or ScannedTrack/Codec = 4444) and ScannedTrack/Bitrate > 192000]">
    <xsl:copy>
        <MixDown>stereo</MixDown>
        <Encoder>Ac3</Encoder>
        <Bitrate>192</Bitrate>
        <xsl:apply-templates select="*[not(self::MixDown or self::Encoder or self::Bitrate)]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Added in response to your comment:

If you want to preserve the original order of the elements under AudioTrack, try:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 1 and ScannedTrack/Codec = 2048 and ScannedTrack/Bitrate <= 192000]">
    <xsl:copy>
        <xsl:apply-templates select="IsNotifying | DRC | Gain"/>
        <Encoder>Ac3Passthrough</Encoder>
        <xsl:apply-templates select="SampleRate | EncoderRateType | Bitrate | Quality | TrackName | IsDefault | SampleRateDisplayValue | ScannedTrack"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 1 and (ScannedTrack/Codec = 2048 or ScannedTrack/Codec = 262144 or ScannedTrack/Codec = 8192 or ScannedTrack/Codec = 4444) and ScannedTrack/Bitrate > 192000]">
    <xsl:copy>
        <xsl:apply-templates select="IsNotifying | DRC | Gain"/>
        <MixDown>stereo</MixDown>
        <Encoder>Ac3</Encoder>
        <xsl:apply-templates select="SampleRate | EncoderRateType"/>
        <Bitrate>192</Bitrate>
        <xsl:apply-templates select="Quality | TrackName | IsDefault | SampleRateDisplayValue | ScannedTrack"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

This is assuming the original order is:

IsNotifying

DRC

Gain

MixDown

Encoder

SampleRate

EncoderRateType

Bitrate

Quality

TrackName

IsDefault

SampleRateDisplayValue

ScannedTrack

Body:
I need to output/amend item(s) in an XML where an item

<TrackNumber> matches number 2 onwards (to infinity) integer value

read from XML is greater than, less than, less than or equal to a    specified integer value

Criteria: For items matching TrackNumber 2 onwards (to infinity):

FOR <ScannedTrack>
WHERE <TrackNumber>2 (and onwards)
IF <Codec>2048</Codec>
AND <Bitrate> is <= LESS THAN OR EQUAL TO <Bitrate>192000</Bitrate>

OUTPUT/WRITE <Encoder> item as:
<Encoder>Ac3Passthrough</Encoder>
AND DELETE element/node <MixDown>

FOR <ScannedTrack>
<TrackNumber>2 (and onwards)
IF <Codec>2048</Codec> or <Codec>16777216</Codec> or <Codec>262144</Codec> or <Codec>8192</Codec> or <Codec>4444</Codec>
AND <Bitrate> is > GREATER THAN <Bitrate>192000</Bitrate>

OUTPUT/WRITE the following to each specific item:
<AudioTrack>
<MixDown>stereo</MixDown>
<Encoder>Ac3</Encoder>
<Bitrate>192</Bitrate>

NOTE: The elements <MixDown>, <Encoder> and <Bitrate> contain existing values already, so replace/overwrite these with the output/write values shown above if match conditions.

Can someone please help me with scripting - VBScript, XSLT or Batch with Regex to help achieve the required output?

I have tried to have a go with the XSL stylesheet code below, but I think some of my syntax is incorrect, could use some help:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

        <xsl:mode on-no-match="shallow-copy"/>

        <xsl:template match="AudioTrack[ScannedTrack/TrackNumber = (>= '2')]">
            <xsl:template match="AudioTrack[ScannedTrack[Codec = (2048)] and [Bitrate (<=192000)]/Encoder">
                <xsl:copy>Ac3Passthrough</xsl:copy>
            </xsl:template>

            <xsl:template match="AudioTrack[ScannedTrack/TrackNumber = (>= '2')]">
                <xsl:template match="AudioTrack[ScannedTrack[Codec = (2048, 262144, 8192, 4444, 16777216)] and [Bitrate = (>192000)]/MixDown/Encoder/Bitrate">
                    <xsl:copy>Stereo</xsl:copy>
                    <xsl:copy>Ac3</xsl:copy>
                    <xsl:copy>192</xsl:copy>
                </xsl:template>

            </xsl:stylesheet>

Here is the example XML file to test with:

<?xml version="1.0"?>
<ArrayOfQueueTask xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <QueueTask>
        <Task>
            <AudioTracks>
                <AudioTrack>
                    <MixDown>5point1</MixDown>
                    <Encoder>EAc3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>448</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>1</TrackNumber>
                        <Description>English (E-AC3) (5.1 ch)</Description>
                        <Codec>16777216</Codec>
                        <Bitrate>448000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>5point1</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>2</TrackNumber>
                        <Description>English (AC3) (5.1 ch)</Description>
                        <Codec>2048</Codec>
                        <Bitrate>192000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>EAc3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>224</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>3</TrackNumber>
                        <Description>English (E-AC3) (5.1 ch)</Description>
                        <Codec>16777216</Codec>
                        <Bitrate>224000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>5point1</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>128</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>4</TrackNumber>
                        <Description>English (AC3) (5.1 ch)</Description>
                        <Codec>2048</Codec>
                        <Bitrate>224000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>5point1</MixDown>
                    <Encoder>ffaac</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>256</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>5</TrackNumber>
                        <Description>English (DTS-HD MA) (5.1 ch)</Description>
                        <Codec>262144</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Lame</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>256</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>6</TrackNumber>
                        <Description>English (DTS) (5.1 ch)</Description>
                        <Codec>8192</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>ffaac</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>160</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>7</TrackNumber>
                        <Description>TrueHD 5.1</Description>
                        <Codec>4444</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
            </AudioTracks>
        </Task>
    </QueueTask>
</ArrayOfQueueTask>

And here is the expected output XML after transformations applied:

<?xml version="1.0"?>
<ArrayOfQueueTask xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <QueueTask>
        <Task>
            <AudioTracks>
                <AudioTrack>
                    <MixDown>5point1</MixDown>
                    <Encoder>EAc3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>448</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>1</TrackNumber>
                        <Description>English (E-AC3) (5.1 ch)</Description>
                        <Codec>16777216</Codec>
                        <Bitrate>448000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <Encoder>Ac3Passthrough</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>2</TrackNumber>
                        <Description>English (AC3) (5.1 ch)</Description>
                        <Codec>2048</Codec>
                        <Bitrate>192000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>3</TrackNumber>
                        <Description>English (E-AC3) (5.1 ch)</Description>
                        <Codec>16777216</Codec>
                        <Bitrate>224000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>4</TrackNumber>
                        <Description>English (AC3) (5.1 ch)</Description>
                        <Codec>2048</Codec>
                        <Bitrate>224000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>5</TrackNumber>
                        <Description>English (DTS-HD MA) (5.1 ch)</Description>
                        <Codec>262144</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>6</TrackNumber>
                        <Description>English (DTS) (5.1 ch)</Description>
                        <Codec>8192</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
                <AudioTrack>
                    <MixDown>stereo</MixDown>
                    <Encoder>Ac3</Encoder>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>192</Bitrate>
                    <ScannedTrack>
                        <TrackNumber>7</TrackNumber>
                        <Description>TrueHD 5.1</Description>
                        <Codec>4444</Codec>
                        <Bitrate>1536000</Bitrate>
                    </ScannedTrack>
                </AudioTrack>
            </AudioTracks>
        </Task>
    </QueueTask>
</ArrayOfQueueTask>

Order of Original XML File:

<?xml version="1.0"?>
<ArrayOfQueueTask xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <QueueTask>
        <Task>
            <AudioTracks>
                <AudioTrack>
                    <IsNotifying>true</IsNotifying>
                    <DRC>0</DRC>
                    <Gain>0</Gain>
                    <MixDown>5point1</MixDown>
                    <Encoder>Ac3</Encoder>
                    <SampleRate>0</SampleRate>
                    <EncoderRateType>Bitrate</EncoderRateType>
                    <Bitrate>448</Bitrate>
                    <Quality>-1</Quality>
                    <TrackName/>
                    <IsDefault>false</IsDefault>
                    <SampleRateDisplayValue>Auto</SampleRateDisplayValue>
                    <ScannedTrack>
                        <TrackNumber>1</TrackNumber>
                        <Language>English</Language>
                        <LanguageCode>eng</LanguageCode>
                        <Description>English (E-AC3) (5.1 ch)</Description>
                        <Codec>16777216</Codec>
                        <SampleRate>48000</SampleRate>
                        <Bitrate>224000</Bitrate>
                        <ChannelLayout>128000</ChannelLayout>
                    </ScannedTrack>
                </AudioTrack>
            </AudioTracks>
        </Task>
    </QueueTask>
</ArrayOfQueueTask>

Body:
This is very difficult and time-consuming to follow. AFAICT, you want to do:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 1 and ScannedTrack/Codec = 2048 and ScannedTrack/Bitrate &lt;= 192000]">
    <xsl:copy>
        <Encoder>Ac3Passthrough</Encoder>
        <xsl:apply-templates select="*[not(self::MixDown or self::Encoder)]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 1 and (ScannedTrack/Codec = 2048 or ScannedTrack/Codec = 262144 or ScannedTrack/Codec = 8192 or ScannedTrack/Codec = 4444) and ScannedTrack/Bitrate > 192000]">
    <xsl:copy>
        <MixDown>stereo</MixDown>
        <Encoder>Ac3</Encoder>
        <Bitrate>192</Bitrate>
        <xsl:apply-templates select="*[not(self::MixDown or self::Encoder or self::Bitrate)]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Added in response to your comment:

If you want to preserve the original order of the elements under AudioTrack, try:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 1 and ScannedTrack/Codec = 2048 and ScannedTrack/Bitrate &lt;= 192000]">
    <xsl:copy>
        <xsl:apply-templates select="IsNotifying | DRC | Gain"/>
        <Encoder>Ac3Passthrough</Encoder>
        <xsl:apply-templates select="SampleRate | EncoderRateType | Bitrate | Quality | TrackName | IsDefault | SampleRateDisplayValue | ScannedTrack"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 1 and (ScannedTrack/Codec = 2048 or ScannedTrack/Codec = 262144 or ScannedTrack/Codec = 8192 or ScannedTrack/Codec = 4444) and ScannedTrack/Bitrate > 192000]">
    <xsl:copy>
        <xsl:apply-templates select="IsNotifying | DRC | Gain"/>
        <MixDown>stereo</MixDown>
        <Encoder>Ac3</Encoder>
        <xsl:apply-templates select="SampleRate | EncoderRateType"/>
        <Bitrate>192</Bitrate>
        <xsl:apply-templates select="Quality | TrackName | IsDefault | SampleRateDisplayValue | ScannedTrack"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

This is assuming the original order is:

IsNotifying

DRC

Gain

MixDown

Encoder

SampleRate

EncoderRateType

Bitrate

Quality

TrackName

IsDefault

SampleRateDisplayValue

ScannedTrack


问:
Do not want to pass all unnecessary parameters in stored Procedure
i have a stroed procedure having two events one is insertion and another one is deletion
using flag. when i have to delete ..i have to pass all parameters which is not actually need while delete.... i need your help to sort it out .

my code is like this..

```<code>ALTER     Proc Proc_Manage_Opening_Leave @ActionFlag int,@SNo int,@LEAVE_ID int,@GIVEN decimal,@GIVENMONTH int,@GIVENYEAR int,@APPROVEDBY int,@IsOpening varchar(6),@EMP_ID int
as
SET NOCOUNT ON
if(@ActionFlag=0)
BEGIN

insert into Tbl_Org_leave_log (EMP_ID,LEAVE_ID,GIVEN,GIVENMONTH,GIVENYEAR,ApprovedBy,OP_FLAG,GIVENDAY)
values(@EMP_ID,@LEAVE_ID,@GIVEN,@GIVENMONTH,@GIVENYEAR,@APPROVEDBY,
(
case
when @IsOpening='False' then 0
when @IsOpening='True' then 1
ELSE NULL
END
),
datepart(day,getdate()))
END

 IF(@ActionFlag=1)
BEGIN

delete from tbl_org_leave_log where SNo=@SNo
END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
</code>```

答: I suggest creating a seperate SPs for each action.</p>

ContentLicense: CC BY-SA 3.0

Body:
i have a stroed procedure having two events one is insertion and another one is deletion
using flag. when i have to delete ..i have to pass all parameters which is not actually need while delete.... i need your help to sort it out .

my code is like this..

ALTER     Proc Proc_Manage_Opening_Leave @ActionFlag int,@SNo int,@LEAVE_ID int,@GIVEN decimal,@GIVENMONTH int,@GIVENYEAR int,@APPROVEDBY int,@IsOpening varchar(6),@EMP_ID int
as
SET NOCOUNT ON
if(@ActionFlag=0)
BEGIN

insert into Tbl_Org_leave_log (EMP_ID,LEAVE_ID,GIVEN,GIVENMONTH,GIVENYEAR,ApprovedBy,OP_FLAG,GIVENDAY)
values(@EMP_ID,@LEAVE_ID,@GIVEN,@GIVENMONTH,@GIVENYEAR,@APPROVEDBY,
(
case
when @IsOpening='False' then 0
when @IsOpening='True' then 1
ELSE NULL
END
),
datepart(day,getdate()))
END

 IF(@ActionFlag=1)
BEGIN

delete from tbl_org_leave_log where SNo=@SNo
END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO


问:
how to decode jQuery json data posted to php
I have a web page that sends form data to php using jQuery.  I want to decode the data array and loop through it, displaying each of the four values using php print_r.

Here is the jQuery function to post the data to php:

```<code><script type="text/javascript">
function postData() {
    return $.ajax({
    var datastring = $("#echo_test").serialize();
    $.ajax({
       type: "POST",
       url: "echo_test.php",
       data: {post: datastring},
    });
});
}
</script>
</code>```

Here is the php function echo_test:

```<code><?php
$obj = json_decode($_POST['post']);
print_r($obj['firstname']);
?>
</code>```

I think json_decode is wrong because the data posted is not json format.

When I click the button that calls the jQuery function, the php page opens in the browser but it's blank, with nothing echoed back.  Ideally I would I loop through $obj to display each of the four values on the screen.

Ultimately I will post the data to Postgres on a cloud server.  For now, I'm testing it locally to verify the data because I'm new to passing data to php from jQuery.

Thanks for any help with this.

答:
form.serialize() send data in query string format. The parse_str() function parses a query string into variables.</p>

```<code><?php
parse_str($_POST['post'], $obj);
print_r($obj);
?>
</code>```

Body:
I have a web page that sends form data to php using jQuery.  I want to decode the data array and loop through it, displaying each of the four values using php print_r.

Here is the jQuery function to post the data to php:

Here is the php function echo_test:

<?php
$obj = json_decode($_POST['post']);
print_r($obj['firstname']);
?>

I think json_decode is wrong because the data posted is not json format.

When I click the button that calls the jQuery function, the php page opens in the browser but it's blank, with nothing echoed back.  Ideally I would I loop through $obj to display each of the four values on the screen.

Ultimately I will post the data to Postgres on a cloud server.  For now, I'm testing it locally to verify the data because I'm new to passing data to php from jQuery.

Thanks for any help with this.

Body:
form.serialize() send data in query string format. The parse_str() function parses a query string into variables.

<?php
parse_str($_POST['post'], $obj);
print_r($obj);
?>


问:
Can't generate FCM Token for some Devices
I've Two android devices 5.1.1 , 5.0.2 and emulator(Pixel2 api 28 (android 9) ) , for the first device (5.1.1) i can generate fcm token with no problem

I am using this code to generate token

```<code>irebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                    Log.w("FCM_TOKEN", "getInstanceId failed", task.getException());
                    return;
                }

                // Get new Instance ID token
                String token = task.getResult().getToken();

            }
        });
</code>```

I am getting this exception when using the second device (5.0.2) and the emulator (android 9)

05-26 01:10:01.115 13377-13402/com.abc.payapp E/FirebaseInstanceId: Token retrieval failed: AUTHENTICATION_FAILED

What kind of authentication required when generating tokens !

答:
Using an emulator or device WITHOUT Google Play will cause this error.

Check the Google Play Store app on your device/emulator, make the update, and you should be good to go !

Body:
I've Two android devices 5.1.1 , 5.0.2 and emulator(Pixel2 api 28 (android 9) ) , for the first device (5.1.1) i can generate fcm token with no problem

I am using this code to generate token

irebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                    Log.w("FCM_TOKEN", "getInstanceId failed", task.getException());
                    return;
                }

                // Get new Instance ID token
                String token = task.getResult().getToken();

            }
        });

I am getting this exception when using the second device (5.0.2) and the emulator (android 9)

05-26 01:10:01.115 13377-13402/com.abc.payapp E/FirebaseInstanceId: Token retrieval failed: AUTHENTICATION_FAILED

What kind of authentication required when generating tokens !


问:
How to find Message Type from attribute name in google proto buf message?
I have protobuf messages defined as below. I need to find the message type from the attribute name. For example, when the input is "cfgMsg" the output should be ConfigMsg or CfgServerMsg.ConfigMsg (full name).

```<code>message CfgServerMsg {
  string name = 1;
  ConfigMsg cfgMsg = 2;
}

message ConfigMsg {
  string cfgName = 1;
  uint32 msgId = 2;
}
</code>```

I have the below code. However, this is working for well defined types like string, int, float etc. and for messages it just prints "message" as the output.

I removed some code and presented only that is relevant to this question. So this is obviously not the complete code.

```<code>google::protobuf::Message *modObj = new ModObj();

const google::protobuf::Descriptor *outModDesc
            =  modObj->GetDescriptor();
const Reflection *outModRefl = modObj->GetReflection();
const FieldDescriptor *field;

// Loop to iterate over all the fields
{
  field = outModDesc->FindFieldByName(tmp_name);
  std::string type = field->type_name();
  std::cout << "Type:" << type << std::endl;
}
</code>```

Output:
Type:string
Type:message

However, I want to get the actual message type which is "ConfigMsg" instead of just "message". Is there any such API available from protobuf ?

I did check this page https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor#FileDescriptor.name.details thoroughly, but couldn't find any thing useful for this.

If anyone has done similar thing or know some thing around this, it would be useful.

Thanks,

答:
I got some clue from another group and I could write the code in C++ to get the actual message type.  Posting the details below to help others.

```<code>google::protobuf::Message *modObj = new ModObj();

const google::protobuf::Descriptor *outModDesc
            =  modObj->GetDescriptor();
const Reflection *outModRefl = modObj->GetReflection();
const FieldDescriptor *field;

// Loop to iterate over all the fields
{
  field = outModDesc->FindFieldByName(tmp_name);
  std::string type = field->type_name();
  std::cout << "Type:" << type << std::endl;

  outField = outModDesc->FindFieldByName(tmp_name);
  const google::protobuf::Descriptor* tmpDesc = outField->message_type();
  std::string subMsgType = tmpDesc->name();
  std::string fullMsgType = tmpDesc->full_name();
  std::cout << " Type: " << subMsgType
                        << ", Full Type: " << fullMsgType << std::endl;
  }
</code>```

Output from the code:

```<code>Type: ConfigMsg, FullType: frrcfg.ConfigMsg
</code>```

Body:
I have protobuf messages defined as below. I need to find the message type from the attribute name. For example, when the input is "cfgMsg" the output should be ConfigMsg or CfgServerMsg.ConfigMsg (full name).

message CfgServerMsg {
  string name = 1;
  ConfigMsg cfgMsg = 2;
}

message ConfigMsg {
  string cfgName = 1;
  uint32 msgId = 2;
}

I have the below code. However, this is working for well defined types like string, int, float etc. and for messages it just prints "message" as the output.

I removed some code and presented only that is relevant to this question. So this is obviously not the complete code.

google::protobuf::Message *modObj = new ModObj();

const google::protobuf::Descriptor *outModDesc
            =  modObj->GetDescriptor();
const Reflection *outModRefl = modObj->GetReflection();
const FieldDescriptor *field;

// Loop to iterate over all the fields
{
  field = outModDesc->FindFieldByName(tmp_name);
  std::string type = field->type_name();
  std::cout << "Type:" << type << std::endl;
}

Output:
Type:string
Type:message

However, I want to get the actual message type which is "ConfigMsg" instead of just "message". Is there any such API available from protobuf ?

I did check this page https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor#FileDescriptor.name.details thoroughly, but couldn't find any thing useful for this.

If anyone has done similar thing or know some thing around this, it would be useful.

Thanks,

Body:
I got some clue from another group and I could write the code in C++ to get the actual message type.  Posting the details below to help others.

google::protobuf::Message *modObj = new ModObj();

const google::protobuf::Descriptor *outModDesc
            =  modObj->GetDescriptor();
const Reflection *outModRefl = modObj->GetReflection();
const FieldDescriptor *field;

// Loop to iterate over all the fields
{
  field = outModDesc->FindFieldByName(tmp_name);
  std::string type = field->type_name();
  std::cout << "Type:" << type << std::endl;

  outField = outModDesc->FindFieldByName(tmp_name);
  const google::protobuf::Descriptor* tmpDesc = outField->message_type();
  std::string subMsgType = tmpDesc->name();
  std::string fullMsgType = tmpDesc->full_name();
  std::cout << " Type: " << subMsgType
                        << ", Full Type: " << fullMsgType << std::endl;
  }

Output from the code:

Type: ConfigMsg, FullType: frrcfg.ConfigMsg


问:
Laravel 5 geting InvalidStateException in AbstractProvider.php
I am trying to use login with facebook in laravel 5 using Socialize.

Here is my route file code.

```<code>Route::get('fb', function ($facebook = "facebook")
{
    $provider = \Socialize::with($facebook);
    if (Input::has('code'))
    {
        $user = $provider->user();
        return var_dump($user);
    } else {
        return $provider->scopes(['public_profile','user_friends'])->redirect();
    }
});
</code>```

login is success and I get the code but time of get $provider->user() I get the error.

InvalidStateException in AbstractProvider.php line 161

答:
I know this post is a little old but I kept hitting it while searching for a possible answer.

I had the same error but my solution was a little different.

I develop on Ubuntu 18.04 desktop since it is a server with a GUI. Socialite works great locally but as soon as I pushed/pulled the changes through git to the server, it quit.

I was running traces by recording what was sent to and from google. I "dd($_GET)" to get a raw dump before Socialite had a chance to get the info so I knew what was stored and ready for use. All info was there but Socialite didn't seem to "see" it. That is when I reasoned it was my apache2 header configuration interfering with the cookies/session data.

I had set header security in my apache2 configs. One of the settings was

```<code>Header always edit Set-Cookie ^(.*) "$1;HttpOnly;Secure;SameSite=Strict"
</code>```

This setting was interfering with the cookie information that socialite needed. I removed that setting from my apache2 header config(by commenting out) and restarted Apache. Finally I removed all sessions in storage/framework/session/* and cleared them from my browser just to be sure. That worked for me.

After I got it working, one by one enabled and tested each of the following settings to have the framework secure what header info it can:

```<code>SESSION_SECURE_COOKIE=true
</code>```

in my .env file

'http_only' => true, and
'same_site' => 'lax'(setting to "strict" did not seem to work)

in my config/session.php file.

Now it is back to testing security and tweaking things back if need be.

Body:
I am trying to use login with facebook in laravel 5 using Socialize.

Here is my route file code.

Route::get('fb', function ($facebook = "facebook")
{
    $provider = \Socialize::with($facebook);
    if (Input::has('code'))
    {
        $user = $provider->user();
        return var_dump($user);
    } else {
        return $provider->scopes(['public_profile','user_friends'])->redirect();
    }
});

login is success and I get the code but time of get $provider->user() I get the error.

InvalidStateException in AbstractProvider.php line 161

Body:
I know this post is a little old but I kept hitting it while searching for a possible answer.

I had the same error but my solution was a little different.

I develop on Ubuntu 18.04 desktop since it is a server with a GUI. Socialite works great locally but as soon as I pushed/pulled the changes through git to the server, it quit.

I was running traces by recording what was sent to and from google. I "dd($_GET)" to get a raw dump before Socialite had a chance to get the info so I knew what was stored and ready for use. All info was there but Socialite didn't seem to "see" it. That is when I reasoned it was my apache2 header configuration interfering with the cookies/session data.

I had set header security in my apache2 configs. One of the settings was

Header always edit Set-Cookie ^(.*) "$1;HttpOnly;Secure;SameSite=Strict"

This setting was interfering with the cookie information that socialite needed. I removed that setting from my apache2 header config(by commenting out) and restarted Apache. Finally I removed all sessions in storage/framework/session/* and cleared them from my browser just to be sure. That worked for me.

After I got it working, one by one enabled and tested each of the following settings to have the framework secure what header info it can:

SESSION_SECURE_COOKIE=true

in my .env file

'http_only' => true, and
'same_site' => 'lax'(setting to "strict" did not seem to work)

in my config/session.php file.

Now it is back to testing security and tweaking things back if need be.


答:
What you need to do is use parse_str, but correctly:</p>

```<code><?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>
</code>```

Title: how to decode jQuery json data posted to php

Body:
What you need to do is use parse_str, but correctly:

<?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>


问:
Convert MySQL date with milliseconds to Google Sheets' date format
I have the following string in Google Sheets, extracted from a MySQL date format:

2018-05-28 23:10:23.477

I need it to be converted to a date format in Google Sheets, including the milliseconds.

答:
Please try:</p>

```<code>=text(A1,"yyyy-mm-dd hh:mm:ss.000")-0
</code>```

Body:
Please try:

=text(A1,"yyyy-mm-dd hh:mm:ss.000")-0


问:
What is an Object in Python?
I am surprised that my question was not asked (worded like the above) before. I am hoping that someone could break down this basic term "object" in the context of a OOP language like Python. Explained in a way in which a beginner like myself would be able to grasp.

When I typed my question on Google, the first post that appears is found here.

This is the definition:
An object is created using the constructor of the class. This object will then be called the instance of the class.

Wikipedia defines it like this:
An object is an instance of a Class. Objects are an abstraction. They hold both data, and ways to manipulate the data. The data is usually not visible outside the object.

I am hoping someone could help to break down this vital concept for me, or kindly point me to more resources. Thanks!

答:
To go deep, you need to understand the Python data model.

But if you want a glossy stackoverflow cheat sheet, let's start with a dictionary. (In order to avoid circular definitions, let's just agree that at a minimum, a dictionary is a mapping of keys to values. In this case, we can even say the keys are definitely strings.)

```<code>def some_method():
    return 'hello world'

some_dictionary = {
    "a_data_key": "a value",
    "a_method_key": some_method,
}
</code>```

An object, then, is such a mapping, with some additional syntactic sugar that allows you to access the "keys" using dot notation.

Now, there's a lot more to it than that. (In fact, if you want to understand this beyond python, I recommend The Art of the Metaobject Protocol.) You have to follow up with "but what is an instance?" and "how can you do things like iterate on entries in a dictionary like that?" and "what's a type system"? Some of this is addressed in Skam's fine answer.

We can talk about the python dunder methods, and how they are basically a protocol to implementing native behaviors like sized (things with length), comparable types (x < y), iterable types, etc.

But since the question is basically PhD-level broad, I think I'll leave my answer terribly reductive and see if you want to constrain the question.

Title: What is an Object in Python?

Body:
To go deep, you need to understand the Python data model.

But if you want a glossy stackoverflow cheat sheet, let's start with a dictionary. (In order to avoid circular definitions, let's just agree that at a minimum, a dictionary is a mapping of keys to values. In this case, we can even say the keys are definitely strings.)

def some_method():
    return 'hello world'

some_dictionary = {
    "a_data_key": "a value",
    "a_method_key": some_method,
}

An object, then, is such a mapping, with some additional syntactic sugar that allows you to access the "keys" using dot notation.

Now, there's a lot more to it than that. (In fact, if you want to understand this beyond python, I recommend The Art of the Metaobject Protocol.) You have to follow up with "but what is an instance?" and "how can you do things like iterate on entries in a dictionary like that?" and "what's a type system"? Some of this is addressed in Skam's fine answer.

We can talk about the python dunder methods, and how they are basically a protocol to implementing native behaviors like sized (things with length), comparable types (x < y), iterable types, etc.

But since the question is basically PhD-level broad, I think I'll leave my answer terribly reductive and see if you want to constrain the question.


问:
Can't create new User
When I try to registering a new user, I had this error

An exception occurred while executing 'INSERT INTO user (username, password, email, gender, newsletter, is_blocked, role_id, purchase_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' with params ["momo", "$2y$13$qCw4ZjU6k4s/dIwTeseEVud/zdjVu3xVper8oHAqsd/fKihq05Ga2", "momo@test.fr", "1", 0, 0, null, null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'role_id' cannot be null

Thank's in advance.

Here is my User entity:

```<code><?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* * @UniqueEntity(
*  fields = {"username"},
*  message = "Le nom d'utilisateur existe déjà",
* )
* @UniqueEntity(
*  fields = {"email"},
*  message = "L'email existe déjà",
* )
*/
class User implements UserInterface
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=180, unique=true)
 */
private $username;

private $roles = [];

/**
 * @var string The hashed password
 * @ORM\Column(type="string")
 */
private $password;

/**
 * @ORM\Column(type="string", length=180, unique=true)
 */
private $email;

/**
 * @ORM\Column(type="string", length=255)
 */
private $gender;

/**
 * @ORM\Column(type="boolean", nullable=true)
 */
private $newsletter;

/**
 * @ORM\Column(type="boolean")
 */
private $isBlocked;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Role", inversedBy="users")
 * @ORM\JoinColumn(nullable=false)
 */
private $role;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Article", inversedBy="users")
 */
private $article;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Firmware", inversedBy="users")
 */
private $firmware;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Purchase", inversedBy="users")
 */
private $purchase;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Note", mappedBy="user",
orphanRemoval=true)
 */
private $notes;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="user",
orphanRemoval=true)
 */
private $comments;

public function __construct()
{
    $this->article = new ArrayCollection();
    $this->firmware = new ArrayCollection();
    $this->notes = new ArrayCollection();
    $this->comments = new ArrayCollection();
}

public function getId(): ?int
{
    return $this->id;
}

/**
 * A visual identifier that represents this user.
 *
 * @see UserInterface
 */
public function getUsername(): string
{
    return (string) $this->username;
}

public function setUsername(string $username): self
{
    $this->username = $username;

    return $this;
}

/**
 * @see UserInterface
 */
public function getRoles(): array
{
    $roles = $this->roles;
    // guarantee every user at least has ROLE_USER
    $roles[] = 'ROLE_USER';

    return array_unique($roles);
}

public function setRoles(array $roles): self
{
    $this->roles = $roles;

    return $this;
}

/**
 * @see UserInterface
 */
public function getPassword(): string
{
    return (string) $this->password;
}

public function setPassword(string $password): self
{
    $this->password = $password;

    return $this;
}

/**
 * @see UserInterface
 */
public function getSalt()
{
    // not needed when using the "bcrypt" algorithm in security.yaml
}

/**
 * @see UserInterface
 */
public function eraseCredentials()
{
    // If you store any temporary, sensitive data on the user, clear it
here
    // $this->plainPassword = null;
}

public function getEmail(): ?string
{
    return $this->email;
}

public function setEmail(string $email): self
{
    $this->email = $email;

    return $this;
}

public function getGender(): ?string
{
    return $this->gender;
}

public function setGender(string $gender): self
{
    $this->gender = $gender;

    return $this;
}

public function getNewsletter(): ?bool
{
    return $this->newsletter;
}

public function setNewsletter(bool $newsletter): self
{
    $this->newsletter = $newsletter;

    return $this;
}

public function getIsBlocked(): ?bool
{
    return $this->isBlocked;
}

public function setIsBlocked(bool $isBlocked): self
{
    $this->isBlocked = $isBlocked;

    return $this;
}

public function getRole(): ?Role
{
    return $this->role;
}

public function setRole(?Role $role): self
{
    $this->role = $role;

    return $this;
}

/**
 * @return Collection|Article[]
 */
public function getArticle(): Collection
{
    return $this->article;
}

public function addArticle(Article $article): self
{
    if (!$this->article->contains($article)) {
        $this->article[] = $article;
    }

    return $this;
}

public function removeArticle(Article $article): self
{
    if ($this->article->contains($article)) {
        $this->article->removeElement($article);
    }

    return $this;
}

/**
 * @return Collection|Firmware[]
 */
public function getFirmware(): Collection
{
    return $this->firmware;
}

public function addFirmware(Firmware $firmware): self
{
    if (!$this->firmware->contains($firmware)) {
        $this->firmware[] = $firmware;
    }

    return $this;
}

public function removeFirmware(Firmware $firmware): self
{
    if ($this->firmware->contains($firmware)) {
        $this->firmware->removeElement($firmware);
    }

    return $this;
}

public function getPurchase(): ?Purchase
{
    return $this->purchase;
}

public function setPurchase(?Purchase $purchase): self
{
    $this->purchase = $purchase;

    return $this;
}

/**
 * @return Collection|Note[]
 */
public function getNotes(): Collection
{
    return $this->notes;
}

public function addNote(Note $note): self
{
    if (!$this->notes->contains($note)) {
        $this->notes[] = $note;
        $note->setUser($this);
    }

    return $this;
}

public function removeNote(Note $note): self
{
    if ($this->notes->contains($note)) {
        $this->notes->removeElement($note);
        // set the owning side to null (unless already changed)
        if ($note->getUser() === $this) {
            $note->setUser(null);
        }
    }

    return $this;
}

/**
 * @return Collection|Comment[]
 */
public function getComments(): Collection
{
    return $this->comments;
}

public function addComment(Comment $comment): self
{
    if (!$this->comments->contains($comment)) {
        $this->comments[] = $comment;
        $comment->setUser($this);
    }

    return $this;
}

public function removeComment(Comment $comment): self
{
    if ($this->comments->contains($comment)) {
        $this->comments->removeElement($comment);
        // set the owning side to null (unless already changed)
        if ($comment->getUser() === $this) {
            $comment->setUser(null);
        }
    }

    return $this;
}
}
</code>```

Role Entity

```<code><?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
  * @ORM\Entity(repositoryClass="App\Repository\RoleRepository")
  */
class Role
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=255)
 */
private $name;

/**
 * @ORM\Column(type="string", length=255)
 */
private $description;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="role")
 */
private $users;

public function __construct()
{
    $this->users = new ArrayCollection();
}

public function getId(): ?int
{
    return $this->id;
}

public function getName(): ?string
{
    return $this->name;
}

public function setName(string $name): self
{
    $this->name = $name;

    return $this;
}

public function getDescription(): ?string
{
    return $this->description;
}

public function setDescription(string $description): self
{
    $this->description = $description;

    return $this;
}

/**
 * @return Collection|User[]
 */
public function getUsers(): Collection
{
    return $this->users;
}

public function addUser(User $user): self
{
    if (!$this->users->contains($user)) {
        $this->users[] = $user;
        $user->setRole($this);
    }

    return $this;
}

public function removeUser(User $user): self
{
    if ($this->users->contains($user)) {
        $this->users->removeElement($user);
        // set the owning side to null (unless already changed)
        if ($user->getRole() === $this) {
            $user->setRole(null);
        }
    }

    return $this;
}

public function __toString()
{
    return $this->name;
}
}
</code>```

UserType

```<code><?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array
$options)
    {
    $builder
        ->add('username', TextType::class, [
            'empty_data' => '',
            ])
        ->add('password', RepeatedType::class, [
            'type' => PasswordType::class,
            'empty_data' => '',
            'invalid_message' => 'Valeur no correcte',
            'options' => ['attr' => ['class' => 'password-field']],
            'required' => true,
            'first_options'  => ['label' => 'Password','empty_data' =>
         ''],
            'second_options' => ['label' => 'Repeat Password','empty_data'
                  => ''],
        ])
        ->add('email',EmailType::class, [
            'empty_data' => '',
        ])
        ->add('gender', ChoiceType::class, [
            'help' => 'Un choix possible',
            'choices' => [
            'Femme' => true,
            'Homme' => true,
            'Autre' => true,
            ],
        ])
        ->add('newsletter')

    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => User::class,
    ]);
}
}
</code>```

SecutityController

```<code><?php

namespace App\Controller;

use App\Entity\User;
use App\Form\UserType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class SecurityController extends AbstractController
{
/**
 * @Route("/login", name="app_login")
 */
public function login(AuthenticationUtils $authenticationUtils): Response
{
    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('security/login.html.twig', ['last_username' =>
$lastUsername, 'error' => $error]);
}

 /**
 * @Route("/inscription", name="registration")
 */
public function registration(Request $request, EntityManagerInterface $em,
UserPasswordEncoderInterface $passwordEncoder)
{
    $user = new User();
    // $role = $user->getRoles();

    $form = $this->createForm(UserType::class, $user);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $password = $passwordEncoder->encodePassword($user, $user-
>getPassword());
        $user->setPassword($password);
        $user->setIsBlocked(false);
        // $user->setRole($role);

        $em->persist($user);
        $em->flush();

        $this->addFlash('success', 'Votre compte à bien été enregistré.');
    }

    return $this->render('security/registration.html.twig', ['form' =>
$form->createView()]);
}

 /**
 * @Route("/logout", name="logout")
 */
public function logout() {}
}
</code>```

答:
On role property Change nullable=false to nullable=true  And update the database

```<code> * @ORM\JoinColumn(nullable=true)
 */
private $role;
</code>```

Title: Can't create new User

Body:
When I try to registering a new user, I had this error

An exception occurred while executing 'INSERT INTO user (username, password, email, gender, newsletter, is_blocked, role_id, purchase_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' with params ["momo", "$2y$13$qCw4ZjU6k4s/dIwTeseEVud/zdjVu3xVper8oHAqsd/fKihq05Ga2", "momo@test.fr", "1", 0, 0, null, null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'role_id' cannot be null

Thank's in advance.

Here is my User entity:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* * @UniqueEntity(
*  fields = {"username"},
*  message = "Le nom d'utilisateur existe déjà",
* )
* @UniqueEntity(
*  fields = {"email"},
*  message = "L'email existe déjà",
* )
*/
class User implements UserInterface
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=180, unique=true)
 */
private $username;

private $roles = [];

/**
 * @var string The hashed password
 * @ORM\Column(type="string")
 */
private $password;

/**
 * @ORM\Column(type="string", length=180, unique=true)
 */
private $email;

/**
 * @ORM\Column(type="string", length=255)
 */
private $gender;

/**
 * @ORM\Column(type="boolean", nullable=true)
 */
private $newsletter;

/**
 * @ORM\Column(type="boolean")
 */
private $isBlocked;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Role", inversedBy="users")
 * @ORM\JoinColumn(nullable=false)
 */
private $role;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Article", inversedBy="users")
 */
private $article;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Firmware", inversedBy="users")
 */
private $firmware;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Purchase", inversedBy="users")
 */
private $purchase;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Note", mappedBy="user",
orphanRemoval=true)
 */
private $notes;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="user",
orphanRemoval=true)
 */
private $comments;

public function __construct()
{
    $this->article = new ArrayCollection();
    $this->firmware = new ArrayCollection();
    $this->notes = new ArrayCollection();
    $this->comments = new ArrayCollection();
}

public function getId(): ?int
{
    return $this->id;
}

/**
 * A visual identifier that represents this user.
 *
 * @see UserInterface
 */
public function getUsername(): string
{
    return (string) $this->username;
}

public function setUsername(string $username): self
{
    $this->username = $username;

    return $this;
}

/**
 * @see UserInterface
 */
public function getRoles(): array
{
    $roles = $this->roles;
    // guarantee every user at least has ROLE_USER
    $roles[] = 'ROLE_USER';

    return array_unique($roles);
}

public function setRoles(array $roles): self
{
    $this->roles = $roles;

    return $this;
}

/**
 * @see UserInterface
 */
public function getPassword(): string
{
    return (string) $this->password;
}

public function setPassword(string $password): self
{
    $this->password = $password;

    return $this;
}

/**
 * @see UserInterface
 */
public function getSalt()
{
    // not needed when using the "bcrypt" algorithm in security.yaml
}

/**
 * @see UserInterface
 */
public function eraseCredentials()
{
    // If you store any temporary, sensitive data on the user, clear it
here
    // $this->plainPassword = null;
}

public function getEmail(): ?string
{
    return $this->email;
}

public function setEmail(string $email): self
{
    $this->email = $email;

    return $this;
}

public function getGender(): ?string
{
    return $this->gender;
}

public function setGender(string $gender): self
{
    $this->gender = $gender;

    return $this;
}

public function getNewsletter(): ?bool
{
    return $this->newsletter;
}

public function setNewsletter(bool $newsletter): self
{
    $this->newsletter = $newsletter;

    return $this;
}

public function getIsBlocked(): ?bool
{
    return $this->isBlocked;
}

public function setIsBlocked(bool $isBlocked): self
{
    $this->isBlocked = $isBlocked;

    return $this;
}

public function getRole(): ?Role
{
    return $this->role;
}

public function setRole(?Role $role): self
{
    $this->role = $role;

    return $this;
}

/**
 * @return Collection|Article[]
 */
public function getArticle(): Collection
{
    return $this->article;
}

public function addArticle(Article $article): self
{
    if (!$this->article->contains($article)) {
        $this->article[] = $article;
    }

    return $this;
}

public function removeArticle(Article $article): self
{
    if ($this->article->contains($article)) {
        $this->article->removeElement($article);
    }

    return $this;
}

/**
 * @return Collection|Firmware[]
 */
public function getFirmware(): Collection
{
    return $this->firmware;
}

public function addFirmware(Firmware $firmware): self
{
    if (!$this->firmware->contains($firmware)) {
        $this->firmware[] = $firmware;
    }

    return $this;
}

public function removeFirmware(Firmware $firmware): self
{
    if ($this->firmware->contains($firmware)) {
        $this->firmware->removeElement($firmware);
    }

    return $this;
}

public function getPurchase(): ?Purchase
{
    return $this->purchase;
}

public function setPurchase(?Purchase $purchase): self
{
    $this->purchase = $purchase;

    return $this;
}

/**
 * @return Collection|Note[]
 */
public function getNotes(): Collection
{
    return $this->notes;
}

public function addNote(Note $note): self
{
    if (!$this->notes->contains($note)) {
        $this->notes[] = $note;
        $note->setUser($this);
    }

    return $this;
}

public function removeNote(Note $note): self
{
    if ($this->notes->contains($note)) {
        $this->notes->removeElement($note);
        // set the owning side to null (unless already changed)
        if ($note->getUser() === $this) {
            $note->setUser(null);
        }
    }

    return $this;
}

/**
 * @return Collection|Comment[]
 */
public function getComments(): Collection
{
    return $this->comments;
}

public function addComment(Comment $comment): self
{
    if (!$this->comments->contains($comment)) {
        $this->comments[] = $comment;
        $comment->setUser($this);
    }

    return $this;
}

public function removeComment(Comment $comment): self
{
    if ($this->comments->contains($comment)) {
        $this->comments->removeElement($comment);
        // set the owning side to null (unless already changed)
        if ($comment->getUser() === $this) {
            $comment->setUser(null);
        }
    }

    return $this;
}
}

Role Entity

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
  * @ORM\Entity(repositoryClass="App\Repository\RoleRepository")
  */
class Role
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=255)
 */
private $name;

/**
 * @ORM\Column(type="string", length=255)
 */
private $description;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="role")
 */
private $users;

public function __construct()
{
    $this->users = new ArrayCollection();
}

public function getId(): ?int
{
    return $this->id;
}

public function getName(): ?string
{
    return $this->name;
}

public function setName(string $name): self
{
    $this->name = $name;

    return $this;
}

public function getDescription(): ?string
{
    return $this->description;
}

public function setDescription(string $description): self
{
    $this->description = $description;

    return $this;
}

/**
 * @return Collection|User[]
 */
public function getUsers(): Collection
{
    return $this->users;
}

public function addUser(User $user): self
{
    if (!$this->users->contains($user)) {
        $this->users[] = $user;
        $user->setRole($this);
    }

    return $this;
}

public function removeUser(User $user): self
{
    if ($this->users->contains($user)) {
        $this->users->removeElement($user);
        // set the owning side to null (unless already changed)
        if ($user->getRole() === $this) {
            $user->setRole(null);
        }
    }

    return $this;
}

public function __toString()
{
    return $this->name;
}
}

UserType

<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array
$options)
    {
    $builder
        ->add('username', TextType::class, [
            'empty_data' => '',
            ])
        ->add('password', RepeatedType::class, [
            'type' => PasswordType::class,
            'empty_data' => '',
            'invalid_message' => 'Valeur no correcte',
            'options' => ['attr' => ['class' => 'password-field']],
            'required' => true,
            'first_options'  => ['label' => 'Password','empty_data' =>
         ''],
            'second_options' => ['label' => 'Repeat Password','empty_data'
                  => ''],
        ])
        ->add('email',EmailType::class, [
            'empty_data' => '',
        ])
        ->add('gender', ChoiceType::class, [
            'help' => 'Un choix possible',
            'choices' => [
            'Femme' => true,
            'Homme' => true,
            'Autre' => true,
            ],
        ])
        ->add('newsletter')

    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => User::class,
    ]);
}
}

SecutityController

<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\UserType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class SecurityController extends AbstractController
{
/**
 * @Route("/login", name="app_login")
 */
public function login(AuthenticationUtils $authenticationUtils): Response
{
    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('security/login.html.twig', ['last_username' =>
$lastUsername, 'error' => $error]);
}

 /**
 * @Route("/inscription", name="registration")
 */
public function registration(Request $request, EntityManagerInterface $em,
UserPasswordEncoderInterface $passwordEncoder)
{
    $user = new User();
    // $role = $user->getRoles();

    $form = $this->createForm(UserType::class, $user);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $password = $passwordEncoder->encodePassword($user, $user-
>getPassword());
        $user->setPassword($password);
        $user->setIsBlocked(false);
        // $user->setRole($role);

        $em->persist($user);
        $em->flush();

        $this->addFlash('success', 'Votre compte à bien été enregistré.');
    }

    return $this->render('security/registration.html.twig', ['form' =>
$form->createView()]);
}

 /**
 * @Route("/logout", name="logout")
 */
public function logout() {}
}

Body:
On role property Change nullable=false to nullable=true  And update the database

 * @ORM\JoinColumn(nullable=true)
 */
private $role;


问:
How is it possible to merge local changes with remote, if some of the new files are present in both? ( git )
I created an xyz.js file in my local repository. A colleague also created one with the same name.

When I was finished with my work, I tried run the following commands:

```<code>git shash
git pull
git stash apply
</code>```

I've got an aborting message after git pull, because xyz.js was present both in remote and locally, so I tried this:

```<code>git stash --all
</code>```

After that I was able to call git pull, but I was not able to run git stash apply afterwards. I tried to stash it again, and then this:

```<code> rm `git ls-tree -r stash@{1}^3 --name-only`
 git stash apply
</code>```

There are a lot of ignored files which are needed to run the project, but some of them are still missing. I tried to fix it, but I just made things worse.

I would like to avoid this situation in the future. How should I pull changes and then push my own the right way?

Please do not mark this question as a duplicate. I've found some questions here about asking for which is the preferred way of pull-commit-push, but the answers are not detailed, and they do not mention this problem.

答:
To add a bit to joanis' answer, no matter how you go about merging your new xyz.js with someone else's also-new xyz.js, you're going to hit an "add/add conflict".  Remember that Git's merge engine, no matter how you invoke it—and git stash apply and git stash pop invoke it, so whether you use git merge (this is my own preference) or git stash to achieve the merge—takes three inputs: a base version, a left-side or "local" or --ours version, and a right-side or remote or --theirs version.

What Git does is compare the base version of the file to your version of the file, to see what you changed.  Separately, it compares the (same) base version of the file to their version of the file, to see what they changed.

In this particular case, the base version of xyz.js is: The file does not exist.  The left-side version is your file, and the right-side one is theirs.  (If you swap left and right sides, nothing changes except for the label: --ours now means their file and --theirs now means your file.  Since the merge is largely symmetric, you the same conflicts and results.  That's why, at least for cases like this, I just like to call them left and right sides.)  So the base, from which your changes sprang, was emptiness.  The base from which their changes sprang was emptiness.  Git always uses a single shared file as the base, so the shared file is this emptiness—and that means that, as far as Git is concerned, it's an "add/add conflict", with all of your lines (creating a file from nothing) conflicting with all of their lines (creating a different version of that file from nothing): Git does not know whether to take your lines, or their lines, or some combination of the two.

It will be up to you, as the person doing the merge, to figure out what to do.  But one of the nice things about having your stuff on your own branch is that you can abort the merge and then start over after making a new commit.  If your xyz.js is completely different from their xyz.js, you can, before merging, rename your xyz.js to, e.g., iter-xyz.js.  Make any other necessary changes, commit the result, and now you're ready to merge—and there's no add/add conflict at all this time, as your iter-xyz.js is added, and their xyz.js is added, and the result is that you have both files in your work-tree and in your merge commit.

Body:
I created an xyz.js file in my local repository. A colleague also created one with the same name.

When I was finished with my work, I tried run the following commands:

git shash
git pull
git stash apply

I've got an aborting message after git pull, because xyz.js was present both in remote and locally, so I tried this:

git stash --all

After that I was able to call git pull, but I was not able to run git stash apply afterwards. I tried to stash it again, and then this:

 rm `git ls-tree -r stash@{1}^3 --name-only`
 git stash apply

There are a lot of ignored files which are needed to run the project, but some of them are still missing. I tried to fix it, but I just made things worse.

I would like to avoid this situation in the future. How should I pull changes and then push my own the right way?

Please do not mark this question as a duplicate. I've found some questions here about asking for which is the preferred way of pull-commit-push, but the answers are not detailed, and they do not mention this problem.


问:
Akka Cluster status Weakly Up
I read Akka document and found this

As mentioned before, if a node is unreachable then gossip convergence is not possible and therefore any leader actions are also not possible. By enabling akka.cluster.allow-weakly-up-members (enabled by default) it is possible to let new joining nodes be promoted while convergence is not yet reached. These Joining nodes will be promoted as WeaklyUp. Once gossip convergence is reached, the leader will move WeaklyUp members to Up.

But it doesn't explain what WeaklyUp status's purpose is. So, please help me to explain what difference is between WeaklyUp and Joining?

答:
The implications of WeaklyUp are application specific. (After all, as you point out, it's configurable whether WeaklyUp is even allowed.) WeaklyUp is a situation that indicates that a new node is in sync with the leader but that all nodes have not yet agreed on the state of new node (because convergence hasn't been reached and therefore a true Up state obtained).

What you do with a node in that state is somewhat up to you. For example, a WeaklyUp node could likely receive incoming traffic from the outside world. Since the WeaklyUp node knows the complete state of the cluster it would know how to handle all incoming requests, even requests that require cluster-aware routing.

Akka Bootstrap (by default), for example, will report a WeaklyUp node as "ready" to Kubernetes. Thereby making the WeaklyUp node eligible to receive incoming traffic. So that's the canonical answer to your question: a WeaklyUp node can receive and process requests and route messages to other nodes in the cluster. It can also receive responses, of course, since remoting works as normal. Another example is that WeaklyUp members are also eligible for cluster-aware routing. Since if the cluster-aware router is aware of the WeaklyUp node, the fact that some other node may not be aware of the WeaklyUp node is moot.

However, as the docs indicate, there are a lot of limitations to WeaklyUp members because not all members have seen the new node and so it can't be allowed to do anything that would depend on convergence: like participating in quorum decisions or sharding.

Title: Akka Cluster status Weakly Up


答:
In the context of Python and all other Object Oriented Programming (OOP) languages, objects have two main characteristics: state and behavior.

You can think of a constructor as a factory that creates an instance of an object with state and behavior.

State - Any instance or class variables associated to that object.

Behavior - Any instance or class methods

The following is an example of a class, in Python, to illustrate some of these concepts.

```<code>class Dog:
    SOUND = 'woof'
    def __init__(self, name):
        """Creates a new instance of the Dog class.

        This is the constructor in Python.
        The underscores are pronounced dunder so this function is called
        dunder init.
        """
        # this is an instance variable.
        # every time you instantiate an object (call the constructor)
        # you must provide a name for the dog
        self._name = name

    def name(self):
        """Gets the name of the dog."""
        return self._name

    @classmethod
    def bork(cls):
        """Makes the noise Dogs do.

        Look past the @classmethod as this is a more advanced feature of Python.
        Just know that this is how you would create a class method in Python.
        This is a little hairy.
        """
        print(cls.SOUND)
</code>```

Though I agree with the comments that this question is a little vague. Please be a little more specific but the answer I've provided is a quick overview of classes and objects in Python.

Title: What is an Object in Python?

Body:
I am surprised that my question was not asked (worded like the above) before. I am hoping that someone could break down this basic term "object" in the context of a OOP language like Python. Explained in a way in which a beginner like myself would be able to grasp.

When I typed my question on Google, the first post that appears is found here.

This is the definition:
An object is created using the constructor of the class. This object will then be called the instance of the class.

Wikipedia defines it like this:
An object is an instance of a Class. Objects are an abstraction. They hold both data, and ways to manipulate the data. The data is usually not visible outside the object.

I am hoping someone could help to break down this vital concept for me, or kindly point me to more resources. Thanks!

Body:
In the context of Python and all other Object Oriented Programming (OOP) languages, objects have two main characteristics: state and behavior.

You can think of a constructor as a factory that creates an instance of an object with state and behavior.

State - Any instance or class variables associated to that object.

Behavior - Any instance or class methods

The following is an example of a class, in Python, to illustrate some of these concepts.

class Dog:
    SOUND = 'woof'
    def __init__(self, name):
        """Creates a new instance of the Dog class.

        This is the constructor in Python.
        The underscores are pronounced dunder so this function is called
        dunder init.
        """
        # this is an instance variable.
        # every time you instantiate an object (call the constructor)
        # you must provide a name for the dog
        self._name = name

    def name(self):
        """Gets the name of the dog."""
        return self._name

    @classmethod
    def bork(cls):
        """Makes the noise Dogs do.

        Look past the @classmethod as this is a more advanced feature of Python.
        Just know that this is how you would create a class method in Python.
        This is a little hairy.
        """
        print(cls.SOUND)

Though I agree with the comments that this question is a little vague. Please be a little more specific but the answer I've provided is a quick overview of classes and objects in Python.


问:
Aligning two HTML objects side by side
I have a color box and some text. I'm trying to align the box exactly left of the text. I'm having issues trying to align it correctly.

I've tried looking at other posts on stack overflow and tried using the float property but couldn't align them correctly because the text goes too far to the right when using the float property. Here is the jsfiddle link if someone wants to run the code : https://jsfiddle.net/1qgep5tn/4/

```<code><!DOCTYPE html>

<html>
<head>

<style>

  .box {
    width: 20px;
    height: 20px;
   }

  .boxColor {
      background: #1c5a7d;
  }

    #right{
      float: right;
    }

    #left{
      float: left;
    }

</style>

</head>
<body>

<div class="box boxColor" ></div>
   Header:
     <br>
          <input type="text" name="firstname"  value="">
     <br>

</body>
</html>
</code>```

I'm expecting the box to be aligned left of the text but it is appearing above the text. Here is an image of what it looks like right now:

答:
With that HTML you are going to have a lot of trouble aligning the items as you want. This is because there is no main container wrapping all of the text content. I would first suggest wrapping your text content in another container, and using a label for the input, such as:

```<code><div class="box boxColor"></div>
<div class="box boxText">
    <label for="firstname">
        <span>Header</span>
        <input type="text" name="firstname" id="firstname"
                value="">
    </label>
 </div>
</code>```

With that structure, you can better apply styling:

```<code>body {
    display: flex;
    flex-direction: row;
}
label > span {
    display: block
}
label > span::after {
    content: ":";
}
.box {
    /* whatever shared styles you might want... */
}
.boxColor {
    background-color: #1c5a7d;
    height: 20px;
    width: 20px;
}
.boxText {
    flex-grow: 1
}
</code>```

Title: Aligning two HTML objects side by side

Body:
I have a color box and some text. I'm trying to align the box exactly left of the text. I'm having issues trying to align it correctly.

I've tried looking at other posts on stack overflow and tried using the float property but couldn't align them correctly because the text goes too far to the right when using the float property. Here is the jsfiddle link if someone wants to run the code : https://jsfiddle.net/1qgep5tn/4/

<!DOCTYPE html>

   Header:

          <input type="text" name="firstname"  value="">

I'm expecting the box to be aligned left of the text but it is appearing above the text. Here is an image of what it looks like right now:

Body:
With that HTML you are going to have a lot of trouble aligning the items as you want. This is because there is no main container wrapping all of the text content. I would first suggest wrapping your text content in another container, and using a label for the input, such as:

<div class="box boxColor"></div>
<div class="box boxText">
    <label for="firstname">
        <span>Header</span>
        <input type="text" name="firstname" id="firstname"
                value="">
    </label>
 </div>

With that structure, you can better apply styling:

body {
    display: flex;
    flex-direction: row;
}
label > span {
    display: block
}
label > span::after {
    content: ":";
}
.box {
    /* whatever shared styles you might want... */
}
.boxColor {
    background-color: #1c5a7d;
    height: 20px;
    width: 20px;
}
.boxText {
    flex-grow: 1
}


问:
Different movements upon Shift+W? It keeps just entering the "W" branch and not letting me exclusively code Shift+W
OK, so I'm trying to make different player animation & speed happen when player hits Shift+W, as opposed to just W.

Here's the working code for just W:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MherControls : MonoBehaviour
{

    float speed = 2;
    float rotSpeed = 80;
    float rot = 0f; //0 when we start the game
    float gravity = 8;

    Vector3 moveDir = Vector3.zero;

    CharacterController controller;
    Animator anim;

    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        //anim condition 0 = idle, 1 = walk, 2 = run

        if (controller.isGrounded)
        {
            if (Input.GetKey(KeyCode.W))
            {
                anim.SetInteger("condition", 1); //changes condition in Animator Controller to 1

                moveDir = new Vector3(0, 0, 1); //only move on the zed axis
                moveDir *= speed;

                moveDir = transform.TransformDirection(moveDir);

                if (speed < 10){
                    speed += Time.deltaTime; //max speed is 10
                    //Debug.Log(speed);
                }
                if (speed >= 2.5)
                {
                    anim.SetInteger("condition", 2);
                }

            }
            if (Input.GetKeyUp(KeyCode.W))
            {
                anim.SetInteger("condition", 0);
                speed = 2;
                moveDir = new Vector3(0, 0, 0);
            }

            rot += Input.GetAxis("Horizontal") * rotSpeed * Time.deltaTime; //horizontal are A and D keys and also left and right arrows
            transform.eulerAngles = new Vector3(0, rot, 0); //our character's transform property

        }
            //every frame move player on y axis by 8. so lowering to the ground
            moveDir.y -= gravity * Time.deltaTime;
            controller.Move(moveDir * Time.deltaTime);
    }
}
</code>```

However, when I try to introduce Shift+W behavior, example:

```<code>if ( (Input.GetKey(KeyCode.W)) && (Input.GetKeyDown(KeyCode.LeftShift)) {
      speed = 2;
      anim.SetInteger("condition", 1);
}
</code>```

Then it doesn't work. It just keeps going into the W branch, and never lets me code behavior exclusively for Shift+W.

What am I doing wrong? How can I make different behavior for when player holds Shift+W, which is different from when player is holding only W?

答:
You need to switch the way you are checking for keys.
GetKeyDown is only true for the frame you press the key (https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html), and GetKey remains true while the key is held down (https://docs.unity3d.com/ScriptReference/Input.GetKey.html). So to hold shift and then press W the check should be</p>

```<code>if ( (Input.GetKey(KeyCode.LeftShift)) && (Input.GetKeyDown(KeyCode.W)) {
      speed = 2;
      anim.SetInteger("condition", 1);
}
</code>```

Body:
OK, so I'm trying to make different player animation & speed happen when player hits Shift+W, as opposed to just W.

Here's the working code for just W:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MherControls : MonoBehaviour
{

    float speed = 2;
    float rotSpeed = 80;
    float rot = 0f; //0 when we start the game
    float gravity = 8;

    Vector3 moveDir = Vector3.zero;

    CharacterController controller;
    Animator anim;

    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        //anim condition 0 = idle, 1 = walk, 2 = run

        if (controller.isGrounded)
        {
            if (Input.GetKey(KeyCode.W))
            {
                anim.SetInteger("condition", 1); //changes condition in Animator Controller to 1

                moveDir = new Vector3(0, 0, 1); //only move on the zed axis
                moveDir *= speed;

                moveDir = transform.TransformDirection(moveDir);

                if (speed < 10){
                    speed += Time.deltaTime; //max speed is 10
                    //Debug.Log(speed);
                }
                if (speed >= 2.5)
                {
                    anim.SetInteger("condition", 2);
                }

            }
            if (Input.GetKeyUp(KeyCode.W))
            {
                anim.SetInteger("condition", 0);
                speed = 2;
                moveDir = new Vector3(0, 0, 0);
            }

            rot += Input.GetAxis("Horizontal") * rotSpeed * Time.deltaTime; //horizontal are A and D keys and also left and right arrows
            transform.eulerAngles = new Vector3(0, rot, 0); //our character's transform property

        }
            //every frame move player on y axis by 8. so lowering to the ground
            moveDir.y -= gravity * Time.deltaTime;
            controller.Move(moveDir * Time.deltaTime);
    }
}

However, when I try to introduce Shift+W behavior, example:

if ( (Input.GetKey(KeyCode.W)) && (Input.GetKeyDown(KeyCode.LeftShift)) {
      speed = 2;
      anim.SetInteger("condition", 1);
}

Then it doesn't work. It just keeps going into the W branch, and never lets me code behavior exclusively for Shift+W.

What am I doing wrong? How can I make different behavior for when player holds Shift+W, which is different from when player is holding only W?

Body:
You need to switch the way you are checking for keys.
GetKeyDown is only true for the frame you press the key (https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html), and GetKey remains true while the key is held down (https://docs.unity3d.com/ScriptReference/Input.GetKey.html). So to hold shift and then press W the check should be

if ( (Input.GetKey(KeyCode.LeftShift)) && (Input.GetKeyDown(KeyCode.W)) {
      speed = 2;
      anim.SetInteger("condition", 1);
}