问:
How to install valgrind on linux
enter image description here

I have basically tried every tutorial out there and still cant run valgrind.

So far....

I installed valgrind from their website to directory 'memcheck'

tar xvf valgrind-3.18.1.tar.bz2

the picture is the outcome of "./configure" ,I cant tell if it was successful or not.

then the command "make" gives: make: *** No targets specified and no makefile found.  Stop.
and the same for "make install"

this is what i tried to do. How to install valgrind properly?

答:
If the output from configure contains "configure: error:" then it failed.

Installing with your package manager will be easiest.

Otherwise, you will need

A C compiler (e.g., gcc or clang), always.
GNU make, always.
Perl, probably always.
Sed and awk, always.

Autotools, m4, if regenerating the configure script.

Lots of packages if you want to generate the docs.

A C++ compiler (g++ or clang++) if you want to build and run the regression tests.

Title: How to install valgrind on linux


来源: stackexchange

问:
how to import JQuery to another html file
I have a html file and in that i have some html and jquery i want to import the jquery to another html file this is my html code ↓↓↓

```<code> <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Register Form Test JQuery</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        var data = "";
        let arr = [];

        $(document).ready(function() {
            var skills = [];
            var subjects = [];

            $("button").click(function() {
                $.each($("input[name='subject']:checked"), function() {
                    subjects.push($(this).val());

                });

                $.each($("input[name='skill']:checked"), function() {
                    skills.push($(this).val());
                });

                var email = $("#email").val();
                var password = $("#password").val();
                var dob = $("#dob").val();
                var gender = $("#gender").val();
                var address = $("#address").val();
                var city = $("#city").val();
                var telephone = $("#telephone").val();
                var aadhaar = $("#aadhaar").val();
                var role = $("#role").val();

                data = "Email: " + email + ", " + "Password: " + password + ", " + "Date Of Birth: " + dob + ", " + "Gender: " + gender + ", " + "Address: " + address + ", " + "City: " + city + ", " + "Subjects: " + subjects.join(", ") + ", " + "Skills: " + skills.join(", ") + ", " + "Telephone Number: " + telephone + ", " + "Aadhaar Number: " + aadhaar + ", " + "Role: " + role;
                arr.push(data);
                console.log(data)
            });
        });
    </script>
</head>

<body>
    <form>
        <label>Email:</label><br>
        <input id="email" type="email" required><br>
        <label>Date Of Birth:</label><br>
        <input id="dob" type="date" required><br>
        <label>Role:</label><br>
        <select id="role" required>
    <option>Learner</option>
    <option>Educator</option>
    <option>Both</option>
    </select><br>
        <label>Gender:</label><br>
        <select id="gender" required>
      <option>Male</option>
      <option>Female</option>
      <option>other</option>
    </select><br>
        <label>Address:</label><br/>
        <input id="address" type="text" required><br/>
        <label>City:</label><br>
        <input id="city" type="text" required><br>
        <label>Subject/s</label><br>
        <label><input type="checkbox" value="Math" name="subject"> Math</label>
        <label><input type="checkbox" value="Science" name="subject"> Science</label>
        <label><input type="checkbox" value="SST" name="subject"> SST</label>
        <label><input type="checkbox" value="English" name="subject"> English</label>
        <label><input type="checkbox" value="Computer Science" name="subject"> Computer Science</label>
        <label><input type="checkbox" value="Kannada" name="subject"> Kannada</label><br>
        <label><input type="checkbox" value="Hindi" name="subject"> Hindi</label><br>
        <label>Skill/s</label>
        <BR>
        <label><input type="checkbox" value="Drawing/Doodling" name="skill"> Drawing/Doodling</label>
        <label><input type="checkbox" value="Instrument Playing" name="skill"> Instrument Playing</label>
        <label><input type="checkbox" value="Dance and/or Music" name="skill"> Dance and/or Music</label>
        <label><input type="checkbox" value="sports (any)" name="skill"> sports (any)</label><br>
        <label>Telephone Number:</label><br>
        <input type="tel" id="telephone" placeholder="1234-567890" pattern="[0-9]{4}-[0-9]{6}"><br>
        <label>Aadhaar Number (if available):</label><br>
        <input id="aadhaar" placeholder="1234-5678-9000" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}"><br>
        <label>Password:</label><br>
        <input type="password" id="password" required><br><br>
        <button type="button" value="submit">Submit</button>
    </form>
</body>

</html>
</code>```

How do i import the jquery script which is in this html file to another html file which also contains jquery? Is there any code which i need to input in my other file or do i need to link it in this html file?

Thanks for your help!

答:
Just copy the code to an external js file and include it in each html file.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="myJQueryScript.js"></script>
</code>```

Just remember to include this after the jquery source file

ContentLicense: CC BY-SA 4.0

Body:
I have a html file and in that i have some html and jquery i want to import the jquery to another html file this is my html code ↓↓↓

 <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Register Form Test JQuery</title>

    <form>
        Email:

        <input id="email" type="email" required>

        Date Of Birth:

        <input id="dob" type="date" required>

        Role:

        <select id="role" required>
    <option>Learner</option>
    <option>Educator</option>
    <option>Both</option>
    </select>

        Gender:

        <select id="gender" required>
      <option>Male</option>
      <option>Female</option>
      <option>other</option>
    </select>

        Address:

        <input id="address" type="text" required>

        City:

        <input id="city" type="text" required>

        Subject/s

        <input type="checkbox" value="Math" name="subject"> Math
        <input type="checkbox" value="Science" name="subject"> Science
        <input type="checkbox" value="SST" name="subject"> SST
        <input type="checkbox" value="English" name="subject"> English
        <input type="checkbox" value="Computer Science" name="subject"> Computer Science
        <input type="checkbox" value="Kannada" name="subject"> Kannada

        <input type="checkbox" value="Hindi" name="subject"> Hindi

        Skill/s

        <input type="checkbox" value="Drawing/Doodling" name="skill"> Drawing/Doodling
        <input type="checkbox" value="Instrument Playing" name="skill"> Instrument Playing
        <input type="checkbox" value="Dance and/or Music" name="skill"> Dance and/or Music
        <input type="checkbox" value="sports (any)" name="skill"> sports (any)

        Telephone Number:

        <input type="tel" id="telephone" placeholder="1234-567890" pattern="[0-9]{4}-[0-9]{6}">

        Aadhaar Number (if available):

        <input id="aadhaar" placeholder="1234-5678-9000" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}">

        Password:

        <input type="password" id="password" required>

        <button type="button" value="submit">Submit</button>
    </form>

How do i import the jquery script which is in this html file to another html file which also contains jquery? Is there any code which i need to input in my other file or do i need to link it in this html file?

Thanks for your help!

Body:
Just copy the code to an external js file and include it in each html file.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="myJQueryScript.js"></script>

Just remember to include this after the jquery source file


问:
Accessing a Custom Configuration Section in .Net
I am trying to access settings in my config file, which is a series of xml elements listed as such:

```<code><databases>
<database name="DatabaseOne" Value="[value]" />
<database name="DatabaseTwo" Value="[value]" />
</databases>
</code>```

Now I want to access it. I have set up classes like so:

```<code>Public Class DatabaseConfigurationHandler
    Inherits ConfigurationSection

    <ConfigurationProperty("Databases", IsDefaultCollection:=True)> _
   Public ReadOnly Property Databases() As DatabaseCollection
        Get
            Return CType(Me("Databases"), DatabaseCollection)
        End Get
    End Property
End Class

Public Class DatabaseCollection
    Inherits ConfigurationElementCollection

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return (New Database())
    End Function

    Protected Overloads Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, Database).DatabaseName)
    End Function

End Class

Public Class Database
    Inherits ConfigurationElement

    <ConfigurationProperty("name", IsKey:=True, IsRequired:=True)> _
       Public Property DatabaseName() As String
        Get
            Return Me("name").ToString()
        End Get
        Set(ByVal Value As String)
            Me("name") = Value
        End Set
    End Property

    <ConfigurationProperty("value", IsRequired:=True)> _
Public Property DatabaseValue() As String
        Get
            Return Me("value").ToString()
        End Get
        Set(ByVal Value As String)
            Me("value") = Value
        End Set
    End Property

End Class
</code>```

I want to be able get the element by it's name and return the value but I can't see to do that:

```<code>Dim config As New DatabaseConfigurationHandler
                config = System.Configuration.ConfigurationManager.GetSection("databases/database")
                Return config.Databases("DatabaseOne")
</code>```

Am I missing some code, what am I doing wrong? Any other errors in the above?

Thanks.

答:
You can use this configuration handler instead.. It will work for ALL custom configuration sections

```<code>   public class XmlConfigurator : IConfigurationSectionHandler
    {
        public object Create(object parent,
                   object configContext, XmlNode section)
        {
            if (section == null)
                throw new ArgumentNullException("section",
                    "Invalid or missing configuration section " +
                    "provided to XmlConfigurator");
            XPathNavigator xNav = section.CreateNavigator();
            if (xNav == null)
                throw new ApplicationException(
                    "Unable to create XPath Navigator");
            Type sectionType = Type.GetType((string)
                (xNav).Evaluate("string(@configType)"));
            XmlSerializer xs = new XmlSerializer(sectionType);
            return xs.Deserialize(new XmlNodeReader(section));
        }
    }
</code>```

Your config file then has to include a reference to the type that the represents the root element

```<code><ConnectionConfig
   configType="MyNamespace.ConnectionConfig, MyNamespace.AssmblyName" >
</code>```

A sample config file might look like this:

```<code><?xml version="1.0" encoding="utf-8" ?>

<ConnectionConfig
   configType="MyNamespace.ConnectionConfig, MyNamespace.AssmblyName" >

  <ConnCompanys>
    <ConnCompany companyName="CompanyNameHere">
      <ConnApps>
        <ConnApp applicationName="Athena" vendorName="Oracle" >
          <ConnSpecs>
            <ConnSpec environments="DEV"
              serverName="Athena"
              port="1521"
              catalog="DatabaseName"
              logon="MyUserName"
              password="%%552355%8234^kNfllceHGp55X5g==" />
     <!--  etc...
</code>```

And you will need to define the classes that each xml element maps to... using the appropriate XmlSerialization attributes ...

```<code>[XmlRoot("ConnectionConfig")]
public class ConnectionConfig
{
    private ConnCompanys comps;

    [XmlArrayItem(ElementName = "ConnCompany")]
    public ConnCompanys ConnCompanys
    {
        get { return comps; }
        set { comps = value; }
    }
    public ConnApp this[string CompanyName, string AppName]
    { get { return ConnCompanys[CompanyName][AppName]; } }

    public ConnSpec this[string CompanyName, string AppName, APPENV env]
    {
        get
        {
            return ConnCompanys[CompanyName][AppName, env];
        }
    }
}

public class ConnCompanys : List<ConnCompany>
{
    public ConnCompany this[string companyName]
    {
        get
        {
            foreach (ConnCompany comp in this)
                if (comp.CompanyName == companyName)
                    return comp;
            return null;
        }
    }
    public bool Contains(string companyName)
    {
        foreach (ConnCompany comp in this)
            if (comp.CompanyName == companyName)
                return true;
        return false;
    }
}

public class ConnCompany
{
    #region private state fields
    private string compNm;
    private ConnApps apps;
    #endregion private state fields

    #region public properties
    [XmlAttribute(DataType = "string", AttributeName = "companyName")]
    public string CompanyName
    {
        get { return compNm; }
        set { compNm = value; }
    }

    [XmlArrayItem(ElementName = "ConnApp")]
    public ConnApps ConnApps
    {
        get { return apps; }
        set { apps = value; }
    }
    #endregion public properties

    #region indexers
    public ConnApp this[string applicationName]
    { get { return ConnApps[applicationName]; } }
    public ConnSpec this[string applicationName, APPENV environment]
    {
        get
        {
            foreach (ConnSpec con in this[applicationName].ConnSpecs)
                if (con.Environment == environment)
                    return con;
            return null;
        }
    }
    #endregion indexers
}
</code>```

etc...

OwnerDisplayName: Damien

ContentLicense: CC BY-SA 2.5

Body:
I am trying to access settings in my config file, which is a series of xml elements listed as such:

<databases>
<database name="DatabaseOne" Value="[value]" />
<database name="DatabaseTwo" Value="[value]" />
</databases>

Now I want to access it. I have set up classes like so:

Public Class DatabaseConfigurationHandler
    Inherits ConfigurationSection

    <ConfigurationProperty("Databases", IsDefaultCollection:=True)> _
   Public ReadOnly Property Databases() As DatabaseCollection
        Get
            Return CType(Me("Databases"), DatabaseCollection)
        End Get
    End Property
End Class

Public Class DatabaseCollection
    Inherits ConfigurationElementCollection

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return (New Database())
    End Function

    Protected Overloads Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, Database).DatabaseName)
    End Function

End Class

Public Class Database
    Inherits ConfigurationElement

    <ConfigurationProperty("name", IsKey:=True, IsRequired:=True)> _
       Public Property DatabaseName() As String
        Get
            Return Me("name").ToString()
        End Get
        Set(ByVal Value As String)
            Me("name") = Value
        End Set
    End Property

    <ConfigurationProperty("value", IsRequired:=True)> _
Public Property DatabaseValue() As String
        Get
            Return Me("value").ToString()
        End Get
        Set(ByVal Value As String)
            Me("value") = Value
        End Set
    End Property

End Class

I want to be able get the element by it's name and return the value but I can't see to do that:

Dim config As New DatabaseConfigurationHandler
                config = System.Configuration.ConfigurationManager.GetSection("databases/database")
                Return config.Databases("DatabaseOne")

Am I missing some code, what am I doing wrong? Any other errors in the above?

Thanks.

Body:
You can use this configuration handler instead.. It will work for ALL custom configuration sections

   public class XmlConfigurator : IConfigurationSectionHandler
    {
        public object Create(object parent,
                   object configContext, XmlNode section)
        {
            if (section == null)
                throw new ArgumentNullException("section",
                    "Invalid or missing configuration section " +
                    "provided to XmlConfigurator");
            XPathNavigator xNav = section.CreateNavigator();
            if (xNav == null)
                throw new ApplicationException(
                    "Unable to create XPath Navigator");
            Type sectionType = Type.GetType((string)
                (xNav).Evaluate("string(@configType)"));
            XmlSerializer xs = new XmlSerializer(sectionType);
            return xs.Deserialize(new XmlNodeReader(section));
        }
    }

Your config file then has to include a reference to the type that the represents the root element

<ConnectionConfig
   configType="MyNamespace.ConnectionConfig, MyNamespace.AssmblyName" >

A sample config file might look like this:

<?xml version="1.0" encoding="utf-8" ?>

<ConnectionConfig
   configType="MyNamespace.ConnectionConfig, MyNamespace.AssmblyName" >

  <ConnCompanys>
    <ConnCompany companyName="CompanyNameHere">
      <ConnApps>
        <ConnApp applicationName="Athena" vendorName="Oracle" >
          <ConnSpecs>
            <ConnSpec environments="DEV"
              serverName="Athena"
              port="1521"
              catalog="DatabaseName"
              logon="MyUserName"
              password="%%552355%8234^kNfllceHGp55X5g==" />
     <!--  etc...

And you will need to define the classes that each xml element maps to... using the appropriate XmlSerialization attributes ...

[XmlRoot("ConnectionConfig")]
public class ConnectionConfig
{
    private ConnCompanys comps;

    [XmlArrayItem(ElementName = "ConnCompany")]
    public ConnCompanys ConnCompanys
    {
        get { return comps; }
        set { comps = value; }
    }
    public ConnApp this[string CompanyName, string AppName]
    { get { return ConnCompanys[CompanyName][AppName]; } }

    public ConnSpec this[string CompanyName, string AppName, APPENV env]
    {
        get
        {
            return ConnCompanys[CompanyName][AppName, env];
        }
    }
}

public class ConnCompanys : List<ConnCompany>
{
    public ConnCompany this[string companyName]
    {
        get
        {
            foreach (ConnCompany comp in this)
                if (comp.CompanyName == companyName)
                    return comp;
            return null;
        }
    }
    public bool Contains(string companyName)
    {
        foreach (ConnCompany comp in this)
            if (comp.CompanyName == companyName)
                return true;
        return false;
    }
}

public class ConnCompany
{
    #region private state fields
    private string compNm;
    private ConnApps apps;
    #endregion private state fields

    #region public properties
    [XmlAttribute(DataType = "string", AttributeName = "companyName")]
    public string CompanyName
    {
        get { return compNm; }
        set { compNm = value; }
    }

    [XmlArrayItem(ElementName = "ConnApp")]
    public ConnApps ConnApps
    {
        get { return apps; }
        set { apps = value; }
    }
    #endregion public properties

    #region indexers
    public ConnApp this[string applicationName]
    { get { return ConnApps[applicationName]; } }
    public ConnSpec this[string applicationName, APPENV environment]
    {
        get
        {
            foreach (ConnSpec con in this[applicationName].ConnSpecs)
                if (con.Environment == environment)
                    return con;
            return null;
        }
    }
    #endregion indexers
}

etc...

OwnerDisplayName: Charles Bretana

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Charles Bretana


问:
How to seralize custom objects into stream (WCF HttpBinding - TransferMode = Streamed)
I would like to know how to serialize custom objects into stream and send the stream via WCF Service. I am thinking to use XMLSerializer and serialize the objects into MemoryStream and pass it to Stream-type parameter of OperationContract method from client and when the request is received from the service, the Stream will be deserialized back to objects.

Your suggestion would be much appreciated!

答:
The Streamed mode it should be used when you want to transfer big data.
The Streamed mode may add some overhead on transport layer.
Also you lose automatically serialization provided by WCF.

UPDATE
XmlSerializer is not good for big data cause it use DOM. DOM parser loads entire xml content in memory and you will lose the benenfits of streaming (generating/consumming chunck by chunck of data).
Binary or Custom Serialization should be your way.
Also, don't forget to apply compression (more details http://social.msdn.microsoft.com/Forums/en-US/dataservices/thread/12557249-2775-44e4-bc39-49585cf15873/)


问:
How to add value on a specific row if there is no value for the cell
I want to add some value like '#Nothing#' to my dataframe if row comes from left-only column and had nothing in the cell or if row comes from right-only column and has nothing in the cell. If something is in the cell, it should be left as it is.

The exercise was to join two dataframes in order to compare. I have used merge function with indicator set to true, so I know which rows come from which dataframe, my problem is how to fill empty cells in such rows with the value I want. If both leave it as it were.

The table looks like this now:

some_name1_A
some_name1_B
some_name2_A
some_name2_B
_merge

One

Three

left_only

Two

Four
right_only

One
Two

Four
both

The table looks should look like this:

some_name1_A
some_name1_B
some_name2_A
some_name2_B
_merge

One
#Nothing#
Three
#Nothing#
left_only

#Nothing#
Two
#Nothing#
Four
right_only

One
Two

Four
both

I had an idea to make few datamframes from the main one like this and then concat them, but I am getting this error:

```<code>data = {'some_name1_A': ['One', None, 'One', None], 'some_name1_B': [None, 'Two', None, 'Two'], 'some_name2_A': ['Three', None, 'Three', None],
        'some_name2_B': [None, 'Four', None, 'Four'], '_merge': ['left_only', 'right_only', 'both', 'right_only']}
df = pd.DataFrame(data)

df_A = df.loc[df_A['_merge'] == 'left_only']
df_A.fillna('#Nothing#', inplace=True)
df_B = df.loc[df_B['_merge'] == 'right_only']
df_B.fillna('#Nothing#', inplace=True)
</code>```

ValueError: Cannot setitem on a Categorical with a new category, set the categories first

答:
Conditionally selecting values. May replace the following with loops.</p>
```<code>df['some_name1_B'] = np.where((df['_merge'] == 'left_only') & df['some_name1_B'].isna(), '#Nothing#', df['some_name1_B'])
df['some_name2_B'] = np.where((df['_merge'] == 'left_only') & df['some_name2_B'].isna(), '#Nothing#', df['some_name2_B'])

df['some_name1_A'] = np.where((df['_merge'] == 'right_only') & df['some_name1_A'].isna(), '#Nothing#', df['some_name1_A'])
df['some_name2_A'] = np.where((df['_merge'] == 'right_only') & df['some_name2_A'].isna(), '#Nothing#', df['some_name2_A'])

some_name1_A    some_name1_B    some_name2_A    some_name2_B    _merge
0   One #Nothing#   Three   #Nothing#   left_only
1   #Nothing#   Two #Nothing#   Four    right_only
2   One None    Three   None    both
3   #Nothing#   Two #Nothing#   Four    right_only
</code>```

Body:
I want to add some value like '#Nothing#' to my dataframe if row comes from left-only column and had nothing in the cell or if row comes from right-only column and has nothing in the cell. If something is in the cell, it should be left as it is.

The exercise was to join two dataframes in order to compare. I have used merge function with indicator set to true, so I know which rows come from which dataframe, my problem is how to fill empty cells in such rows with the value I want. If both leave it as it were.

The table looks like this now:

some_name1_A
some_name1_B
some_name2_A
some_name2_B
_merge

One

Three

left_only

Two

Four
right_only

One
Two

Four
both

The table looks should look like this:

some_name1_A
some_name1_B
some_name2_A
some_name2_B
_merge

One
#Nothing#
Three
#Nothing#
left_only

#Nothing#
Two
#Nothing#
Four
right_only

One
Two

Four
both

I had an idea to make few datamframes from the main one like this and then concat them, but I am getting this error:

data = {'some_name1_A': ['One', None, 'One', None], 'some_name1_B': [None, 'Two', None, 'Two'], 'some_name2_A': ['Three', None, 'Three', None],
        'some_name2_B': [None, 'Four', None, 'Four'], '_merge': ['left_only', 'right_only', 'both', 'right_only']}
df = pd.DataFrame(data)

df_A = df.loc[df_A['_merge'] == 'left_only']
df_A.fillna('#Nothing#', inplace=True)
df_B = df.loc[df_B['_merge'] == 'right_only']
df_B.fillna('#Nothing#', inplace=True)

ValueError: Cannot setitem on a Categorical with a new category, set the categories first

Body:
Conditionally selecting values. May replace the following with loops.

df['some_name1_B'] = np.where((df['_merge'] == 'left_only') & df['some_name1_B'].isna(), '#Nothing#', df['some_name1_B'])
df['some_name2_B'] = np.where((df['_merge'] == 'left_only') & df['some_name2_B'].isna(), '#Nothing#', df['some_name2_B'])

df['some_name1_A'] = np.where((df['_merge'] == 'right_only') & df['some_name1_A'].isna(), '#Nothing#', df['some_name1_A'])
df['some_name2_A'] = np.where((df['_merge'] == 'right_only') & df['some_name2_A'].isna(), '#Nothing#', df['some_name2_A'])

some_name1_A    some_name1_B    some_name2_A    some_name2_B    _merge
0   One #Nothing#   Three   #Nothing#   left_only
1   #Nothing#   Two #Nothing#   Four    right_only
2   One None    Three   None    both
3   #Nothing#   Two #Nothing#   Four    right_only


问:
"Not Authorized to access " error on create mutation + GraphQL
I'm running the below GraphQL query to create data on dynamodb table, but gets the response with "Not Authorized to access createClient on type Client"

Why this is happening at.

GraphQL query:

```<code>`mutation addClient{
  createClient(input:{
    fullName: "Jhon Smith"
    title: "Software Engineer"
    organization: "AWS"
    contactNo: "+341289655524"
    email: "smithj@amazon.com"
    country: "Canada"
    address: "AN/458, Norton place, Down Town"
  }){
    fullName
  }
}`
</code>```

Response :

```<code>{
  "data": {
    "createClient": null
  },
  "errors": [
    {
      "path": [
        "createClient"
      ],
      "data": null,
      "errorType": "Unauthorized",
      "errorInfo": null,
      "locations": [
        {
          "line": 2,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "Not Authorized to access createClient on type Client"
    }
  ]
}
</code>```

答:
It solved with authMode

        const newTodo = await API.graphql({ query: mutations.createClient, variables: {input: inputData}, authMode: "AMAZON_COGNITO_USER_POOLS" });

Body:
I'm running the below GraphQL query to create data on dynamodb table, but gets the response with "Not Authorized to access createClient on type Client"

Why this is happening at.

GraphQL query:

`mutation addClient{
  createClient(input:{
    fullName: "Jhon Smith"
    title: "Software Engineer"
    organization: "AWS"
    contactNo: "+341289655524"
    email: "smithj@amazon.com"
    country: "Canada"
    address: "AN/458, Norton place, Down Town"
  }){
    fullName
  }
}`

Response :

{
  "data": {
    "createClient": null
  },
  "errors": [
    {
      "path": [
        "createClient"
      ],
      "data": null,
      "errorType": "Unauthorized",
      "errorInfo": null,
      "locations": [
        {
          "line": 2,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "Not Authorized to access createClient on type Client"
    }
  ]
}


问:
How to output csv in locust when using as library?
I'm using locust as a library in my Python script (from the example in the docs) and I want to output the stats data into a CSV file. I found out that there is a StatsCSVFileWriter class and created it, but I don't know how to "tell" it to write the file at the end.

Here's my code so far:

def start_locust(time_hh: int, time_mm: int, user: int, spawn_rate: int):
    # setup Environment and Runner
    env = Environment(user_classes=[User])
    env.create_local_runner()

    # CSV writer
    stats_path = os.path.join(os.getcwd(), "data")
    csv_writer = StatsCSVFileWriter(
        environment=env,
        base_filepath=stats_path,
        full_history=True,
        percentiles_to_report=[90.0, 95.0]
    )

    # start a WebUI instance
    env.create_web_ui(host="127.0.0.1", port=8089, stats_csv_writer=csv_writer)

    # start a greenlet that periodically outputs the current stats
    gevent.spawn(stats_printer(env.stats))

    # start a greenlet that saves current stats to history
    gevent.spawn(stats_history, env.runner)

    # start the test
    env.runner.start(user_count=user, spawn_rate=spawn_rate)

    # stop the runner in a given time
    time_in_seconds = (time_hh * 60 * 60) + (time_mm * 60)
    gevent.spawn_later(time_in_seconds, lambda: env.runner.quit())

    # wait for the greenlets
    env.runner.greenlet.join()

    # stop the web server for good measures
    env.web_ui.stop()
```

答:
```<code># Writing all the stats to a CSV file
gevent.spawn(csv_writer.stats_writer)
</code>```


问:
Cocos2dx 3.17.2 Project size over 10 gb After compiling For android
After compiling for Android in Debug and Release APK the compiled files are Taking so much space. is there any way to reduce it?

.ccx is taking 5 gb space and .externalNativeBuild taking 2 gb space

答: The app/build is a temporary folder. You can't really reduce the size of it, but if you only want to save disk space you can delete it without any issues as it will be re-generated next time you build the project, though next build time might be increased because of that.


问:
can't install get_cli flutter
I want to install get_cli but when running the command below, error is found

flutter pub global activate get_cli

the error

Warning: Executable "get" runs "bin/get.dart", which was not found in get_cli.

Warning: Executable "getx" runs "bin/get.dart", which was not found in get_cli.

I have entered the path below to the environment

export PATH="$PATH":"$HOME/.pub-cache/bin"

答: dart pub global activate get_cli</p>

Title: can't install get_cli flutter

Body: dart pub global activate get_cli


问:
Can I force the use of 'this' keyword in c# .NET?
Is there a way to force the use of the this keyword in Visual Studio when referencing current instance members?

Example with a bug in the constructor:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = Foo; // this should of course be lowercase but it's easy to miss
    }
}
</code>```

This code will probably generate the infamous 'object reference not set to an instance of an object' exception somewhere later on.

How to make it work but still It's easy to miss:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = foo; // Valid syntax but unclear.
    }
}
</code>```

This is valid syntax but it's easy to miss.

The syntax I'd like visual studio enforce:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        this.Foo = foo; // this is "safe".
    }
}
</code>```

If this convention is enforced i would have to type this.Foo = this.Foo to create the same type of bug as in the first example.

I always use the this keyword anyway since it makes my life easier while switching between c# and other languages so there wouldn't be any disadvantages at all.

答:
No, you can't change the behaviour of the language like this. If you use ReSharper I believe you can tell it to flag up this sort of thing - it may not come up in the error list, but in the margin and in an "indicator light" for the overall file health.

I personally don't tend to lose too much sleep over this sort of thing, as it's usually obvious as soon as you test - I can only recall one scenario where it's really bitten me, which was when I ended up with a stack overflow (not exactly the same situation, but again a casing issue) within a type initializer, running on Windows Phone 7 - a mixture of difficult debug environments, basically.

Body:
Is there a way to force the use of the this keyword in Visual Studio when referencing current instance members?

Example with a bug in the constructor:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = Foo; // this should of course be lowercase but it's easy to miss
    }
}

This code will probably generate the infamous 'object reference not set to an instance of an object' exception somewhere later on.

How to make it work but still It's easy to miss:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = foo; // Valid syntax but unclear.
    }
}

This is valid syntax but it's easy to miss.

The syntax I'd like visual studio enforce:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        this.Foo = foo; // this is "safe".
    }
}

If this convention is enforced i would have to type this.Foo = this.Foo to create the same type of bug as in the first example.

I always use the this keyword anyway since it makes my life easier while switching between c# and other languages so there wouldn't be any disadvantages at all.


问:
Why is Spring Cloud ignoring my bootstrap-prod.xml?
I have this microservice based on Spring Boot 2.2.7 and it works very well when locally. However when I try to deploy in a Kubernetes cluster, it fails on loading the Config Map values at the startup and, consequently, everything fails from this point:

The container logging is this:

```<code>2022-02-08 14:54:50.696  WARN [myservice,,,] 1 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8761/config/myservice/dev/master": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused
</code>```

I have a bootstrap.yml file like this:

```<code>jhipster:
  registry:
    password: admin

spring:
  application:
    name: myservice
  profiles:
    # The commented value for `active` can be replaced with valid Spring profiles to load.
    # Otherwise, it will be filled in by maven when building the JAR file
    # Either way, it can be overridden by `--spring.profiles.active` value passed in the commandline or `-Dspring.profiles.active` set in `JAVA_OPTS`
    active: #spring.profiles.active#
  cloud:
    config:
      fail-fast: false # if not in "prod" profile, do not force to use Spring Cloud Config
      uri: http://admin:${jhipster.registry.password}@localhost:8761/config
      # name of the config server's property source (file.yml) that we want to use
      name: myservice
      profile: dev # profile(s) of the property source
      label: master # toggle to switch to a different version of the configuration as stored in git
      # it can be set to any label, branch or commit of the configuration source Git repository
</code>```

This is my bootstrap-prod.yml

```<code>spring:
  application:
    name: myservice
  cloud:
    kubernetes:
      config:
        enabled: true # enables fetching configmap
        name: myservice
        profile: prod
        sources:
         - name: myservice
      enabled: true # enables all the sub-configurations
</code>```

It's like when the application starts, Spring Boot just ignored my bootstrap-prod.yml.

The container's environment variable SPRING_PROFILES_ACTIVE value is "prod,swagger,no-liquibase".

答:
I finally found out the cause of this problem.

It's necessary to include this dependency in the pom.xml:

```<code><dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-kubernetes-config</artifactId>
   <version>${spring-cloud-kubernetes.version}</version>
</dependency>
</code>```

In my case it was a little more tricky because I had this dependency already, but it was inside a "prod" profile. So just had to run maven specifying this profile:

```<code>mvn package -P prod
</code>```

Body:
I have this microservice based on Spring Boot 2.2.7 and it works very well when locally. However when I try to deploy in a Kubernetes cluster, it fails on loading the Config Map values at the startup and, consequently, everything fails from this point:

The container logging is this:

2022-02-08 14:54:50.696  WARN [myservice,,,] 1 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8761/config/myservice/dev/master": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused

I have a bootstrap.yml file like this:

jhipster:
  registry:
    password: admin

spring:
  application:
    name: myservice
  profiles:
    # The commented value for `active` can be replaced with valid Spring profiles to load.
    # Otherwise, it will be filled in by maven when building the JAR file
    # Either way, it can be overridden by `--spring.profiles.active` value passed in the commandline or `-Dspring.profiles.active` set in `JAVA_OPTS`
    active: #spring.profiles.active#
  cloud:
    config:
      fail-fast: false # if not in "prod" profile, do not force to use Spring Cloud Config
      uri: http://admin:${jhipster.registry.password}@localhost:8761/config
      # name of the config server's property source (file.yml) that we want to use
      name: myservice
      profile: dev # profile(s) of the property source
      label: master # toggle to switch to a different version of the configuration as stored in git
      # it can be set to any label, branch or commit of the configuration source Git repository

This is my bootstrap-prod.yml

spring:
  application:
    name: myservice
  cloud:
    kubernetes:
      config:
        enabled: true # enables fetching configmap
        name: myservice
        profile: prod
        sources:
         - name: myservice
      enabled: true # enables all the sub-configurations

It's like when the application starts, Spring Boot just ignored my bootstrap-prod.yml.

The container's environment variable SPRING_PROFILES_ACTIVE value is "prod,swagger,no-liquibase".

Body:
I finally found out the cause of this problem.

It's necessary to include this dependency in the pom.xml:

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-kubernetes-config</artifactId>
   <version>${spring-cloud-kubernetes.version}</version>
</dependency>

In my case it was a little more tricky because I had this dependency already, but it was inside a "prod" profile. So just had to run maven specifying this profile:

mvn package -P prod


问:
Rounding to 2 decimal places using MongoDB aggregation framework
I am using the mongodb aggregation framework and doing some calculations as shown below

```<code>db.RptAgg.aggregate(
  {$group: {
    _id: {Region: "$RegionTxt", Mth: "$Month"},
    ActSls: {$sum:"$ActSls"},
    PlnSls: {$sum:"$PlnSls"}
  }},
  {$project: {
    ActSls: 1,
    PlnSls: 1,
    ActToPln: {$cond: [
      {$ne: ["$PlnSls", 0]},
      {$multiply: [{$divide: ['$ActSls', '$PlnSls']}, 100]},
      0
    ]}
  }}
);
</code>```

I am trying to figure out what is the best and easiest way to round my results to 2 decimal places. Following is my result

```<code>{
  "result": [{
    "_id": {
      "Region": "East",
      "Mth": 201301
    },
    "ActSls": 72,
    "PlnSls": 102,
    "ActToPln": 70.58823529411765
  }],
  "ok": 1
}
</code>```

I want "ActToPln" to show 70.59 instead of "ActToPln" : 70.58823529411765, in the results from aggegation framework itself. I want to avoid doing the rounding in my application

Can you please help with the same.

Following is the dataset i used.

```<code>{
    "_id" : ObjectId("51d67ef69557c507cb172572"),
    "RegionTxt" : "East",
    "Month" : 201301,
    "Date" : "2013-01-01",
    "ActSls" : 31,
    "PlnSls" : 51
}
{
    "_id" : ObjectId("51d67ef69557c507cb172573"),
    "RegionTxt" : "East",
    "Month" : 201301,
    "Date" : "2013-01-02",
    "ActSls" : 41,
    "PlnSls" : 51
}
</code>```

Thanks in advance.
Nandu

答:
Watch out for issues with the $round aggregation. When working with double type will sometimes round incorrectly. Here is an example:

5.885 --to double--> 5.8849999999999 ---$round(2)--> 5.88 (instead of 5.89)

Here is a workaround:

```<code>> db.a.save({x:5.884})
> db.a.save({x:5.885})
> db.a.save({x:5.886})
> db.a.aggregate([{
     $project:{
         _id:0,
         x: '$x',
         round: {$round: ['$x', 2]}
         better_round: {$round: [{$add: ['$x', 0.000000001]}, 2]}
     }
}])
Output:
{ "x" : 5.884, "round" : 5.88, "better_round" : 5.88 }
{ "x" : 5.885, "round" : 5.88, "better_round" : 5.89 }
{ "x" : 5.886, "round" : 5.89, "better_round" : 5.89 }
</code>```

Body:
I am using the mongodb aggregation framework and doing some calculations as shown below

db.RptAgg.aggregate(
  {$group: {
    _id: {Region: "$RegionTxt", Mth: "$Month"},
    ActSls: {$sum:"$ActSls"},
    PlnSls: {$sum:"$PlnSls"}
  }},
  {$project: {
    ActSls: 1,
    PlnSls: 1,
    ActToPln: {$cond: [
      {$ne: ["$PlnSls", 0]},
      {$multiply: [{$divide: ['$ActSls', '$PlnSls']}, 100]},
      0
    ]}
  }}
);

I am trying to figure out what is the best and easiest way to round my results to 2 decimal places. Following is my result

{
  "result": [{
    "_id": {
      "Region": "East",
      "Mth": 201301
    },
    "ActSls": 72,
    "PlnSls": 102,
    "ActToPln": 70.58823529411765
  }],
  "ok": 1
}

I want "ActToPln" to show 70.59 instead of "ActToPln" : 70.58823529411765, in the results from aggegation framework itself. I want to avoid doing the rounding in my application

Can you please help with the same.

Following is the dataset i used.

{
    "_id" : ObjectId("51d67ef69557c507cb172572"),
    "RegionTxt" : "East",
    "Month" : 201301,
    "Date" : "2013-01-01",
    "ActSls" : 31,
    "PlnSls" : 51
}
{
    "_id" : ObjectId("51d67ef69557c507cb172573"),
    "RegionTxt" : "East",
    "Month" : 201301,
    "Date" : "2013-01-02",
    "ActSls" : 41,
    "PlnSls" : 51
}

Thanks in advance.
Nandu

Body:
Watch out for issues with the $round aggregation. When working with double type will sometimes round incorrectly. Here is an example:

5.885 --to double--> 5.8849999999999 ---$round(2)--> 5.88 (instead of 5.89)

Here is a workaround:

> db.a.save({x:5.884})
> db.a.save({x:5.885})
> db.a.save({x:5.886})
> db.a.aggregate([{
     $project:{
         _id:0,
         x: '$x',
         round: {$round: ['$x', 2]}
         better_round: {$round: [{$add: ['$x', 0.000000001]}, 2]}
     }
}])
Output:
{ "x" : 5.884, "round" : 5.88, "better_round" : 5.88 }
{ "x" : 5.885, "round" : 5.88, "better_round" : 5.89 }
{ "x" : 5.886, "round" : 5.89, "better_round" : 5.89 }


问:
How to open a file from CLI using a text editor of my choice, if the name of application has multiple strings?
Im learning to use hyper terminal for my web development. I need to open a file directly from CLI using VSCode.
For opening it using notepad++ i can open it by writing

```<code>start Notepad++ filename.ext
</code>```

But i want to open it with Visual studio code.For which i wrote

```<code>start Visual studio Code filename.ext
</code>```

The name of vscode is shown as Visual studio Code in apps. Since it has multiple strings im getting error. how do i bind the name of application together.
Incase if i want to open through atom i write,it works fine.

```<code>start Atom filename.ext
</code>```

How do i make it work.

答: To open Visual Studio code from your Hyper Terminal, just type: code .

Body:
Im learning to use hyper terminal for my web development. I need to open a file directly from CLI using VSCode.
For opening it using notepad++ i can open it by writing

start Notepad++ filename.ext

But i want to open it with Visual studio code.For which i wrote

start Visual studio Code filename.ext

The name of vscode is shown as Visual studio Code in apps. Since it has multiple strings im getting error. how do i bind the name of application together.
Incase if i want to open through atom i write,it works fine.

start Atom filename.ext

How do i make it work.


问:
Parsing outlook .msg files with python
Looked around and couldn't find a satisfactory answer. Does anyone know how to parse .msg files from outlook with Python?

I've tried using mimetools and email.parser with no luck. Help would be greatly appreciated!

答:
The extract-msg Python module (pip install extract-msg) is also extremely useful because it allows quick access to the full headers from the message, something that Outlook makes much harder than necessary to get hold of.

My modification of Vladimir's code that shows full headers is:

```<code>#!/usr/bin/env python3

import extract_msg
import sys

msg = extract_msg.Message(sys.argv[1])
msg_sender = msg.sender
msg_date = msg.date
msg_subj = msg.subject

print('Sender: {}'.format(msg_sender))
print('Sent On: {}'.format(msg_date))
print('Subject: {}'.format(msg_subj))

print ("=== Details ===")

for k, v in msg.header.items():
    print("{}: {}".format(k, v))

print(msg.body)
</code>```

Title: Parsing outlook .msg files with python

Body:
The extract-msg Python module (pip install extract-msg) is also extremely useful because it allows quick access to the full headers from the message, something that Outlook makes much harder than necessary to get hold of.

My modification of Vladimir's code that shows full headers is:

#!/usr/bin/env python3

import extract_msg
import sys

msg = extract_msg.Message(sys.argv[1])
msg_sender = msg.sender
msg_date = msg.date
msg_subj = msg.subject

print('Sender: {}'.format(msg_sender))
print('Sent On: {}'.format(msg_date))
print('Subject: {}'.format(msg_subj))

print ("=== Details ===")

for k, v in msg.header.items():
    print("{}: {}".format(k, v))

print(msg.body)


问:
How to use Camera in flutter Windows
I want to use the camera in the flutter windows and also has a library for Android but not for Windows. I did not get any results from Google.</p>

答: There was a problem with my system drivers, and after updating the drivers, the problem was fixed and the program worked without any problems.</p>

Title: How to use Camera in flutter Windows


问:
How to use an existing DB for unit testing in Django?
I have created a REST-API application using Django Rest Framework.

The API just converts the data from an existing Read-only Postgres DB to a REST- API to be consumed by the front-end.

Now I need to write some unit tests to test the application. Since there are lots of tables and views involved, I cannot create mock data and test.

Is there a way to run the tests in Django using the existing DB (Postgres) without creating any mock data ?

Note: I have read a lot of SO posts related to my problem but none of them worked as they were for old versions of Django.

答:
You could do something like this in your settings.py</p>
```<code>import sys
if 'test' in sys.argv:
    DATABASES['default'] = {
        # your default database credentials
    }
</code>```

Body:
You could do something like this in your settings.py

import sys
if 'test' in sys.argv:
    DATABASES['default'] = {
        # your default database credentials
    }


问:
Can you start AI platform jobs from HTTP requests?
I have a web app (react + node.js) running on App Engine.

I would like to kick off (from this web app) a Machine Learning job that requires a GPU (running in a container on AI platform or running on GKE using a GPU node pool like in this tutorial, but we are open to other solutions).

I was thinking of trying what is described at the end of this answer, basically making an HTTP request to start the job using project.job.create API.

More details on the ML job in case this is useful: it generates an output every second that is stored on Cloud Storage and then read in the web app.

I am looking for examples of how to set this up? Where would the job configuration live and how should I set up the API call to kick off that job? Are the there other ways to achieve the same result?

Thank you in advance!

答:
On Google Cloud, all is API, and you can interact with all the product with HTTP request. SO you can definitively achieve what you want.

I personally haven't an example but you have to build a JSON job description  and post it to the API.

Don't forget, when you interact with Google Cloud API, you have to add an access token in the Authorization: Bearer header

Where should be your job config description? It depends...

If it is strongly related to your App Engine app, you can add it in App Engine code itself and have it "hard coded". The downside of that option is anytime you have to update the configuration, you have to redeploy a new App Engine version. But if your new version isn't correct, a rollback to a previous and stable version is easy and consistent.

If you prefer to update differently your config file and your App Engine code, you can store the config out of App Engine code, on Cloud Storage for instance. Like that, the update is simple and easy: update the config on Cloud Storage to change the job configuration. However there is no longer relation between the App Engine version and the config version. And the rollback to a stable version can be more difficult.

You can also have a combination of both, where you have a default job configuration in your App Engine code, and an environment variable potentially set to point to a Cloud Storage file that contain a new version of the configuration.

I don't know if it answers all your questions. Don't hesitate to comment if you want more details on some parts.


问:
Email field is accepting emojis
I'm using RegExp to validate email in one of my Flutter projects. Apparently, I'm able to insert, both by typing and copy-pasting, emojis in the email field. Below is the code for the email field:

```<code>Container(
  child: Theme(
    data: ThemeData(
        primaryColor: backgroundColor,
        hintColor: hintTextColor,
        primarySwatch: backgroundColorMaterial),
    child: TextFormField(
      controller: provider.emailController,
      border: outlineBorderGrey,
      hintText: Translations.of(context).getEmail,
      labelText: Translations.of(context).getEmail,
      prefixIcon: IconButton(
        icon: provider.emailvalid ? emailFieldLogo : emailFieldLogoRed,
      ),
    ),
    inputFormatters: [ValidateHelper.emailRegex],
    keyboardType: TextInputType.emailAddress,
  ),
),
</code>```

);

The inputFormatter that I'm using is also a RegExp:

```<code>static TextInputFormatter emailRegex = BlacklistingTextInputFormatter(RegExp(r'[!$#<>?":` ~;[\]\\|=+)(*&^%A-Z]'));
</code>```

After finishing the form, when I'm applying validation check on the email, the emojis are being accepted as valid input as well. The code for email validation is as follows:

```<code>bool isEmailValid(BuildContext context, String email) {
    Pattern patternEmail =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regexEmail = new RegExp(patternEmail);
    if (!regexEmail.hasMatch(email)) {
      return false;
    }
    if (email.isEmpty) {
      return false;
    }
    return true;
  }
</code>```

Is there any problem in the Regex pattern? Did I miss something out?

答: Emojis are nothing but Characters. A  is U+1F601 in Unicode. And that Unicode is allowed with your Regex. You can restrict Here is a question about restricting Emojis in a Textfield. Maybe that helps :)

Title: Email field is accepting emojis

Body:
I'm using RegExp to validate email in one of my Flutter projects. Apparently, I'm able to insert, both by typing and copy-pasting, emojis in the email field. Below is the code for the email field:

Container(
  child: Theme(
    data: ThemeData(
        primaryColor: backgroundColor,
        hintColor: hintTextColor,
        primarySwatch: backgroundColorMaterial),
    child: TextFormField(
      controller: provider.emailController,
      border: outlineBorderGrey,
      hintText: Translations.of(context).getEmail,
      labelText: Translations.of(context).getEmail,
      prefixIcon: IconButton(
        icon: provider.emailvalid ? emailFieldLogo : emailFieldLogoRed,
      ),
    ),
    inputFormatters: [ValidateHelper.emailRegex],
    keyboardType: TextInputType.emailAddress,
  ),
),

);

The inputFormatter that I'm using is also a RegExp:

static TextInputFormatter emailRegex = BlacklistingTextInputFormatter(RegExp(r'[!$#<>?":` ~;[\]\\|=+)(*&^%A-Z]'));

After finishing the form, when I'm applying validation check on the email, the emojis are being accepted as valid input as well. The code for email validation is as follows:

bool isEmailValid(BuildContext context, String email) {
    Pattern patternEmail =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regexEmail = new RegExp(patternEmail);
    if (!regexEmail.hasMatch(email)) {
      return false;
    }
    if (email.isEmpty) {
      return false;
    }
    return true;
  }

Is there any problem in the Regex pattern? Did I miss something out?


问:
How to calculate the sum of numbers in deeply nested array of objects using JavaScript?
I just started learning JavaScript, and ran into such a problem, I have a nested array, I want to summarize the price value of these arrays and return the existing sum, I wonder which method is applicable for it, which does not hurt the performance, I need one example to understand the way to solve the problem. Thanks in advance

const initialData = [
      {
          title: 'm2212',
          data: [
              {
                  id: 98233181232,
                  variations:[{
                          warranty: '',
                          price: 120,
                          comment: '',
                      }]

              },
          ]
      },
      {
          title: 'm2',
          data: [
              {
                  id: 982812,
                  variations:[{
                          warranty: '',
                          price: 92,
                          comment: '',
                      }]

              },
               {
                  id: 92182812,
                  variations:[{
                          warranty: '',
                          price: 922,
                          comment: '',
                      }]

              },
          ]
      },
 ]

 //what i tried
 let sum = 0
 initialData.forEach((el)=>{
   el.data.forEach((el1)=>{
     sum = sum + el1.variations[0].price
    })
 })

 console.log(sum);```

答:
Your data structure looks pretty simple, so I'll just explain in plain english how to accomplish it:

The simple straight forward way is to ignore all the fancy functional things you can do on arrays, and just do this:

Set a sum variable equal to 0. Iterate over every element of initialData. On each element, iterate over every element of data. On each data element, iterate over every element of variations. Add the price property to your sum variable.


答:
Reproducible example:

```<code>df = pd.DataFrame({'A': ['One', np.nan, 'One'],
                   'B': ['Two', 'Two', np.nan]}, dtype='category')
print(df.dtypes)
print(df)

# Output:
A    category
B    category
dtype: object

     A    B
0  One  Two
1  NaN  Two
2  One  NaN
</code>```

Now if you fill missing values:

```<code>>>> df.fillna('#Nothing#')
...
ValueError: Cannot setitem on a Categorical with a new category, set the categories first
</code>```

How to fix this? Add the new category before filling missing values:

```<code>cols = df.select_dtypes('category').columns
df[cols] = df[cols].apply(lambda x: x.cat.add_categories('#Nothing#'))
</code>```
```<code>>>> df.fillna('#Nothing#')
           A          B
0        One        Two
1  #Nothing#        Two
2        One  #Nothing#
</code>```

Title: How to add value on a specific row if there is no value for the cell

Body:
Reproducible example:

df = pd.DataFrame({'A': ['One', np.nan, 'One'],
                   'B': ['Two', 'Two', np.nan]}, dtype='category')
print(df.dtypes)
print(df)

# Output:
A    category
B    category
dtype: object

     A    B
0  One  Two
1  NaN  Two
2  One  NaN

Now if you fill missing values:

>>> df.fillna('#Nothing#')
...
ValueError: Cannot setitem on a Categorical with a new category, set the categories first

How to fix this? Add the new category before filling missing values:

cols = df.select_dtypes('category').columns
df[cols] = df[cols].apply(lambda x: x.cat.add_categories('#Nothing#'))

>>> df.fillna('#Nothing#')
           A          B
0        One        Two
1  #Nothing#        Two
2        One  #Nothing#


问:
How to add fixed width image view in center horizontal using constraint layout

Hello guys, I need to add 2 fixed width and height imageview in to center of screen using constraint layout how we can achieve something like this.

xml layout

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activity.profile.view.UserDetailsActivity">

    <TextView
        android:id="@+id/tv_label"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:gravity="center"
        android:text="@string/you_are"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent=".1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintWidth_percent=".25" />

    <CircularImageView
        android:id="@+id/iv_farmer"
        android:layout_width="@dimen/_100dp"
        android:layout_height="@dimen/_100dp"
        android:src="@drawable/ic_profilewithimage"
        app:civ_border="true"
        app:civ_border_color="#e4e4e4"
        app:civ_border_width="@dimen/_1dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="@+id/iv_prof"
        app:layout_constraintTop_toBottomOf="@+id/tv_label" />

    <CircularImageView
        android:id="@+id/iv_prof"
        android:layout_width="@dimen/_100dp"
        android:layout_height="@dimen/_100dp"
        android:src="@drawable/ic_profilewithimage"
        app:civ_border="true"
        app:civ_border_color="#e4e4e4"
        app:civ_border_width="@dimen/_1dp"
        app:layout_constraintLeft_toRightOf="@+id/iv_farmer"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_label" />

</android.support.constraint.ConstraintLayout>
</code>```

i am trying this but views are not centerd.

答:
It worked for me using bias:

```<code><androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/img_splash_logo"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/weather_logo"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
Hello guys, I need to add 2 fixed width and height imageview in to center of screen using constraint layout how we can achieve something like this.

xml layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activity.profile.view.UserDetailsActivity">

    <TextView
        android:id="@+id/tv_label"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:gravity="center"
        android:text="@string/you_are"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent=".1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintWidth_percent=".25" />

    <CircularImageView
        android:id="@+id/iv_farmer"
        android:layout_width="@dimen/_100dp"
        android:layout_height="@dimen/_100dp"
        android:src="@drawable/ic_profilewithimage"
        app:civ_border="true"
        app:civ_border_color="#e4e4e4"
        app:civ_border_width="@dimen/_1dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="@+id/iv_prof"
        app:layout_constraintTop_toBottomOf="@+id/tv_label" />

    <CircularImageView
        android:id="@+id/iv_prof"
        android:layout_width="@dimen/_100dp"
        android:layout_height="@dimen/_100dp"
        android:src="@drawable/ic_profilewithimage"
        app:civ_border="true"
        app:civ_border_color="#e4e4e4"
        app:civ_border_width="@dimen/_1dp"
        app:layout_constraintLeft_toRightOf="@+id/iv_farmer"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_label" />

</android.support.constraint.ConstraintLayout>

i am trying this but views are not centerd.

Body:
It worked for me using bias:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/img_splash_logo"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/weather_logo"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Cookies with iframe: SameSite = None not working on server
I am working on an ASPX page which works with iFrame. After chrome v80 upgrade the site was not working.
I made below changes in ASP.NET .cs page to set samesite attribute.

Now the fix is working on my DEV and UAT servers. But it still failing in PROD servers.
Below are the screen shot of cookies from UAT and PROD. Whereas the same code is deployed on both the servers.

Please provide possible root cause, looks like cookies attribute is getting overwrite.

Code:

```<code>HttpCookie cookie = Cookie.CreateCookie(a_sAuthenticationGuid, a_objContext, uData.SUID);
cookie.SameSite = SameSiteMode.None;
cookie.Secure = true;
</code>```

PROD:
PROD Cookies snapshot

UAT:
UAT Cookies snapshot

答:
I had to change the samesite setting in chrome to get this resolved and after updating chrome setting for samesite, its working.
search for samesite on cookies://flags</p>

Body:
I am working on an ASPX page which works with iFrame. After chrome v80 upgrade the site was not working.
I made below changes in ASP.NET .cs page to set samesite attribute.

Now the fix is working on my DEV and UAT servers. But it still failing in PROD servers.
Below are the screen shot of cookies from UAT and PROD. Whereas the same code is deployed on both the servers.

Please provide possible root cause, looks like cookies attribute is getting overwrite.

Code:

HttpCookie cookie = Cookie.CreateCookie(a_sAuthenticationGuid, a_objContext, uData.SUID);
cookie.SameSite = SameSiteMode.None;
cookie.Secure = true;

PROD:
PROD Cookies snapshot

UAT:
UAT Cookies snapshot


问:
Cannot include the given value in a string template: string required
Does someone have experience in building a Packer ec2 with Terraform and can assist me?
Basically, I am getting this error for a "null_resource" that represent Packer

```<code>   │ Error: Invalid template interpolation value
│
│   on asg.tf line 14, in resource "null_resource" "packer":
│    7:     command = <<EOF
│    8: packer build \
│    9:   -var region=${var.region} \
│   10:   -var vpc_id=${module.vpc.vpc_id} \
│   11:   -var subnet_id="${module.vpc.private_subnets[0]}" \
│   12:   -var instance_type=${var.instance_type} \
│   13:   -var ami_name=${var.ami_name} \
│   14:   -var source_ami=${data.aws_ami.search} \
│   15:   -var image_path=${local.image_complete_path} \
│   16:   template.json
│   17: EOF
│     ├────────────────
│     │ data.aws_ami.search is object with 34 attributes
│
│ Cannot include the given value in a string template: string required.
</code>```

Would love some help here, thank you all!

答:
The error message is pretty expressive:

data.aws_ami.search is object with 34 attributes

You need a single value, so you need a way to filter the attributes.

As per Terraform documentation for the aws_ami data source [1], you probably want the name attribute so the value you should look for is:

```<code>data.aws_ami.search.name
</code>```

If you need the AMI ID, then you should use:

```<code>data.aws_ami.search.id
</code>```

This is the same as using data.aws_ami.search.image_id [2].

[1] https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/ami#name

[2] https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/ami#image_id

Body:
Does someone have experience in building a Packer ec2 with Terraform and can assist me?
Basically, I am getting this error for a "null_resource" that represent Packer

   │ Error: Invalid template interpolation value
│
│   on asg.tf line 14, in resource "null_resource" "packer":
│    7:     command = <<EOF
│    8: packer build \
│    9:   -var region=${var.region} \
│   10:   -var vpc_id=${module.vpc.vpc_id} \
│   11:   -var subnet_id="${module.vpc.private_subnets[0]}" \
│   12:   -var instance_type=${var.instance_type} \
│   13:   -var ami_name=${var.ami_name} \
│   14:   -var source_ami=${data.aws_ami.search} \
│   15:   -var image_path=${local.image_complete_path} \
│   16:   template.json
│   17: EOF
│     ├────────────────
│     │ data.aws_ami.search is object with 34 attributes
│
│ Cannot include the given value in a string template: string required.

Would love some help here, thank you all!

Body:
The error message is pretty expressive:

data.aws_ami.search is object with 34 attributes

You need a single value, so you need a way to filter the attributes.

As per Terraform documentation for the aws_ami data source [1], you probably want the name attribute so the value you should look for is:

data.aws_ami.search.name

If you need the AMI ID, then you should use:

data.aws_ami.search.id

This is the same as using data.aws_ami.search.image_id [2].

[1] https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/ami#name

[2] https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/ami#image_id


问:
How to compare given value with Pandas dataframe values without using a for loop
I have the following example dataframe:

```<code>d = {'target': [1, 2, 4, 3, 6, 5]}
df = pd.DataFrame(data=d)
df
</code>```

Output:

```<code>    target
0   1
1   2
2   4
3   3
4   6
5   5
</code>```

I need a function that will do the following:

Let the function have the name find_index_of_first_hit(value).

The function...

will be comparing the function input value with elements of the column target.

will search for the first column value that is greater than or equal to the function input value.

and will return the index of the dataframe row for the very first match.

Example:

```<code>find_index_of_first_hit(3)
</code>```

Should return 2 which is the index of the target column value 4, which is where the column value (which is 4) is >= the function input value 3 for the first time in the column. And the index is 2, which is expected to be returned.

The function is expected to return -1 if none of column values are >= the function input value.

The original dataframe is fairly large and I wonder how I can write such a program without using for loop.

This function needs to be written in Python and it needs to be a fast solution, which is why I would like to avoid for loop. Performance is important here.

How can I write such a Python function doing this work?

答:
use an equality check .eq with idxmax

You'll find you rarely need to write any functions for Pandas (unless you need to package up reusable code snippets) as most things are available in the API.

```<code>index = df.ge(3).idxmax()

target    2
dtype: int64
</code>```

Body:
I have the following example dataframe:

d = {'target': [1, 2, 4, 3, 6, 5]}
df = pd.DataFrame(data=d)
df

Output:

    target
0   1
1   2
2   4
3   3
4   6
5   5

I need a function that will do the following:

Let the function have the name find_index_of_first_hit(value).

The function...

will be comparing the function input value with elements of the column target.

will search for the first column value that is greater than or equal to the function input value.

and will return the index of the dataframe row for the very first match.

Example:

find_index_of_first_hit(3)

Should return 2 which is the index of the target column value 4, which is where the column value (which is 4) is >= the function input value 3 for the first time in the column. And the index is 2, which is expected to be returned.

The function is expected to return -1 if none of column values are >= the function input value.

The original dataframe is fairly large and I wonder how I can write such a program without using for loop.

This function needs to be written in Python and it needs to be a fast solution, which is why I would like to avoid for loop. Performance is important here.

How can I write such a Python function doing this work?

Body:
use an equality check .eq with idxmax

You'll find you rarely need to write any functions for Pandas (unless you need to package up reusable code snippets) as most things are available in the API.

index = df.ge(3).idxmax()

target    2
dtype: int64


问:
CSS pseudo element positioning - partial border above header
I am struggling to position the partial border directly above the title without the title floating to the left of the 'before' pseudo element.  It works fine on pages without an image but I need the title and text to wrap around the image on some pages where an image exists but not on others and this is causing the issue.

I have tried absolute positioning, different displays but nothing works.

https://codepen.io/lol4000/pen/dyZvmGK

```<code> <img width="420" height="195" src="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="PIM" srcset="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg 420w, https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS-300x139.jpg 300w" sizes="(max-width: 420px) 100vw, 420px">            <h2 class="sub-title">Test English subtitle</h2><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.</p> <p>Donec mattis vulputate tellus, vel tincidunt purus condimentum vel. </p>Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis. <p>In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus. </p><p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.</p> <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p><p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.</p> <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>

h2.sub-title {font-size:28px;display: block;}
h2.sub-title::before{ position: relative; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}

.wp-post-image {
    float: left;
    margin: 0 15px 10px 0;}
</code>```

答:
As far I understood, I've created an alternate solution rather than pesudo element. please check it out and let me know.

.image-text{display: flex; flex-direction:row; flex-wrap: wrap;}
.heading{posittion: relative;}
h2.sub-title {font-size:28px;position: relative;}
.border{ position: relative; height: 8px;width: 130px; top: 17px;background: #441A6D; display: inline-block; }

.wp-post-image {
    margin: 0 15px 10px 0;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-text">
  <div class="image"><img width="420" height="195" src="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="PIM" srcset="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg 420w, https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS-300x139.jpg 300w" sizes="(max-width: 420px) 100vw, 420px">
  </div>
  <div class="heading">
    <span class="border"></span>
    <h2 class="sub-title">Test English subtitle</h2>

  </div>
</div></code>```

Body:
I am struggling to position the partial border directly above the title without the title floating to the left of the 'before' pseudo element.  It works fine on pages without an image but I need the title and text to wrap around the image on some pages where an image exists but not on others and this is causing the issue.

I have tried absolute positioning, different displays but nothing works.

https://codepen.io/lol4000/pen/dyZvmGK

Test English subtitle

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.

Donec mattis vulputate tellus, vel tincidunt purus condimentum vel.
Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis.
In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus.

Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.

Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.

Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.

Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.

h2.sub-title {font-size:28px;display: block;}
h2.sub-title::before{ position: relative; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}

.wp-post-image {
    float: left;
    margin: 0 15px 10px 0;}

Body:
As far I understood, I've created an alternate solution rather than pesudo element. please check it out and let me know.

.image-text{display: flex; flex-direction:row; flex-wrap: wrap;}
.heading{posittion: relative;}
h2.sub-title {font-size:28px;position: relative;}
.border{ position: relative; height: 8px;width: 130px; top: 17px;background: #441A6D; display: inline-block; }

.wp-post-image {
    margin: 0 15px 10px 0;}

<div class="image-text">
  <div class="image"><img width="420" height="195" src="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="PIM" srcset="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg 420w, https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS-300x139.jpg 300w" sizes="(max-width: 420px) 100vw, 420px">
  </div>
  <div class="heading">
    <span class="border"></span>
    <h2 class="sub-title">Test English subtitle</h2>

  </div>
</div>


问:
Why python file in virtual environment is carrying the same installation date after deleting the previous one?
I'm deleting the virtual environment and creating it again and again but in bin, the python and python3 file is not recreating. It's showing the installation time of those 2 files are the same as the first time it was installed.
why is this happening? as I'm deleting it completely but again those 2 files carry the same installation time.

答:
The files have been copied from the base Python installation and carries the modification time from there.

The files' modification times shouldn't cause any "problems in selecting interpreters".


问:
How to enable unicode when compiling using cl.exe from Visual Studio Build Tools?
I'm trying to have unicode characters in WIN32 (winapi, no console) program compiled using cl.exe from Visual Studio Build Tools. I've defined UNICODE and _UNICODE in my program source and also using cmd option, but I still don't get unicode characters. Here is my compilation command line: cl C:\path_to_source\preventShutdown.c kernel32.lib user32.lib /DUNICODE /D_UNICODE /O2 /link /NODEFAULTLIB /ENTRY:wWinMain and my source code:

/*
cl C:\path_to_source\preventShutdown.c kernel32.lib user32.lib /DUNICODE /D_UNICODE /O2 /link /NODEFAULTLIB /ENTRY:wWinMain
*/
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <windows.h>
LRESULT CALLBACK WindowProc(HWND,UINT,WPARAM,LPARAM);
int WINAPI wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPWSTR lpCmdLine,int nShowCmd)
{
LPCTSTR windowClassName=TEXT("windowClass"),windowName=TEXT("Zatrzymaj wyłączenie");
WNDCLASS windowClass={0};
windowClass.hInstance=hInstance;
windowClass.hIcon=NULL;
windowClass.hCursor=LoadCursor(NULL,IDC_ARROW);
windowClass.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
windowClass.lpszMenuName=NULL;
windowClass.lpszClassName=windowClassName;
windowClass.lpfnWndProc=&WindowProc;
if(!RegisterClass(&windowClass))return -1;
HWND hWnd=NULL;
if(!(hWnd=CreateWindow(windowClassName,windowName,WS_OVERLAPPEDWINDOW|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,NULL,NULL)))return -2;
MSG msg={0};
int bRet=0;
while((bRet=GetMessage(&msg,NULL,0,0))!=0)
{
 if(-1==bRet)return -3;
 TranslateMessage(&msg);
 DispatchMessage(&msg);
}
ExitProcess((UINT)msg.wParam);
return (int)msg.wParam;
}

LRESULT CALLBACK WindowProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
switch(msg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_QUERYENDSESSION:
ShutdownBlockReasonCreate(hWnd,TEXT("Rozpoczęto przez użytkownika"));
break;
case WM_ENDSESSION:
return 0;
break;
default:
return DefWindowProc(hWnd,msg,wParam,lParam);
break;
}
return 0;
}
```

- where path_to_source is real path to source code.

答: Like @Hans Passant stated it the comment, problem was that compiler doesn't recognize my source file as unicode. Saving a file with BOM or adding /source-charset:utf-8 option makes it work correctly. I prefer the second option:  cl /source-charset:utf-8 C:\path_to_source\preventShutdown.c kernel32.lib user32.lib /DUNICODE /D_UNICODE /O2 /link /NODEFAULTLIB /ENTRY:wWinMain

Body:
I'm trying to have unicode characters in WIN32 (winapi, no console) program compiled using cl.exe from Visual Studio Build Tools. I've defined UNICODE and _UNICODE in my program source and also using cmd option, but I still don't get unicode characters. Here is my compilation command line: cl C:\path_to_source\preventShutdown.c kernel32.lib user32.lib /DUNICODE /D_UNICODE /O2 /link /NODEFAULTLIB /ENTRY:wWinMain and my source code:

/*
cl C:\path_to_source\preventShutdown.c kernel32.lib user32.lib /DUNICODE /D_UNICODE /O2 /link /NODEFAULTLIB /ENTRY:wWinMain
*/
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <windows.h>
LRESULT CALLBACK WindowProc(HWND,UINT,WPARAM,LPARAM);
int WINAPI wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPWSTR lpCmdLine,int nShowCmd)
{
LPCTSTR windowClassName=TEXT("windowClass"),windowName=TEXT("Zatrzymaj wyłączenie");
WNDCLASS windowClass={0};
windowClass.hInstance=hInstance;
windowClass.hIcon=NULL;
windowClass.hCursor=LoadCursor(NULL,IDC_ARROW);
windowClass.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
windowClass.lpszMenuName=NULL;
windowClass.lpszClassName=windowClassName;
windowClass.lpfnWndProc=&WindowProc;
if(!RegisterClass(&windowClass))return -1;
HWND hWnd=NULL;
if(!(hWnd=CreateWindow(windowClassName,windowName,WS_OVERLAPPEDWINDOW|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,NULL,NULL)))return -2;
MSG msg={0};
int bRet=0;
while((bRet=GetMessage(&msg,NULL,0,0))!=0)
{
 if(-1==bRet)return -3;
 TranslateMessage(&msg);
 DispatchMessage(&msg);
}
ExitProcess((UINT)msg.wParam);
return (int)msg.wParam;
}

LRESULT CALLBACK WindowProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
switch(msg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_QUERYENDSESSION:
ShutdownBlockReasonCreate(hWnd,TEXT("Rozpoczęto przez użytkownika"));
break;
case WM_ENDSESSION:
return 0;
break;
default:
return DefWindowProc(hWnd,msg,wParam,lParam);
break;
}
return 0;
}

- where path_to_source is real path to source code.


问:
Call a Widget based on the result of an If statement Flutter
I want to be able to call either one of two different widgets based on the result of an if statement.
I am able to get a Text Widget to show two different answers based on the result of the first dropdown box, but I am not able to call another widget the same way ...

```<code>import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({Key? key}) : super(key: key);

  @override
  State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
  String firstDropdownValue = 'Option A';
  String secondDropdownValue = 'Option B';

  @override
  void dispose() {
    super.dispose();
  }

  static const String _title = 'Filter Code Sample';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Padding(
            padding: EdgeInsets.all(4),
          ),
        ],
        title: Column(
          children: [
            Text(
              'Filter',
              style: TextStyle(fontSize: 22, color: Colors.amberAccent),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                'What are the Options ?',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),

              /*
              * This is the first dropdown that is called, This dropdown provides
              * two possible options,
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: firstDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    firstDropdownValue = newValue!;
                  });
                },
                items: <String>['Option A', 'Option B']
                    .map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * So this is the if Statement that works based upon the first
              * drop down box's answer...
              *
              * The problem is I can not get the system to call another Drop down Butten
              * Widget based on the answer of the first DropdownBox,
              * However, i can get a Text Widget to print...
              * */
              Text((() {
                if (firstDropdownValue == 'Option A') {
                  return "Option is Option A";
                }
                return "Option is Option B";
              })()),

              /*
              * This is the second dropbox that I would like to be called if the
              * previous statement is met instead of the Text Widget above...
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 1',
                  'Option 2',
                  'Option 3',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * This is also drop box two, but this dropbox with these different
              * options should be called when the if statement is not met ..
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 4',
                  'Option 5',
                  'Option 6',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

The flow diagram is maybe easier to get the whole picture from.

答:
One solution here is to use an inline if condition like this:

```<code> DropdownButton<String>(
    dropdownColor: Colors.blueGrey.shade700,
    value: firstDropdownValue,
    icon: const Icon(Icons.arrow_downward),
    elevation: 16,
    style: const TextStyle(color: Colors.white),
    underline: Container(
      height: 2,
      color: Colors.blueGrey.shade900,
    ),
    onChanged: (String? newValue) {
      setState(() {
        firstDropdownValue = newValue!;
      });
    },
    items: <String>['Option A', 'Option B']
        .map<DropdownMenuItem<String>>((String doaValue) {
      return DropdownMenuItem<String>(
        value: doaValue,
        child: Text(doaValue),
      );
    }).toList(),
),
firstDropdownValue == 'Option A'?
       DropdownButton(/*first dropdown*/) :
       DropdownButton(/*second dropdown*/),
</code>```

The other is creating a Widget variable at the beginning of the build method and giving it a value before returning the Scaffold, then put the created variable as one of the Column children:

```<code>@override
  Widget build(BuildContext context) {
    Widget bottomDropdown;
    if (firstDropdownValue == 'Option A'){
       bottomDropdown = DropdownButton(/*first dropdown*/);
    } else {
       bottomDropdown = DropdownButton(/*second dropdown*/);
    }
    return Scaffold(
      appBar: AppBar(
//...other code
    DropdownButton<String>(
      dropdownColor: Colors.blueGrey.shade700,
      value: firstDropdownValue,
      icon: const Icon(Icons.arrow_downward),
      elevation: 16,
      style: const TextStyle(color: Colors.white),
      underline: Container(
        height: 2,
        color: Colors.blueGrey.shade900,
      ),
      onChanged: (String? newValue) {
        setState(() {
          firstDropdownValue = newValue!;
        });
      },
      items: <String>['Option A', 'Option B']
          .map<DropdownMenuItem<String>>((String doaValue) {
        return DropdownMenuItem<String>(
          value: doaValue,
          child: Text(doaValue),
        );
      }).toList(),
   ),
   bottomDropdown,
</code>```

Body:
I want to be able to call either one of two different widgets based on the result of an if statement.
I am able to get a Text Widget to show two different answers based on the result of the first dropdown box, but I am not able to call another widget the same way ...

import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({Key? key}) : super(key: key);

  @override
  State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
  String firstDropdownValue = 'Option A';
  String secondDropdownValue = 'Option B';

  @override
  void dispose() {
    super.dispose();
  }

  static const String _title = 'Filter Code Sample';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Padding(
            padding: EdgeInsets.all(4),
          ),
        ],
        title: Column(
          children: [
            Text(
              'Filter',
              style: TextStyle(fontSize: 22, color: Colors.amberAccent),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                'What are the Options ?',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),

              /*
              * This is the first dropdown that is called, This dropdown provides
              * two possible options,
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: firstDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    firstDropdownValue = newValue!;
                  });
                },
                items: <String>['Option A', 'Option B']
                    .map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * So this is the if Statement that works based upon the first
              * drop down box's answer...
              *
              * The problem is I can not get the system to call another Drop down Butten
              * Widget based on the answer of the first DropdownBox,
              * However, i can get a Text Widget to print...
              * */
              Text((() {
                if (firstDropdownValue == 'Option A') {
                  return "Option is Option A";
                }
                return "Option is Option B";
              })()),

              /*
              * This is the second dropbox that I would like to be called if the
              * previous statement is met instead of the Text Widget above...
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 1',
                  'Option 2',
                  'Option 3',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * This is also drop box two, but this dropbox with these different
              * options should be called when the if statement is not met ..
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 4',
                  'Option 5',
                  'Option 6',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

The flow diagram is maybe easier to get the whole picture from.

Body:
One solution here is to use an inline if condition like this:

 DropdownButton<String>(
    dropdownColor: Colors.blueGrey.shade700,
    value: firstDropdownValue,
    icon: const Icon(Icons.arrow_downward),
    elevation: 16,
    style: const TextStyle(color: Colors.white),
    underline: Container(
      height: 2,
      color: Colors.blueGrey.shade900,
    ),
    onChanged: (String? newValue) {
      setState(() {
        firstDropdownValue = newValue!;
      });
    },
    items: <String>['Option A', 'Option B']
        .map<DropdownMenuItem<String>>((String doaValue) {
      return DropdownMenuItem<String>(
        value: doaValue,
        child: Text(doaValue),
      );
    }).toList(),
),
firstDropdownValue == 'Option A'?
       DropdownButton(/*first dropdown*/) :
       DropdownButton(/*second dropdown*/),

The other is creating a Widget variable at the beginning of the build method and giving it a value before returning the Scaffold, then put the created variable as one of the Column children:

@override
  Widget build(BuildContext context) {
    Widget bottomDropdown;
    if (firstDropdownValue == 'Option A'){
       bottomDropdown = DropdownButton(/*first dropdown*/);
    } else {
       bottomDropdown = DropdownButton(/*second dropdown*/);
    }
    return Scaffold(
      appBar: AppBar(
//...other code
    DropdownButton<String>(
      dropdownColor: Colors.blueGrey.shade700,
      value: firstDropdownValue,
      icon: const Icon(Icons.arrow_downward),
      elevation: 16,
      style: const TextStyle(color: Colors.white),
      underline: Container(
        height: 2,
        color: Colors.blueGrey.shade900,
      ),
      onChanged: (String? newValue) {
        setState(() {
          firstDropdownValue = newValue!;
        });
      },
      items: <String>['Option A', 'Option B']
          .map<DropdownMenuItem<String>>((String doaValue) {
        return DropdownMenuItem<String>(
          value: doaValue,
          child: Text(doaValue),
        );
      }).toList(),
   ),
   bottomDropdown,