问:
Angular- module is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property
I get this error after ng serve:
ERROR in ./src/app/Modeles/utilisateurs.model.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: C:\Users\xx\src\app\Modeles\utilisateurs.model.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.

tsconfig.json:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ],
    "types": ["gapi", "gapi.auth2"],

  },

  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  },

  "include": [
    "./src",
    "node_modules/@jaspero/ng2-select",
    "**/app/lazyModules/**/*.ts"
  ]
}
</code>```

tsconfig.app.json:

```<code>{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["gapi", "gapi.auth2"],
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}
</code>```

angular.json:

```<code>"projects": {
    "xx": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/xx",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "preserveSymlinks": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.scss"
            ],
            "scripts": []
          },
</code>```

答:
In tsconfig.app.json change your include array from </p>

```<code>"include": [
    "src/**/*.d.ts"
  ]
</code>```

<p>To </p>

```<code>"include": [
    "src/**/*.d.ts",
    "src/**/*.ts"
  ]
</code>```

Body:
I get this error after ng serve:
ERROR in ./src/app/Modeles/utilisateurs.model.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: C:\Users\xx\src\app\Modeles\utilisateurs.model.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ],
    "types": ["gapi", "gapi.auth2"],

  },

  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  },

  "include": [
    "./src",
    "node_modules/@jaspero/ng2-select",
    "**/app/lazyModules/**/*.ts"
  ]
}

tsconfig.app.json:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["gapi", "gapi.auth2"],
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

angular.json:

"projects": {
    "xx": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/xx",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "preserveSymlinks": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.scss"
            ],
            "scripts": []
          },

Body:
In tsconfig.app.json change your include array from

"include": [
    "src/**/*.d.ts"
  ]

To

"include": [
    "src/**/*.d.ts",
    "src/**/*.ts"
  ]


来源: stackexchange

问:
Python Class Attribute Reference
File 1:

```<code>class Person:

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
    def add_friend(friends):
        pass
def load_people():
    op = open("file.txt", "r")
    read = op.readlines()
    for i in read:
        p = Person(first_name, last_name)
        name = first_name + last_name
        p.add_friend(name)
    pass
</code>```

File 2:

```<code>class Patient:

    def __init__(self, first_name, last_name, health):
        self.first_name = first_name
        self.last_name = last_name
        self.health = health

def load_patient():
    op = open("file.txt", "r")
    read = op.readlines()
    for i in read:
        pa = Patient(first_name, last_name, health)
    pass
</code>```

I've 2 separate ".py files"
File 1 have a class called Person and a function called load_people, I've created an object called "p" in load_patient(my program is supposed to create an object for each line in the file, i.e for each name)
Then that object "p" is used to call a method called add_friend of "class Person" and this method will add a person into a list whenever it is called.

There are no issues with File1, my main concern is File2

In File2, the class we have now is called Patient and a function called load_patient
Now, I'm supposed to the same thing I did for load_people function. So I created a new object in load_patient function for Patient class which should be used to call add_friend function to add the person into the list. But I'm getting AttributeError.

答:
Firstly the question description is very wage.
"load_patient function for Patient class which should be used to call add_friend function" - Patient has to inherit from Person class to do so and it's not doing.

Code is not pasted propery.
Do you mean name = Person.first_name + Person.last_name ?

ContentLicense: CC BY-SA 4.0

Title: Python Class Attribute Reference

Body:
File 1:

class Person:

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
    def add_friend(friends):
        pass
def load_people():
    op = open("file.txt", "r")
    read = op.readlines()
    for i in read:
        p = Person(first_name, last_name)
        name = first_name + last_name
        p.add_friend(name)
    pass

File 2:

class Patient:

    def __init__(self, first_name, last_name, health):
        self.first_name = first_name
        self.last_name = last_name
        self.health = health

def load_patient():
    op = open("file.txt", "r")
    read = op.readlines()
    for i in read:
        pa = Patient(first_name, last_name, health)
    pass

I've 2 separate ".py files"
File 1 have a class called Person and a function called load_people, I've created an object called "p" in load_patient(my program is supposed to create an object for each line in the file, i.e for each name)
Then that object "p" is used to call a method called add_friend of "class Person" and this method will add a person into a list whenever it is called.

There are no issues with File1, my main concern is File2

In File2, the class we have now is called Patient and a function called load_patient
Now, I'm supposed to the same thing I did for load_people function. So I created a new object in load_patient function for Patient class which should be used to call add_friend function to add the person into the list. But I'm getting AttributeError.


问:
Third parameter (kwargs) sklearn fit() function
I'm quite new to scikit-learn and I have a question about the fit() function. I tried to look for information on the internet but couldn't find much.
In an assignement I have to create a dict of parameters passed to the fit function of a classifier, which means the function will take 3 arguments (X, y, kwargs). What parameters is this dictionary supposed to have? Apparently those are hyper parameters for the fit function. Online I only found information for xgbooster but I'm not supposed to use that, only classifiers from sklearn.

I also found online that fit can take a dictionary called **fit_params but there is nothing about the parameters the function might take.

I hope my question is clear, thanks a lot in advance!

答:
The model hyperparameters are not arguments to the fit function, but to the model class object that you need to create beforehand.

If you have a dictionary with parameters that you want to pass to your model, you need to do things this way (here with a Logistic Regression):

```<code>from sklearn.linear_model import LogisticRegression
params = {"C":10, "max_iter":200}
LR = LogisticRegression(**params)
</code>```

Now that you have created the model specifying the hyperparameters, you can proceed and fit it with your data.

```<code>LR.fit(X, y)
</code>```

Body:
The model hyperparameters are not arguments to the fit function, but to the model class object that you need to create beforehand.

If you have a dictionary with parameters that you want to pass to your model, you need to do things this way (here with a Logistic Regression):

from sklearn.linear_model import LogisticRegression
params = {"C":10, "max_iter":200}
LR = LogisticRegression(**params)

Now that you have created the model specifying the hyperparameters, you can proceed and fit it with your data.

LR.fit(X, y)


问:
How to sign a XML file with special characters?
I have to sign an XML and this returns error "Invalid CAF sign". (CAF = Código Autorización de Folios)

I have this XML File:

```<code><?xml version="1.0"?>
<AUTORIZACION>
<CAF version="1.0">
<DA>
<RE>76521854-3</RE>
<RS>SOCIEDAD FARMACEUTICA O"HIGGINS SPA</RS>
<TD>33</TD>
<RNG><D>101</D><H>200</H></RNG>
<FA>2020-05-28</FA>
<RSAPK><M>t6ldOQd1Mz+1tiYhaMvVCKeAyT2vQK4rqYCHtbMDWIAHBGwI3mr1mmgLUpXKfvisRl1pTY2RXWdZVd6vE12PSw==</M><E>Aw==</E></RSAPK>
<IDK>100</IDK>
</DA>
<FRMA algoritmo="SHA1withRSA">UQ85YCoqC+pBw7kjzU0g+0uufqKKg759DapDJP4Bt4LMk1mK4330cgBPpVh/iUo5oC9TxINqo0icwFYiAabskw==</FRMA>
</CAF>
<RSASK>-----BEGIN RSA PRIVATE KEY-----
MIIBOQIBAAJBALepXTkHdTM/tbYmIWjL1QingMk9r0CuK6mAh7WzA1iABwRsCN5q
9ZpoC1KVyn74rEZdaU2NkV1nWVXerxNdj0sCAQMCQHpw6NCvo3d/znluwPCH41sa
Vdt+dNXJcnEAWnkiAjr+4v/O/o8lhCUGHFaf/0B+1jp2kTnb7b/A4qrd9fxFs7sC
IQDm1L63s29TnXKNkSrlDPGRuqBa0IsmFoXM82Xp0aVhfwIhAMuv9tNUQ1vFbFM/
euaRSNk0CzSmOIanQDhiK9RHT6A1AiEAmeMpz8z04mj3CQtx7gihC9HAPIsHbrmu
iKJD8TZuQP8CIQCHyqSM4teSg52M1PyZtjCQzVzNxCWvGirQQXKNhN/AIwIgXDO7
2/zf8L8fGm6nrDl56Oiybnq0PIg67W4FJ3NBXxI=
-----END RSA PRIVATE KEY-----
</RSASK>

<RSAPUBK>-----BEGIN PUBLIC KEY-----
MFowDQYJKoZIhvcNAQEBBQADSQAwRgJBALepXTkHdTM/tbYmIWjL1QingMk9r0Cu
K6mAh7WzA1iABwRsCN5q9ZpoC1KVyn74rEZdaU2NkV1nWVXerxNdj0sCAQM=
-----END PUBLIC KEY-----
</RSAPUBK>
</AUTORIZACION>
</code>```

At RS tag we found:

```<code><RS>SOCIEDAD FARMACEUTICA O"HIGGINS SPA</RS>
</code>```

For deserialization i use this method with C#:

```<code>public static T DeserializeRawWithoutEncoding<T>(string filePath)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    T obj;
    using (StreamReader reader = new StreamReader(filePath))
    {
        obj = (T)serializer.Deserialize(reader);
        reader.Close();
    }
    return obj;
}
</code>```

But at the moment of desserialize, " is transformed to \" like in the image:

I know that both cases are valid because is just an Encoding interpretation.

The final XML signed is like this:

```<code><TED version="1.0">
<DD>
<RE>76521854-3</RE>
<TD>33</TD>
<F>101</F>
<FE>2020-05-30</FE>
<RR>66666666-6</RR>
<RSR>Razon Social de Cliente</RSR>
<MNT>0</MNT>
<IT1>Cajón AFECTO</IT1>
<CAF version="1.0">
<DA>
<RE>76521854-3</RE>
<RS>SOCIEDAD FARMACEUTICA O"HIGGINS SPA</RS>
<TD>33</TD>
<RNG>
<D>101</D>
<H>200</H>
</RNG>
<FA>2020-05-28</FA>
<RSAPK>
<M>t6ldOQd1Mz+1tiYhaMvVCKeAyT2vQK4rqYCHtbMDWIAHBGwI3mr1mmgLUpXKfvisRl1pTY2RXWdZVd6vE12PSw==</M>
<E>Aw==</E>
</RSAPK>
<IDK>100</IDK>
</DA>
<FRMA algoritmo="SHA1withRSA">UQ85YCoqC+pBw7kjzU0g+0uufqKKg759DapDJP4Bt4LMk1mK4330cgBPpVh/iUo5oC9TxINqo0icwFYiAabskw==</FRMA>
</CAF>
<TSTED>2020-05-30T20:37:53</TSTED>
</DD>
<FRMT algoritmo="SHA1withRSA">tVLkmiiS4+f2df6VSAuUbtBFzfBREEPu/xY2425y6+GOoBY7RJ44GN0sJOWZV4gqMrVm1bYUFR5PsMFuxyGPQA==</FRMT>
</TED>
</code>```

This XML file is generated when an TED object is serialized by this way:

```<code>XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.GetEncoding("ISO-8859-1");
settings.Indent = true;
settings.IndentChars = "";
settings.OmitXmlDeclaration = false;
using (XmlWriter xmlWriter = XmlWriter.Create(tempFilePath, settings))
{
      XmlSerializer s = new XmlSerializer(obj.GetType());
      s.Serialize(xmlWriter, obj, ns);
}
</code>```

BUT, <RS> tag is written with \" instead of " and i think that this transformation is the cause of the error.

Actions done without success:

Replace \" by " in a lot of differents ways. Directly with string.Replace() or SecurityElement.Escape(), hoewever i still getting this error. Also sometimes (according to the replacement done) i get SOCIEDAD FARMACEUTICA O"HIGGINS SPA.

The serialization and deserialization has been done with ISO-8859-1 Encoding. Ive tried changing this by UTF-8 but without success.

The government institution that is in charge of this, says that special characters have to be replaced pag. 20 but if i do this, i get this error "Invalid CAF sign".

EDIT:

Martin Honnen's answer seems to work. But this "final" XML is part of another bigger. When i sign this file " character is replaced by \"

Code to sign:

```<code>XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(filePath); //path where is the XML file. This XML has " instead of \"

SignedXml signedXml = new SignedXml(doc);
signedXml.SigningKey = certificado.PrivateKey;
Signature XMLSignature = signedXml.Signature;
Reference reference = new Reference();
reference.Uri = "#" + referenceID;

XmlDsigC14NTransform t = new XmlDsigC14NTransform();
reference.AddTransform(t);

XMLSignature.SignedInfo.AddReference(reference);
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new RSAKeyValue((RSA)certificado.PrivateKey));
keyInfo.AddClause(new KeyInfoX509Data(certificado));
XMLSignature.KeyInfo = keyInfo;
signedXml.ComputeSignature();

XmlElement xmlDigitalSignature = signedXml.GetXml();
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
doc.Save(filePath); //filepath is overwritten with \" instead of "
</code>```

How to sign this file keeping " instead of \" in C#?

答:
Instead of

```<code>using (XmlWriter xmlWriter = XmlWriter.Create(tempFilePath, settings))
{
      XmlSerializer s = new XmlSerializer(obj.GetType());
      s.Serialize(xmlWriter, obj, ns);
}
</code>```

you will need to wrap an existing XmlWriter into your own one that changes the serialization of " and ' to use entity references " and ':

```<code>using (EscapeQuotesXmlWriter exw = new EscapeQuotesXmlWriter(XmlWriter.Create(tempFilePath, settings)))
{
      XmlSerializer s = new XmlSerializer(obj.GetType());
      s.Serialize(exw , obj, ns);
}
</code>```

The class can be implemented as a subclass of XmlWrappingWriter

```<code>public class EscapeQuotesXmlWriter : XmlWrappingWriter
{
    public EscapeQuotesXmlWriter(XmlWriter baseWriter) : base(baseWriter)
    {
    }

    public override void WriteString(string text)
    {
        foreach (char ch in text)
        {
            if (ch == '"')
            {
                WriteEntityRef("quot");
            }
            else if (ch == '\'')
            {
                WriteEntityRef("apos");
            }
            else
            {
                base.WriteString(ch.ToString());
            }
        }
    }
    public override void WriteChars(char[] buffer, int index, int count)
    {
        WriteString(new String(buffer.Where((ch, pos) => pos >= index && pos < index + count).ToArray()));
    }

}
</code>```

XmlWrappingWriter is part of the project https://archive.codeplex.com/?p=mvpxml still available on the archived Codeplex web site, I am not sure there is a newer or more up to date version somewhere. The one I downloaded there seems to have some Guard.ArgumentNotNull(value, "value"); checks you might need to replace or comment out.

Note that this code will ensure any " or ' is written out out as the corresponding entity reference, I don't think there is a way to preserve the input format in a deserialization/serialization step.

As for your comment and edit, if you replace doc.Save(filePath); with another use of that writer e.g.

```<code>using (EscapeQuotesXmlWriter exw = new EscapeQuotesXmlWriter(XmlWriter.Create(filePath)))
{
   doc.Save(exw);
}
</code>```

I suppose you should have wanted format.

Body:
I have to sign an XML and this returns error "Invalid CAF sign". (CAF = Código Autorización de Folios)

I have this XML File:

<?xml version="1.0"?>
<AUTORIZACION>
<CAF version="1.0">
<DA>
<RE>76521854-3</RE>
<RS>SOCIEDAD FARMACEUTICA O"HIGGINS SPA</RS>
33
<RNG><D>101</D><H>200</H></RNG>
<FA>2020-05-28</FA>
<RSAPK><M>t6ldOQd1Mz+1tiYhaMvVCKeAyT2vQK4rqYCHtbMDWIAHBGwI3mr1mmgLUpXKfvisRl1pTY2RXWdZVd6vE12PSw==</M><E>Aw==</E></RSAPK>
<IDK>100</IDK>
</DA>
<FRMA algoritmo="SHA1withRSA">UQ85YCoqC+pBw7kjzU0g+0uufqKKg759DapDJP4Bt4LMk1mK4330cgBPpVh/iUo5oC9TxINqo0icwFYiAabskw==</FRMA>
</CAF>
<RSASK>-----BEGIN RSA PRIVATE KEY-----
MIIBOQIBAAJBALepXTkHdTM/tbYmIWjL1QingMk9r0CuK6mAh7WzA1iABwRsCN5q
9ZpoC1KVyn74rEZdaU2NkV1nWVXerxNdj0sCAQMCQHpw6NCvo3d/znluwPCH41sa
Vdt+dNXJcnEAWnkiAjr+4v/O/o8lhCUGHFaf/0B+1jp2kTnb7b/A4qrd9fxFs7sC
IQDm1L63s29TnXKNkSrlDPGRuqBa0IsmFoXM82Xp0aVhfwIhAMuv9tNUQ1vFbFM/
euaRSNk0CzSmOIanQDhiK9RHT6A1AiEAmeMpz8z04mj3CQtx7gihC9HAPIsHbrmu
iKJD8TZuQP8CIQCHyqSM4teSg52M1PyZtjCQzVzNxCWvGirQQXKNhN/AIwIgXDO7
2/zf8L8fGm6nrDl56Oiybnq0PIg67W4FJ3NBXxI=
-----END RSA PRIVATE KEY-----
</RSASK>

<RSAPUBK>-----BEGIN PUBLIC KEY-----
MFowDQYJKoZIhvcNAQEBBQADSQAwRgJBALepXTkHdTM/tbYmIWjL1QingMk9r0Cu
K6mAh7WzA1iABwRsCN5q9ZpoC1KVyn74rEZdaU2NkV1nWVXerxNdj0sCAQM=
-----END PUBLIC KEY-----
</RSAPUBK>
</AUTORIZACION>

At RS tag we found:

<RS>SOCIEDAD FARMACEUTICA O"HIGGINS SPA</RS>

For deserialization i use this method with C#:

public static T DeserializeRawWithoutEncoding<T>(string filePath)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    T obj;
    using (StreamReader reader = new StreamReader(filePath))
    {
        obj = (T)serializer.Deserialize(reader);
        reader.Close();
    }
    return obj;
}

But at the moment of desserialize, " is transformed to \" like in the image:

I know that both cases are valid because is just an Encoding interpretation.

The final XML signed is like this:

<TED version="1.0">

<RE>76521854-3</RE>
33
<F>101</F>
<FE>2020-05-30</FE>
<RR>66666666-6</RR>
<RSR>Razon Social de Cliente</RSR>
<MNT>0</MNT>
<IT1>Cajón AFECTO</IT1>
<CAF version="1.0">
<DA>
<RE>76521854-3</RE>
<RS>SOCIEDAD FARMACEUTICA O"HIGGINS SPA</RS>
33
<RNG>
<D>101</D>
<H>200</H>
</RNG>
<FA>2020-05-28</FA>
<RSAPK>
<M>t6ldOQd1Mz+1tiYhaMvVCKeAyT2vQK4rqYCHtbMDWIAHBGwI3mr1mmgLUpXKfvisRl1pTY2RXWdZVd6vE12PSw==</M>
<E>Aw==</E>
</RSAPK>
<IDK>100</IDK>
</DA>
<FRMA algoritmo="SHA1withRSA">UQ85YCoqC+pBw7kjzU0g+0uufqKKg759DapDJP4Bt4LMk1mK4330cgBPpVh/iUo5oC9TxINqo0icwFYiAabskw==</FRMA>
</CAF>
<TSTED>2020-05-30T20:37:53</TSTED>

<FRMT algoritmo="SHA1withRSA">tVLkmiiS4+f2df6VSAuUbtBFzfBREEPu/xY2425y6+GOoBY7RJ44GN0sJOWZV4gqMrVm1bYUFR5PsMFuxyGPQA==</FRMT>
</TED>

This XML file is generated when an TED object is serialized by this way:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.GetEncoding("ISO-8859-1");
settings.Indent = true;
settings.IndentChars = "";
settings.OmitXmlDeclaration = false;
using (XmlWriter xmlWriter = XmlWriter.Create(tempFilePath, settings))
{
      XmlSerializer s = new XmlSerializer(obj.GetType());
      s.Serialize(xmlWriter, obj, ns);
}

BUT, <RS> tag is written with \" instead of " and i think that this transformation is the cause of the error.

Actions done without success:

Replace \" by " in a lot of differents ways. Directly with string.Replace() or SecurityElement.Escape(), hoewever i still getting this error. Also sometimes (according to the replacement done) i get SOCIEDAD FARMACEUTICA O&quot;HIGGINS SPA.

The serialization and deserialization has been done with ISO-8859-1 Encoding. Ive tried changing this by UTF-8 but without success.

The government institution that is in charge of this, says that special characters have to be replaced pag. 20 but if i do this, i get this error "Invalid CAF sign".

EDIT:

Martin Honnen's answer seems to work. But this "final" XML is part of another bigger. When i sign this file " character is replaced by \"

Code to sign:

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(filePath); //path where is the XML file. This XML has " instead of \"

SignedXml signedXml = new SignedXml(doc);
signedXml.SigningKey = certificado.PrivateKey;
Signature XMLSignature = signedXml.Signature;
Reference reference = new Reference();
reference.Uri = "#" + referenceID;

XmlDsigC14NTransform t = new XmlDsigC14NTransform();
reference.AddTransform(t);

XMLSignature.SignedInfo.AddReference(reference);
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new RSAKeyValue((RSA)certificado.PrivateKey));
keyInfo.AddClause(new KeyInfoX509Data(certificado));
XMLSignature.KeyInfo = keyInfo;
signedXml.ComputeSignature();

XmlElement xmlDigitalSignature = signedXml.GetXml();
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
doc.Save(filePath); //filepath is overwritten with \" instead of "

How to sign this file keeping " instead of \" in C#?

Body:
Instead of

using (XmlWriter xmlWriter = XmlWriter.Create(tempFilePath, settings))
{
      XmlSerializer s = new XmlSerializer(obj.GetType());
      s.Serialize(xmlWriter, obj, ns);
}

you will need to wrap an existing XmlWriter into your own one that changes the serialization of " and ' to use entity references &quot; and &apos;:

using (EscapeQuotesXmlWriter exw = new EscapeQuotesXmlWriter(XmlWriter.Create(tempFilePath, settings)))
{
      XmlSerializer s = new XmlSerializer(obj.GetType());
      s.Serialize(exw , obj, ns);
}

The class can be implemented as a subclass of XmlWrappingWriter

public class EscapeQuotesXmlWriter : XmlWrappingWriter
{
    public EscapeQuotesXmlWriter(XmlWriter baseWriter) : base(baseWriter)
    {
    }

    public override void WriteString(string text)
    {
        foreach (char ch in text)
        {
            if (ch == '"')
            {
                WriteEntityRef("quot");
            }
            else if (ch == '\'')
            {
                WriteEntityRef("apos");
            }
            else
            {
                base.WriteString(ch.ToString());
            }
        }
    }
    public override void WriteChars(char[] buffer, int index, int count)
    {
        WriteString(new String(buffer.Where((ch, pos) => pos >= index && pos < index + count).ToArray()));
    }

}

XmlWrappingWriter is part of the project https://archive.codeplex.com/?p=mvpxml still available on the archived Codeplex web site, I am not sure there is a newer or more up to date version somewhere. The one I downloaded there seems to have some Guard.ArgumentNotNull(value, "value"); checks you might need to replace or comment out.

Note that this code will ensure any " or ' is written out out as the corresponding entity reference, I don't think there is a way to preserve the input format in a deserialization/serialization step.

As for your comment and edit, if you replace doc.Save(filePath); with another use of that writer e.g.

using (EscapeQuotesXmlWriter exw = new EscapeQuotesXmlWriter(XmlWriter.Create(filePath)))
{
   doc.Save(exw);
}

I suppose you should have wanted format.


问:
Should I unsubscribe from Firestore in an App.vue destruction lifecycle?
I am currently developing an app with Vue.js and Firebase database.
I am listening to real-time changes of one of the database documents, at the App.vue level.

In a child component, I would typically unsubscribe from the database in the beforeDestroy() Vue.js lifecycle.

Is there any point of unscubscribing at the App.vue level?

Thanks!

答:
If you believe that all subscribes should have matching unsubscribes, for the purpose of code symmetry, and communicating to other readers of your code when the subscription is expected to end, you might choose to add that code.

If your code runs in an environment (perhaps a test environment) that does not fully get destroyed when the lifecycle is complete, then you'd probably want to make sure your app releases its resources correctly.

Or maybe you are just concerned if there is any chance at all a subscription might leak, causing you money over time as it causes reads when those reads will not be used, so you choose to clean up properly just in case.


问:
How do I work with "image data as a byte string", using Python?
First I'm going to explain what I'm trying to do and then explain my problem.

Okay so I've been making prototypes on a project that I hope to be working on over the summer. The project is a small media player and one of the requirements is to display the albulm artwork of an mp3 file.

After some research I found this library:
http://code.google.com/p/mutagen/

The reason I chose this library was because it doesn't have any dependencies and it would make my application more portable.

After fidilling around with the code I was able to retrieve data from the mp3 file, such as the artist and recording year etc. I'll give a little demonstration here:

```<code>from mutagen.mp3 import MP3
audio = MP3("born.mp3")
artist = audio["TPE1"]
print artist
</code>```

In case this doesn't make much sense, this is the tutorial that is provided by mutagen - http://code.google.com/p/mutagen/wiki/Tutorial (its a little bit short)

Problem - I want to display the image using pygame. Normally this would read something like this:

```<code> monkey = pygame.image.load("monkey.jpg")

 screen.blit(monkey,(0,0))
</code>```

but instead I want to do use the image from the image file. So going from the first example it reads something like:

```<code>audio = MP3("born.mp3")
data = audio.tags['APIC:'].data
monkey = pygame.image.load(data)
</code>```

but pygame throws an exception error because the data type of the variable 'value' is raw image data as a byte string.

Question - Is it possible to convert the byte string to some sort of image format so pygame can use it?

For python documentation on images - http://www.pygame.org/docs/ref/image.html

I'm not sure if it is even possible to do what I am asking so please forgive me!

答:
Have you tried pygame.image.fromstring()?

note: since it's raw data, you'll need to know in advance a few details such as the resolution and colour depth.

ContentLicense: CC BY-SA 3.0

Body:
First I'm going to explain what I'm trying to do and then explain my problem.

Okay so I've been making prototypes on a project that I hope to be working on over the summer. The project is a small media player and one of the requirements is to display the albulm artwork of an mp3 file.

After some research I found this library:
http://code.google.com/p/mutagen/

The reason I chose this library was because it doesn't have any dependencies and it would make my application more portable.

After fidilling around with the code I was able to retrieve data from the mp3 file, such as the artist and recording year etc. I'll give a little demonstration here:

from mutagen.mp3 import MP3
audio = MP3("born.mp3")
artist = audio["TPE1"]
print artist

In case this doesn't make much sense, this is the tutorial that is provided by mutagen - http://code.google.com/p/mutagen/wiki/Tutorial (its a little bit short)

Problem - I want to display the image using pygame. Normally this would read something like this:

 monkey = pygame.image.load("monkey.jpg")

 screen.blit(monkey,(0,0))

but instead I want to do use the image from the image file. So going from the first example it reads something like:

audio = MP3("born.mp3")
data = audio.tags['APIC:'].data
monkey = pygame.image.load(data)

but pygame throws an exception error because the data type of the variable 'value' is raw image data as a byte string.

Question - Is it possible to convert the byte string to some sort of image format so pygame can use it?

For python documentation on images - http://www.pygame.org/docs/ref/image.html

I'm not sure if it is even possible to do what I am asking so please forgive me!


问:
EWS: Search in email body only responses 250 results
I currently got a problem with the exchange web service in C#.
I'm trying to loop through mails that are older than 3 months, but I only get 250 mails back. In the folder are more than 80.000 mails so that isn't the correct count.

After searching for the problem I now know that the service only gives me 250 results per page. But the TotalCount is 250 too, so I can't work with paging because there is no second page. Without the body filter it works and I get back like 70.000 mails which is correct. Has anyone had the same problem and can help me?

Currently the programm just uses 2 filters with the SearchFilter And operator and orders the result ascending.
Here is my current code for getting the mails:

Folder folder; // folder from loop
DateTime dateStart; // = today - 3 months

SearchFilter.SearchFilterCollection filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
filter.Add(new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dateStart));
filter.Add(new SearchFilter.ContainsSubstring(ItemSchema.Body, "test"));

ItemView view = new ItemView(1000, 0, OffsetBasePoint.Beginning);
// Get oldest first
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.DateTimeReceived);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
view.Traversal = ItemTraversal.Shallow;

FindItemsResults<Item> findResults = exchangeService.FindItems(folder.Id, filter, view);

findResults.TotalCount() // = 250
```

I would be glad about a solution, thanks for helping :)

答: Am sure you have figured this out by now, but it is due to EWS throttling.  While this can be changed, it is not advised.  Only workaround I have found is to move the items to another folder and keep re-running logic.  Here is a link to info on EWS throttling and also a way to determine your current policy - https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/ews-throttling-in-exchange.</p>

Body:
I currently got a problem with the exchange web service in C#.
I'm trying to loop through mails that are older than 3 months, but I only get 250 mails back. In the folder are more than 80.000 mails so that isn't the correct count.

After searching for the problem I now know that the service only gives me 250 results per page. But the TotalCount is 250 too, so I can't work with paging because there is no second page. Without the body filter it works and I get back like 70.000 mails which is correct. Has anyone had the same problem and can help me?

Currently the programm just uses 2 filters with the SearchFilter And operator and orders the result ascending.
Here is my current code for getting the mails:

Folder folder; // folder from loop
DateTime dateStart; // = today - 3 months

SearchFilter.SearchFilterCollection filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
filter.Add(new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dateStart));
filter.Add(new SearchFilter.ContainsSubstring(ItemSchema.Body, "test"));

ItemView view = new ItemView(1000, 0, OffsetBasePoint.Beginning);
// Get oldest first
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.DateTimeReceived);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
view.Traversal = ItemTraversal.Shallow;

FindItemsResults<Item> findResults = exchangeService.FindItems(folder.Id, filter, view);

findResults.TotalCount() // = 250

I would be glad about a solution, thanks for helping :)


问:
Adding empty rows to Angular Material table when rows are less than a set number?
I have two angular tables and I am comparing their data side by side, let's say I have default 10 rows to show up on both tables, It can be the case that either if the two tables has less than 10 rows. E.g One table has 10 rows and second has just 1, so the second table end at just 1 row, what I would like to do is to have some empty rows(Number of rows that should be present - number of rows actually present). How can I do that ?

My First table

test-table.component.html

    <ng-container matColumnDef="id">
      Id
      {{row.id}}
    </ng-container>

    <ng-container matColumnDef="name">
      Name
      {{row.name}}
    </ng-container>

  <mat-paginator #paginator
      [length]="dataSource?.data.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>

```

<p>Data source file for this</p>

<p><code>test-table-datasource.ts</code></p>

<pre class="lang-js prettyprint-override"><code>import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface TestTableItem {
  name: string;
  id: number;
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: TestTableItem[] = [
  {id: 1, name: 'Hydrogen'},
  {id: 2, name: 'Helium'},
  {id: 3, name: 'Lithium'},
  {id: 4, name: 'Beryllium'},
  {id: 5, name: 'Boron'},
  {id: 6, name: 'Carbon'},
  {id: 7, name: 'Nitrogen'},
  {id: 8, name: 'Oxygen'},
  {id: 9, name: 'Fluorine'},
  {id: 10, name: 'Neon'},
  {id: 11, name: 'Sodium'},
  {id: 12, name: 'Magnesium'},
  {id: 13, name: 'Aluminum'},
  {id: 14, name: 'Silicon'},
  {id: 15, name: 'Phosphorus'},
  {id: 16, name: 'Sulfur'},
  {id: 17, name: 'Chlorine'},
  {id: 18, name: 'Argon'},
  {id: 19, name: 'Potassium'},
  {id: 20, name: 'Calcium'},
];

/**
 * Data source for the TestTable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class TestTableDataSource extends DataSource<TestTableItem> {
  data: TestTableItem[] = EXAMPLE_DATA;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<TestTableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: TestTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: TestTableItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
</code>```

test-table.component.ts

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { TestTableDataSource, TestTableItem } from './test-table-datasource';

@Component({
  selector: 'app-test-table',
  templateUrl: './test-table.component.html',
  styleUrls: ['./test-table.component.css']
})
export class TestTableComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<TestTableItem>;
  dataSource: TestTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  ngOnInit() {
    this.dataSource = new TestTableDataSource();
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }
}
```

<p>My Second Table
<code>sample-table.component.html</code></p>

<pre class="lang-js prettyprint-override"><code><div class="mat-elevation-z8">
  <table mat-table class="full-width-table" matSort aria-label="Elements">
    <!-- Id Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
      <td mat-cell *matCellDef="let row">{{row.id}}</td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
      <td mat-cell *matCellDef="let row">{{row.name}}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

  <mat-paginator #paginator
      [length]="dataSource?.data.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>
</div>
</code>```

sample-table-datasource.ts

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface SampleTableItem {
  name: string;
  id: number;
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: SampleTableItem[] = [
  {id: 1, name: 'Hydrogen'},
  {id: 2, name: 'Helium'},
  {id: 3, name: 'Lithium'},
  {id: 4, name: 'Beryllium'},
  {id: 5, name: 'Boron'},
  {id: 6, name: 'Carbon'},
  {id: 7, name: 'Nitrogen'},
  {id: 8, name: 'Oxygen'},
  {id: 9, name: 'Fluorine'},
  {id: 10, name: 'Neon'},
  {id: 11, name: 'Sodium'},
  {id: 12, name: 'Magnesium'},
  {id: 13, name: 'Aluminum'},
  {id: 14, name: 'Silicon'},
  {id: 15, name: 'Phosphorus'},
  {id: 16, name: 'Sulfur'},
  {id: 17, name: 'Chlorine'},
  {id: 18, name: 'Argon'},
  {id: 19, name: 'Potassium'},
  {id: 20, name: 'Calcium'},
];

/**
 * Data source for the SampleTable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class SampleTableDataSource extends DataSource<SampleTableItem> {
  data: SampleTableItem[] = EXAMPLE_DATA;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<SampleTableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: SampleTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: SampleTableItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
```

<p><code>sample-table.component.ts</code></p>

<pre class="lang-js prettyprint-override"><code>import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { SampleTableDataSource, SampleTableItem } from './sample-table-datasource';

@Component({
  selector: 'app-sample-table',
  templateUrl: './sample-table.component.html',
  styleUrls: ['./sample-table.component.css']
})
export class SampleTableComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<SampleTableItem>;
  dataSource: SampleTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  ngOnInit() {
    this.dataSource = new SampleTableDataSource();
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }
}
</code>```

app-compoenent.html

Table 1

<app-test-table></app-test-table>

Table 2

<app-sample-table></app-sample-table>

```

How do I add empty rows dynamically ?

答:
Okay so I have figured it out, here's the correct answer

In test-table-datasource.ts
Add the following to getPagedData method

 private getPagedData(data: TestTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    if( data.length -  startIndex < this.paginator.pageSize ){
      let diff = this.paginator.pageSize -(data.length - startIndex)
      for(let i=0 ; i<diff;i++){
        data.push(Object.create(null));
      }
    }

    return data.splice(startIndex, this.paginator.pageSize);
  }
```

This will add the empty rows to the DataSource,and this actually doesn't permanently change your data, since it adds the empty rows according to the pageSize.

Body:
I have two angular tables and I am comparing their data side by side, let's say I have default 10 rows to show up on both tables, It can be the case that either if the two tables has less than 10 rows. E.g One table has 10 rows and second has just 1, so the second table end at just 1 row, what I would like to do is to have some empty rows(Number of rows that should be present - number of rows actually present). How can I do that ?

My First table

test-table.component.html

    <ng-container matColumnDef="id">
      Id
      {{row.id}}
    </ng-container>

    <ng-container matColumnDef="name">
      Name
      {{row.name}}
    </ng-container>

  <mat-paginator #paginator
      [length]="dataSource?.data.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>

Data source file for this

test-table-datasource.ts

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface TestTableItem {
  name: string;
  id: number;
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: TestTableItem[] = [
  {id: 1, name: 'Hydrogen'},
  {id: 2, name: 'Helium'},
  {id: 3, name: 'Lithium'},
  {id: 4, name: 'Beryllium'},
  {id: 5, name: 'Boron'},
  {id: 6, name: 'Carbon'},
  {id: 7, name: 'Nitrogen'},
  {id: 8, name: 'Oxygen'},
  {id: 9, name: 'Fluorine'},
  {id: 10, name: 'Neon'},
  {id: 11, name: 'Sodium'},
  {id: 12, name: 'Magnesium'},
  {id: 13, name: 'Aluminum'},
  {id: 14, name: 'Silicon'},
  {id: 15, name: 'Phosphorus'},
  {id: 16, name: 'Sulfur'},
  {id: 17, name: 'Chlorine'},
  {id: 18, name: 'Argon'},
  {id: 19, name: 'Potassium'},
  {id: 20, name: 'Calcium'},
];

/**
 * Data source for the TestTable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class TestTableDataSource extends DataSource<TestTableItem> {
  data: TestTableItem[] = EXAMPLE_DATA;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<TestTableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: TestTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: TestTableItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

test-table.component.ts

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { TestTableDataSource, TestTableItem } from './test-table-datasource';

@Component({
  selector: 'app-test-table',
  templateUrl: './test-table.component.html',
  styleUrls: ['./test-table.component.css']
})
export class TestTableComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<TestTableItem>;
  dataSource: TestTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  ngOnInit() {
    this.dataSource = new TestTableDataSource();
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }
}

My Second Table
sample-table.component.html

    <ng-container matColumnDef="id">
      Id
      {{row.id}}
    </ng-container>

    <ng-container matColumnDef="name">
      Name
      {{row.name}}
    </ng-container>

  <mat-paginator #paginator
      [length]="dataSource?.data.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>

sample-table-datasource.ts

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface SampleTableItem {
  name: string;
  id: number;
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: SampleTableItem[] = [
  {id: 1, name: 'Hydrogen'},
  {id: 2, name: 'Helium'},
  {id: 3, name: 'Lithium'},
  {id: 4, name: 'Beryllium'},
  {id: 5, name: 'Boron'},
  {id: 6, name: 'Carbon'},
  {id: 7, name: 'Nitrogen'},
  {id: 8, name: 'Oxygen'},
  {id: 9, name: 'Fluorine'},
  {id: 10, name: 'Neon'},
  {id: 11, name: 'Sodium'},
  {id: 12, name: 'Magnesium'},
  {id: 13, name: 'Aluminum'},
  {id: 14, name: 'Silicon'},
  {id: 15, name: 'Phosphorus'},
  {id: 16, name: 'Sulfur'},
  {id: 17, name: 'Chlorine'},
  {id: 18, name: 'Argon'},
  {id: 19, name: 'Potassium'},
  {id: 20, name: 'Calcium'},
];

/**
 * Data source for the SampleTable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class SampleTableDataSource extends DataSource<SampleTableItem> {
  data: SampleTableItem[] = EXAMPLE_DATA;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<SampleTableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: SampleTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: SampleTableItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

sample-table.component.ts

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { SampleTableDataSource, SampleTableItem } from './sample-table-datasource';

@Component({
  selector: 'app-sample-table',
  templateUrl: './sample-table.component.html',
  styleUrls: ['./sample-table.component.css']
})
export class SampleTableComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<SampleTableItem>;
  dataSource: SampleTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  ngOnInit() {
    this.dataSource = new SampleTableDataSource();
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }
}

app-compoenent.html

Table 1

<app-test-table></app-test-table>

Table 2

<app-sample-table></app-sample-table>

How do I add empty rows dynamically ?

Body:
Okay so I have figured it out, here's the correct answer

In test-table-datasource.ts
Add the following to getPagedData method

 private getPagedData(data: TestTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    if( data.length -  startIndex < this.paginator.pageSize ){
      let diff = this.paginator.pageSize -(data.length - startIndex)
      for(let i=0 ; i<diff;i++){
        data.push(Object.create(null));
      }
    }

    return data.splice(startIndex, this.paginator.pageSize);
  }

This will add the empty rows to the DataSource,and this actually doesn't permanently change your data, since it adds the empty rows according to the pageSize.


问:
Removing a duplicate row from source spreadsheet
MASTER-PRE contains the master data,
PRE pulls data from the master data using IMPORTRANGE.
IMPORTRANGE is columns B-N from MASTER-PRE.
When a value is entered in column O on PRE, the below code is run and it drops the row back into MASTER-PRE.
However, it is a duplicate just with the value of column O added.

How do I amend the below code to either:
a) overwrite the exiting row
b) delete the duplicate row that doesn't contain a value in column O

```<code>function run2() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = ss.getSheetByName("PRE");
  var dstSheet = ss.getSheetByName("MASTER_PRE");

  // 1. Retrieve the values from "A2:G" of sheet "IN".
  var srcValues = srcSheet.getRange("B6:O" + srcSheet.getLastRow()).getValues();

  // 2. Create an object for putting values and deleting the contents of the columns "E" and "F".
  var obj = srcValues.reduce((o, [B,C,D,E,F,G,H,I,J,K,L,M,N,O], i) => {
    if (O != "") {
      o.values.push([B,C,D,E,F,G,H,I,J,K,L,M,N,O]);
      //o.ranges.push(`E${i + 2}:F${i + 2}`);
    }
    return o;
  }, {values: [], ranges: []});

  // 3. Copy the values to the sheet "ORDERS".
  dstSheet.getRange(dstSheet.getLastRow() + 1, 2, obj.values.length, obj.values[0].length).setValues(obj.values);

  // 4. Delete the contents of the columns "E" and "F" of sheet "IN".
  //srcSheet.getRangeList(obj.ranges).clearContent();
}
</code>```

答:
Solved. I used the following query/arrayformula in another sheet:

=ARRAYFORMULA(SORT(UNIQUE(VLOOKUP(
 QUERY(MASTER_PRE!B1:O, "select N where N is not null order by K desc", 0),
 QUERY(MASTER_PRE!B1:O, "select N,K,B,C,D,E,F,G,H,I,J,L,M,O where N is not null order by K desc", 0), {3,4,5,6,7,8,9,10,11,2,12,13,1,14}, 0)), 1, 1))

Full credit to @player0 for his answer on this post:
[Formula to filter unique rows with highest value in Google Sheets

Body:
MASTER-PRE contains the master data,
PRE pulls data from the master data using IMPORTRANGE.
IMPORTRANGE is columns B-N from MASTER-PRE.
When a value is entered in column O on PRE, the below code is run and it drops the row back into MASTER-PRE.
However, it is a duplicate just with the value of column O added.

How do I amend the below code to either:
a) overwrite the exiting row
b) delete the duplicate row that doesn't contain a value in column O

function run2() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = ss.getSheetByName("PRE");
  var dstSheet = ss.getSheetByName("MASTER_PRE");

  // 1. Retrieve the values from "A2:G" of sheet "IN".
  var srcValues = srcSheet.getRange("B6:O" + srcSheet.getLastRow()).getValues();

  // 2. Create an object for putting values and deleting the contents of the columns "E" and "F".
  var obj = srcValues.reduce((o, [B,C,D,E,F,G,H,I,J,K,L,M,N,O], i) => {
    if (O != "") {
      o.values.push([B,C,D,E,F,G,H,I,J,K,L,M,N,O]);
      //o.ranges.push(`E${i + 2}:F${i + 2}`);
    }
    return o;
  }, {values: [], ranges: []});

  // 3. Copy the values to the sheet "ORDERS".
  dstSheet.getRange(dstSheet.getLastRow() + 1, 2, obj.values.length, obj.values[0].length).setValues(obj.values);

  // 4. Delete the contents of the columns "E" and "F" of sheet "IN".
  //srcSheet.getRangeList(obj.ranges).clearContent();
}


问:
C++ template instance as function parameter and lambda binary predicate
I am in the process of fixing some of the sonarcloud issues on my project. One complaint is the function where I read and deserialize the settings for my application. Basically there are 50 or so blocks of this in one function:

```<code>if (!m_logLevel.deserializeFromSettings(settings, HGGW_KEY_LOGLEVEL) || m_logLevel.value() <= 0 || m_logLevel.value() > 4)
    {
        m_logLevel.update(HGGW_DEFAULT_LOGLEVEL, 0);
        m_logLevel.serializeToQSettings(settings, HGGW_KEY_LOGLEVEL);
    }
</code>```

The members are instances of a templated class:

```<code>template <typename T>
class AwsProperty
{
public:
    AwsProperty(T value, qint64 timestamp) : m_timestamp(timestamp), m_data(value){}
    //other stuff, not important
}
//example:
AwsProperty<int> m_property;
</code>```

I tried to design this function:

```<code>template <typename X>
    void readAWSSettingOrPopulateDefault(AwsProperty<X> property, QString key, X default_val, QSettings settings, bool (*predicate)(X)){
        if(!property.deserializeFromSettings(settings,key) || predicate(property.value())){
            property.update(default_val, 0);
            property.serializeToQSettings(settings, key);
        }
    }
</code>```

Trying to call it:

```<code>    this->readAWSSettingOrPopulateDefault(m_logLevel, HGGW_KEY_LOGLEVEL, HGGW_DEFAULT_LOGLEVEL, settings, [](int val){return val <= 0 || val > 4;});
</code>```

Yields this error:

```<code>XXXXconfig.cpp:275: error: no matching function for call to ‘LocalConfig::readAWSSettingOrPopulateDefault(HGGWAwsPropertyInt32&, const QString&, const int&, QSettings&, LocalConfig::init(QString)::<lambda(int)>)’
     this->readAWSSettingOrPopulateDefault(m_logLevel, HGGW_KEY_LOGLEVEL, HGGW_DEFAULT_LOGLEVEL, settings, [](int val){return val <= 0 || val > 4;});
XXXXconfig.cpp:275: note:   mismatched types ‘bool (*)(X)’ and ‘LocalConfig::init(QString)::<lambda(int)>’
     this->readAWSSettingOrPopulateDefault(m_logLevel, HGGW_KEY_LOGLEVEL, HGGW_DEFAULT_LOGLEVEL, settings, [](int val){return val <= 0 || val > 4;});
                                                                                ^                                                                                ^
                                                                                XXXXconfig.cpp:275: note:   mismatched types ‘bool (*)(X)’ and ‘LocalConfig::init(QString)::<lambda(int)>’
                                                                                ^
</code>```

答:
The reason your code reports an error is that for a function template declared as:

```<code>template <typename X>
void readAWSSettingOrPopulateDefault(AwsProperty<X> property, QString key
                                   , X default_val, QSettings settings
                                   , bool (*predicate)(X));
</code>```

the compiler will have to deduce X from all arguments using this template parameter -- property, default_val and predicate -- and then  make sure that those deduced types are the same (that is, there's only one template parameter, it can hold one type).

However, a lambda is not a function. It is convertible to a function pointer through an implicit conversion. Template argument deduction does not consider conversions (except for the derived-to-base conversion). Hence, the compiler is unable to finalize template argument deduction.

In order to make your code work, put the last occurrence of X in the function pointer-type parameter declaration in a non-deduced context:

```<code>template <typename T>
struct dont_deduce { using type = T; };

template <typename T>
using dont_deduce_t = typename dont_deduce<T>::type;

template <typename X>
void readAWSSettingOrPopulateDefault(AwsProperty<X> property, QString key
                                   , X default_val, QSettings settings
                                   , bool (*predicate)(dont_deduce_t<X>));
</code>```

This way, the compiler will not even attempt to deduce X from the lambda expression, and instead will use the type from property/default_val, thus making it possible to use the implicit conversion of the lambda to a function pointer. That is, no deduction and at the same time, a known function signature that can trigger the conversion.

Body:
I am in the process of fixing some of the sonarcloud issues on my project. One complaint is the function where I read and deserialize the settings for my application. Basically there are 50 or so blocks of this in one function:

if (!m_logLevel.deserializeFromSettings(settings, HGGW_KEY_LOGLEVEL) || m_logLevel.value() <= 0 || m_logLevel.value() > 4)
    {
        m_logLevel.update(HGGW_DEFAULT_LOGLEVEL, 0);
        m_logLevel.serializeToQSettings(settings, HGGW_KEY_LOGLEVEL);
    }

The members are instances of a templated class:

template <typename T>
class AwsProperty
{
public:
    AwsProperty(T value, qint64 timestamp) : m_timestamp(timestamp), m_data(value){}
    //other stuff, not important
}
//example:
AwsProperty<int> m_property;

I tried to design this function:

template <typename X>
    void readAWSSettingOrPopulateDefault(AwsProperty<X> property, QString key, X default_val, QSettings settings, bool (*predicate)(X)){
        if(!property.deserializeFromSettings(settings,key) || predicate(property.value())){
            property.update(default_val, 0);
            property.serializeToQSettings(settings, key);
        }
    }

Trying to call it:

    this->readAWSSettingOrPopulateDefault(m_logLevel, HGGW_KEY_LOGLEVEL, HGGW_DEFAULT_LOGLEVEL, settings, [](int val){return val <= 0 || val > 4;});

Yields this error:

XXXXconfig.cpp:275: error: no matching function for call to ‘LocalConfig::readAWSSettingOrPopulateDefault(HGGWAwsPropertyInt32&, const QString&, const int&, QSettings&, LocalConfig::init(QString)::<lambda(int)>)’
     this->readAWSSettingOrPopulateDefault(m_logLevel, HGGW_KEY_LOGLEVEL, HGGW_DEFAULT_LOGLEVEL, settings, [](int val){return val <= 0 || val > 4;});
XXXXconfig.cpp:275: note:   mismatched types ‘bool (*)(X)’ and ‘LocalConfig::init(QString)::<lambda(int)>’
     this->readAWSSettingOrPopulateDefault(m_logLevel, HGGW_KEY_LOGLEVEL, HGGW_DEFAULT_LOGLEVEL, settings, [](int val){return val <= 0 || val > 4;});
                                                                                ^                                                                                ^
                                                                                XXXXconfig.cpp:275: note:   mismatched types ‘bool (*)(X)’ and ‘LocalConfig::init(QString)::<lambda(int)>’
                                                                                ^

Body:
The reason your code reports an error is that for a function template declared as:

template <typename X>
void readAWSSettingOrPopulateDefault(AwsProperty<X> property, QString key
                                   , X default_val, QSettings settings
                                   , bool (*predicate)(X));

the compiler will have to deduce X from all arguments using this template parameter -- property, default_val and predicate -- and then  make sure that those deduced types are the same (that is, there's only one template parameter, it can hold one type).

However, a lambda is not a function. It is convertible to a function pointer through an implicit conversion. Template argument deduction does not consider conversions (except for the derived-to-base conversion). Hence, the compiler is unable to finalize template argument deduction.

In order to make your code work, put the last occurrence of X in the function pointer-type parameter declaration in a non-deduced context:

template <typename T>
struct dont_deduce { using type = T; };

template <typename T>
using dont_deduce_t = typename dont_deduce<T>::type;

template <typename X>
void readAWSSettingOrPopulateDefault(AwsProperty<X> property, QString key
                                   , X default_val, QSettings settings
                                   , bool (*predicate)(dont_deduce_t<X>));

This way, the compiler will not even attempt to deduce X from the lambda expression, and instead will use the type from property/default_val, thus making it possible to use the implicit conversion of the lambda to a function pointer. That is, no deduction and at the same time, a known function signature that can trigger the conversion.


问:
I loop through data frame, graph histogram for each column, use column name as graph title, print first value instead
I'd like to loop through columns with purrr::map and print a histogram for each of them. This works.

```<code>library(tidyverse)
library(patchwork)

iris %>% # example data
  select(-Species) %>% # drop one non-numeric col
  map( ~ ggplot(iris, aes(x = .)) + # loop through cols... for col, take it as x aes
         geom_histogram() # graph histogram
       ) %>% # output is list of graphs
  wrap_plots() # wrap list using patchwork
</code>```

But the graphs are pretty cryptic without titles to tell you which graph belongs to which column.

I tried adding a ggtitle option.

```<code>library(tidyverse)
library(patchwork)

iris %>%
  select(-Species) %>%
  map( ~ ggplot(iris, aes(x = .)) +
         geom_histogram() +
         ggtitle(.)
       ) %>%
  wrap_plots()
</code>```

However, it prints the first value of each column as the title, not the colname.

```<code>head(iris, 1) # for reference

</code>```

What should I be doing differently to get colnames as graph titles for the individual graphs? I can make do with proper x axis labels as well.

答:
This doesn't answer your question exactly, but if your use case is EDA only, you can take a massive shortcut and just use the skimr package. Basic histograms are printed in the console output. </p>

```<code>skimr::skim(iris)

Skim summary statistics
 n obs: 150
 n variables: 5

-- Variable type:factor --------------------------------------------------------
 variable missing complete   n n_unique                       top_counts ordered
  Species       0      150 150        3 set: 50, ver: 50, vir: 50, NA: 0   FALSE

-- Variable type:numeric -------------------------------------------------------
     variable missing complete   n mean   sd  p0 p25  p50 p75 p100     hist
 Petal.Length       0      150 150 3.76 1.77 1   1.6 4.35 5.1  6.9 ▇▁▁▂▅▅▃▁
  Petal.Width       0      150 150 1.2  0.76 0.1 0.3 1.3  1.8  2.5 ▇▁▁▅▃▃▂▂
 Sepal.Length       0      150 150 5.84 0.83 4.3 5.1 5.8  6.4  7.9 ▂▇▅▇▆▅▂▂
  Sepal.Width       0      150 150 3.06 0.44 2   2.8 3    3.3  4.4 ▁▂▅▇▃▂▁▁
</code>```

Body:
I'd like to loop through columns with purrr::map and print a histogram for each of them. This works.

library(tidyverse)
library(patchwork)

iris %>% # example data
  select(-Species) %>% # drop one non-numeric col
  map( ~ ggplot(iris, aes(x = .)) + # loop through cols... for col, take it as x aes
         geom_histogram() # graph histogram
       ) %>% # output is list of graphs
  wrap_plots() # wrap list using patchwork

But the graphs are pretty cryptic without titles to tell you which graph belongs to which column.

I tried adding a ggtitle option.

library(tidyverse)
library(patchwork)

iris %>%
  select(-Species) %>%
  map( ~ ggplot(iris, aes(x = .)) +
         geom_histogram() +
         ggtitle(.)
       ) %>%
  wrap_plots()

However, it prints the first value of each column as the title, not the colname.

head(iris, 1) # for reference

What should I be doing differently to get colnames as graph titles for the individual graphs? I can make do with proper x axis labels as well.

Body:
This doesn't answer your question exactly, but if your use case is EDA only, you can take a massive shortcut and just use the skimr package. Basic histograms are printed in the console output.

skimr::skim(iris)

Skim summary statistics
 n obs: 150
 n variables: 5

-- Variable type:factor --------------------------------------------------------
 variable missing complete   n n_unique                       top_counts ordered
  Species       0      150 150        3 set: 50, ver: 50, vir: 50, NA: 0   FALSE

-- Variable type:numeric -------------------------------------------------------
     variable missing complete   n mean   sd  p0 p25  p50 p75 p100     hist
 Petal.Length       0      150 150 3.76 1.77 1   1.6 4.35 5.1  6.9 ▇▁▁▂▅▅▃▁
  Petal.Width       0      150 150 1.2  0.76 0.1 0.3 1.3  1.8  2.5 ▇▁▁▅▃▃▂▂
 Sepal.Length       0      150 150 5.84 0.83 4.3 5.1 5.8  6.4  7.9 ▂▇▅▇▆▅▂▂
  Sepal.Width       0      150 150 3.06 0.44 2   2.8 3    3.3  4.4 ▁▂▅▇▃▂▁▁


问:
How to listen to when it is tapped outside a dialog in flutter?
Just as the title says. I already set barrierDismissible to false when calling showDialog so that the Dialog is not dismissed when tapping outside of it. I tried wrapping the Dialog in a GestureDetector and listening to onTap but this only listens to when the dialog is tapped and not outside of it.

答:
You can use await-then </p>

```<code> await showDialog(
       //Your Dialog Code
).then((val){
//here to run on dismiss codes
    Navigator.pop(_context);
});
</code>```

Body:
You can use await-then

 await showDialog(
       //Your Dialog Code
).then((val){
//here to run on dismiss codes
    Navigator.pop(_context);
});


问:
Populating and passing complex object from MVC2 view to controller action
I have following code in my MVC2 view:

```<code><tr class="edit" style="display:none">
    <td>
        <%= Html.DropDownList("drpFields", new SelectList(Model.Fields, "FieldID", "NiceName", whiteout.FieldID)) %>
    </td>
    <td>
        <%= Html.DropDownList("drpStartTimeh", new SelectList(Model.Hours, whiteout.StartHour.Hour.ToString("0,0")))%>
        <%= Html.DropDownList("drpStartTimem", new SelectList(Model.Minutes, whiteout.StartHour.Minute.ToString("0,0")))%>
        <%= Html.DropDownList("drpStartTimet", new SelectList(Model.AMPM, whiteout.StartHour.Hour > 12 ? "PM" : "AM"))%>
        -
        <%= Html.DropDownList("drpEndTime", new SelectList(Model.Hours, whiteout.EndHour.Hour > 12 ? (whiteout.EndHour.Hour - 12).ToString("0,0") : whiteout.EndHour.Hour.ToString("0,0")))%>
        <%= Html.DropDownList("drpEndTimem", new SelectList(Model.Minutes, whiteout.EndHour.Minute.ToString("0,0")))%>
        <%= Html.DropDownList("drpEndTimet", new SelectList(Model.AMPM, whiteout.EndHour.Hour > 12 ? "PM" : "AM"))%>
    </td>
    <td>
      <%= Html.DropDownList("drprepeat", new SelectList(Model.RepeatList,whiteout.Repeats))%>
    </td>
    <td>
     Active
    </td>
    <td>
             <a class="icon-button-cancel" href='<%: Url.Action("EditWhiteOut", "Settings", new {Id = whiteout.WhiteoutID}) %>'>
    <img src='<%: Url.Content("~/static/Images/expanded.png") %>' alt="Delete this device" />
</a>
            <a class="icon-button-success" href="#">
            <img src="/static/images/gear.png" alt="Edit this device" /></a>
    </td>
    <td>
    </td>
</tr>
</code>```

I want to create an object of type Whiteout class and populate it with values selected by user from dropdowns and send to settingcontroller's EditWhiteout action method instead of passing only new {Id = whiteout.WhiteoutID}. How can I do this ?

Please suggest solution.

Thanks.

答:
MVC provides some automatic mapping on form values from the view back into the controller action.  Usually you would use a strongly type view i.e. at the top of the page you will have something
like
Control Language="C#" Inherits="System.Web.Mvc.ViewPage<namespace.Whiteout>

The names of the dropdown lists need to match those of the properties in the Whiteout class and the controller action will expect a return value of the model type i.e.

```<code> [HttpPost]
 public ActionResult EditWhiteout(WhiteOut tseItem)
 { //method body here
</code>```

The rest should just happen as if by magic.  If you are getting confused by the dropdowns it is sometimes easier to replace them with simple inputs until you get the send/receive part working - then change to dropdown.

Body:
I have following code in my MVC2 view:

        <%= Html.DropDownList("drpFields", new SelectList(Model.Fields, "FieldID", "NiceName", whiteout.FieldID)) %>

        <%= Html.DropDownList("drpStartTimeh", new SelectList(Model.Hours, whiteout.StartHour.Hour.ToString("0,0")))%>
        <%= Html.DropDownList("drpStartTimem", new SelectList(Model.Minutes, whiteout.StartHour.Minute.ToString("0,0")))%>
        <%= Html.DropDownList("drpStartTimet", new SelectList(Model.AMPM, whiteout.StartHour.Hour > 12 ? "PM" : "AM"))%>
        -
        <%= Html.DropDownList("drpEndTime", new SelectList(Model.Hours, whiteout.EndHour.Hour > 12 ? (whiteout.EndHour.Hour - 12).ToString("0,0") : whiteout.EndHour.Hour.ToString("0,0")))%>
        <%= Html.DropDownList("drpEndTimem", new SelectList(Model.Minutes, whiteout.EndHour.Minute.ToString("0,0")))%>
        <%= Html.DropDownList("drpEndTimet", new SelectList(Model.AMPM, whiteout.EndHour.Hour > 12 ? "PM" : "AM"))%>

      <%= Html.DropDownList("drprepeat", new SelectList(Model.RepeatList,whiteout.Repeats))%>

     Active

             <a class="icon-button-cancel" href='<%: Url.Action("EditWhiteOut", "Settings", new {Id = whiteout.WhiteoutID}) %>'>
    <img src='<%: Url.Content("~/static/Images/expanded.png") %>' alt="Delete this device" />

I want to create an object of type Whiteout class and populate it with values selected by user from dropdowns and send to settingcontroller's EditWhiteout action method instead of passing only new {Id = whiteout.WhiteoutID}. How can I do this ?

Please suggest solution.

Thanks.

Body:
MVC provides some automatic mapping on form values from the view back into the controller action.  Usually you would use a strongly type view i.e. at the top of the page you will have something
like
Control Language="C#" Inherits="System.Web.Mvc.ViewPage<namespace.Whiteout>

The names of the dropdown lists need to match those of the properties in the Whiteout class and the controller action will expect a return value of the model type i.e.

 [HttpPost]
 public ActionResult EditWhiteout(WhiteOut tseItem)
 { //method body here

The rest should just happen as if by magic.  If you are getting confused by the dropdowns it is sometimes easier to replace them with simple inputs until you get the send/receive part working - then change to dropdown.


问:
How to get the column names with value more than ZERO as the multilabels for each row
I have a case where I have label names as columns of a DataFrame with value 0 or more like below.

```<code>.net    2007    actionscript-3  activerecord    air ajax
0   0   0   0   1   1   1
1   0   0   0   1   1   1
2   0   0   0   1   1   1
3   2   2   2   2   0   0
4   2   2   2   2   0   0
5   2   2   2   2   0   0
</code>```

My requirement is to put those column names whose value is more than zero, in a single column seperated by space for each row like below :

```<code>0   activerecord air ajax
1   activerecord air ajax
2   activerecord air ajax
3   .net 2007 actionscript-3 activerecord
4   .net 2007 actionscript-3 activerecord
5   .net 2007 actionscript-3 activerecord
</code>```

Example : values in columns activerecord, air, ajax has value of 1 in first row so these 3 should appear in one column of the dataframe separated by space.

This is an example of multi-label classification.

答:
try this,

```<code>print(df.apply(lambda x: " ".join([k for k, v in x.iteritems() if v]), axis=1))
</code>```

output,

```<code>0                    activerecord air ajax
1                    activerecord air ajax
2                    activerecord air ajax
3    .net 2007 actionscript-3 activerecord
4    .net 2007 actionscript-3 activerecord
5    .net 2007 actionscript-3 activerecord
</code>```

Body:
I have a case where I have label names as columns of a DataFrame with value 0 or more like below.

.net    2007    actionscript-3  activerecord    air ajax
0   0   0   0   1   1   1
1   0   0   0   1   1   1
2   0   0   0   1   1   1
3   2   2   2   2   0   0
4   2   2   2   2   0   0
5   2   2   2   2   0   0

My requirement is to put those column names whose value is more than zero, in a single column seperated by space for each row like below :

0   activerecord air ajax
1   activerecord air ajax
2   activerecord air ajax
3   .net 2007 actionscript-3 activerecord
4   .net 2007 actionscript-3 activerecord
5   .net 2007 actionscript-3 activerecord

Example : values in columns activerecord, air, ajax has value of 1 in first row so these 3 should appear in one column of the dataframe separated by space.

This is an example of multi-label classification.

Body:
try this,

print(df.apply(lambda x: " ".join([k for k, v in x.iteritems() if v]), axis=1))

output,

0                    activerecord air ajax
1                    activerecord air ajax
2                    activerecord air ajax
3    .net 2007 actionscript-3 activerecord
4    .net 2007 actionscript-3 activerecord
5    .net 2007 actionscript-3 activerecord


问:
Reading a json webpage using python
I am trying to read a json webpage and insert it into a dataframe.

import urllib3
import json
import pandas as pd

url = 'https://covid.ourworldindata.org/data/owid-covid-data.json'
http = urllib3.PoolManager()
r = http.request('GET', url, headers={'Accept': 'application/json'})

data = json.loads(r.data.decode('utf-8'))
data_copy = data

df = pd.DataFrame.from_dict(data_copy, orient='index')
df.transpose()
```

I need to use the same code I previewed but the output has to be in the following format:

答:
This implementation results in the desired output form.

Only pandas is required.

Directly read the url with pandas.read_json

Use pandas.DataFrame.stack to stack all the columns of dictionaries into one column.

As of pandas v1.0.0, json_normalize is in the top level name space.

Otherwise, use from pandas.io.json import json_normalize and replace pd.json_normalize(df2[0]) with json_normalize(df2[0])

import pandas as pd

# read data with pandas
df = pd.read_json('https://covid.ourworldindata.org/data/owid-covid-data.json', orient='index')

# stack all the dictionary columns
df2 = df.stack().reset_index()

# use json_normalize to expand dicts, drop and rename columns
df2 = df2.join(pd.json_normalize(df2[0])).drop(columns=['level_1', 0]).rename(columns={'level_0': 'iso_code'})

iso_code location        date  total_cases  new_cases  total_deaths  new_deaths  total_cases_per_million  new_cases_per_million  total_deaths_per_million  new_deaths_per_million  stringency_index  population  population_density  median_age  aged_65_older  aged_70_older  gdp_per_capita  diabetes_prevalence  cvd_death_rate  handwashing_facilities  hospital_beds_per_100k  extreme_poverty  female_smokers  male_smokers  total_tests  total_tests_per_thousand tests_units  new_tests  new_tests_per_thousand  new_tests_smoothed  new_tests_smoothed_per_thousand
     ABW    Aruba  2020-03-13            2          2             0           0                   18.733                 18.733                       0.0                     0.0              0.00    106766.0               584.8        41.2         13.085          7.452       35973.781                11.62             NaN                     NaN                     NaN              NaN             NaN           NaN          NaN                       NaN         NaN        NaN                     NaN                 NaN                              NaN
     ABW    Aruba  2020-03-20            4          2             0           0                   37.465                 18.733                       0.0                     0.0             30.56    106766.0               584.8        41.2         13.085          7.452       35973.781                11.62             NaN                     NaN                     NaN              NaN             NaN           NaN          NaN                       NaN         NaN        NaN                     NaN                 NaN                              NaN
     ABW    Aruba  2020-03-24           12          8             0           0                  112.395                 74.930                       0.0                     0.0             41.67    106766.0               584.8        41.2         13.085          7.452       35973.781                11.62             NaN                     NaN                     NaN              NaN             NaN           NaN          NaN                       NaN         NaN        NaN                     NaN                 NaN                              NaN
     ABW    Aruba  2020-03-25           17          5             0           0                  159.227                 46.831                       0.0                     0.0             41.67    106766.0               584.8        41.2         13.085          7.452       35973.781                11.62             NaN                     NaN                     NaN              NaN             NaN           NaN          NaN                       NaN         NaN        NaN                     NaN                 NaN                              NaN
     ABW    Aruba  2020-03-26           19          2             0           0                  177.959                 18.733                       0.0                     0.0             41.67    106766.0               584.8        41.2         13.085          7.452       35973.781                11.62             NaN                     NaN                     NaN              NaN             NaN           NaN          NaN                       NaN         NaN        NaN                     NaN                 NaN                              NaN
```

Title: Reading a json webpage using python

Body:
I am trying to read a json webpage and insert it into a dataframe.

import urllib3
import json
import pandas as pd

url = 'https://covid.ourworldindata.org/data/owid-covid-data.json'
http = urllib3.PoolManager()
r = http.request('GET', url, headers={'Accept': 'application/json'})

data = json.loads(r.data.decode('utf-8'))
data_copy = data

df = pd.DataFrame.from_dict(data_copy, orient='index')
df.transpose()

I need to use the same code I previewed but the output has to be in the following format:


问:
There was an error while I tried to install urlparse4
```<code>pip install urlparse4
Collecting urlparse4
  Using cached urlparse4-0.1.3.tar.gz (158 kB)
    ERROR: Command errored out with exit status 1:
     command: /opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/5d/s05y8m4107z_tgvnq4z02kdr0000gp/T/pip-install-4dhc591p/urlparse4/setup.py'"'"'; __file__='"'"'/private/var/folders/5d/s05y8m4107z_tgvnq4z02kdr0000gp/T/pip-install-4dhc591p/urlparse4/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/5d/s05y8m4107z_tgvnq4z02kdr0000gp/T/pip-pip-egg-info-me23x0q2
         cwd: /private/var/folders/5d/s05y8m4107z_tgvnq4z02kdr0000gp/T/pip-install-4dhc591p/urlparse4/
    Complete output (6 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/5d/s05y8m4107z_tgvnq4z02kdr0000gp/T/pip-install-4dhc591p/urlparse4/setup.py", line 46
        print "urlparse4/gurl.cpp not found and Cython failed to run to recreate it. Please install/upgrade Cython and try again."
                                                                                ^
    SyntaxError: Missing parentheses in call to 'print'. Did you mean print("urlparse4/gurl.cpp not found and Cython failed to run to recreate it. Please install/upgrade Cython and try again.")?
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

</code>```

Dears, what caused this problem and I can I resolve it? Many thanks in advance!

答:
The urlparse module only supports Python2.7. (See https://pypi.org/project/urlparse4/)

In Python3, you should use urllib.parse instead:

```<code>import urllib.parse
</code>```

More info: How can i import urlparse in python-3?

Body:
pip install urlparse4
Collecting urlparse4
  Using cached urlparse4-0.1.3.tar.gz (158 kB)
    ERROR: Command errored out with exit status 1:
     command: /opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/5d/s05y8m4107z_tgvnq4z02kdr0000gp/T/pip-install-4dhc591p/urlparse4/setup.py'"'"'; __file__='"'"'/private/var/folders/5d/s05y8m4107z_tgvnq4z02kdr0000gp/T/pip-install-4dhc591p/urlparse4/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/5d/s05y8m4107z_tgvnq4z02kdr0000gp/T/pip-pip-egg-info-me23x0q2
         cwd: /private/var/folders/5d/s05y8m4107z_tgvnq4z02kdr0000gp/T/pip-install-4dhc591p/urlparse4/
    Complete output (6 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/5d/s05y8m4107z_tgvnq4z02kdr0000gp/T/pip-install-4dhc591p/urlparse4/setup.py", line 46
        print "urlparse4/gurl.cpp not found and Cython failed to run to recreate it. Please install/upgrade Cython and try again."
                                                                                ^
    SyntaxError: Missing parentheses in call to 'print'. Did you mean print("urlparse4/gurl.cpp not found and Cython failed to run to recreate it. Please install/upgrade Cython and try again.")?
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Dears, what caused this problem and I can I resolve it? Many thanks in advance!

Body:
The urlparse module only supports Python2.7. (See https://pypi.org/project/urlparse4/)

In Python3, you should use urllib.parse instead:

import urllib.parse

More info: How can i import urlparse in python-3?


问:
Twitter timeline - How to include retweets?
This loads up a Twitter feed and displays the last tweet.

Is there a way to include and retrieve all the retweets in this function?

```<code>$(document).ready(function() {
    var url = "http://twitter.com/status/user_timeline/mytwittername.json?count=3&callback=?";
    var lastClass = "";
    $.getJSON(url,
        function(data){
            $.each(data, function(i, item) {
            // check for last tweet
            if (i == (data.length - 1)) {
                lastClass = "class='last'"
            }
            $("#twitter-content ul").append("<li " + lastClass + ">" + item.text.linkify().atify() + " <span class='created_at'>[" + relative_time(item.created_at) + " via " + item.source + "]</span></li>");
        });
    });

    $("#sidebar ul li:last-child").addClass("last");
});
</code>```

答:
Modify the url variable in your code to be the following:

http://api.twitter.com/1/statuses/user_timeline/mytwittername.json?count=3&include_rts=1&callback=?
```

The magic is in the include_rts=1 parameter which will cause retweets by the target user to be included in their timeline.

The statuses/user_timeline method does not require authentication, however if you do auth, you'll get an extra 200 API calls per hour. Note that the twitter.com REST methods are no longer supported, so be sure to use the versioned API methods when interacting with Twitter.

Body:
This loads up a Twitter feed and displays the last tweet.

Is there a way to include and retrieve all the retweets in this function?

$(document).ready(function() {
    var url = "http://twitter.com/status/user_timeline/mytwittername.json?count=3&callback=?";
    var lastClass = "";
    $.getJSON(url,
        function(data){
            $.each(data, function(i, item) {
            // check for last tweet
            if (i == (data.length - 1)) {
                lastClass = "class='last'"
            }
            $("#twitter-content ul").append("
" + item.text.linkify().atify() + " [" + relative_time(item.created_at) + " via " + item.source + "]
");
        });
    });

    $("#sidebar ul li:last-child").addClass("last");
});

Body:
Modify the url variable in your code to be the following:

http://api.twitter.com/1/statuses/user_timeline/mytwittername.json?count=3&include_rts=1&callback=?

The magic is in the include_rts=1 parameter which will cause retweets by the target user to be included in their timeline.

The statuses/user_timeline method does not require authentication, however if you do auth, you'll get an extra 200 API calls per hour. Note that the twitter.com REST methods are no longer supported, so be sure to use the versioned API methods when interacting with Twitter.


问:
Export data to Excel in Laravel
I want to make export data into excel in my project, i have made it, but after I check the results, the results  doesnt like what I want. here I would like to make a result there is a title table.

This code my controller:

```<code>public function getExport(){
        Excel::create('Export data', function($excel) {

        $excel->sheet('Sheet 1', function($sheet) {

            $products=DB::table('log_patrols')
            ->join("cms_companies","cms_companies.id","=","log_patrols.id_cms_companies")
            ->join("securities","securities.id","=","log_patrols.id_securities")
            ->select("log_patrols.*","cms_companies.name as nama_companies","securities.name as nama_security")
            ->get();
                foreach($products as $product) {
                 $data[] = array(
                    $product->date_start,
                    $product->date_end,
                    $product->condition_status,
                    $product->nama_security,
                    $product->nama_companies,
                );
            }
            $sheet->fromArray($data);
        });
    })->export('xls');
    }
</code>```

this my problem result :

and it should be :

my problem is how to change the number into text what i want in the header table.

what improvements do i have to make to the code to achieve my goal?

NB : i use maatwebsite/excel

答:
Try this in your controller</p>

```<code>$data=Insertion::get()->toArray();
    return Excel::create('yourfilename', function($excel) use ($data) {
        $excel->sheet('mySheet', function($sheet) use ($data)
        {
            $sheet->cell('A1:C1',function($cell)
            {
                $cell->setAlignment('center');
                $cell->setFontWeight('bold');
            });

            $sheet->cell('A:C',function($cell)
            {
                $cell->setAlignment('center');
            });

            $sheet->cell('A1', function($cell)
            {
                $cell->setValue('S.No');

            });
            $sheet->cell('B1', function($cell)
            {
                $cell->setValue('Name');
            });
            $sheet->cell('C1', function($cell)
            {
                $cell->setValue('Father Name');
            });
            if (!empty($data)) {
                $sno=1;
                foreach ($data as $key => $value)
                {
                    $i= $key+2;
                    $sheet->cell('A'.$i, $sno);
                    $sheet->cell('B'.$i, $value['name']);
                    $sheet->cell('C'.$i, $value['fathername']);
                    $sno++;
                }
            }
        });
    })->download(xlsx);
</code>```

Title: Export data to Excel in Laravel

Body:
I want to make export data into excel in my project, i have made it, but after I check the results, the results  doesnt like what I want. here I would like to make a result there is a title table.

This code my controller:

public function getExport(){
        Excel::create('Export data', function($excel) {

        $excel->sheet('Sheet 1', function($sheet) {

            $products=DB::table('log_patrols')
            ->join("cms_companies","cms_companies.id","=","log_patrols.id_cms_companies")
            ->join("securities","securities.id","=","log_patrols.id_securities")
            ->select("log_patrols.*","cms_companies.name as nama_companies","securities.name as nama_security")
            ->get();
                foreach($products as $product) {
                 $data[] = array(
                    $product->date_start,
                    $product->date_end,
                    $product->condition_status,
                    $product->nama_security,
                    $product->nama_companies,
                );
            }
            $sheet->fromArray($data);
        });
    })->export('xls');
    }

this my problem result :

and it should be :

my problem is how to change the number into text what i want in the header table.

what improvements do i have to make to the code to achieve my goal?

NB : i use maatwebsite/excel

Body:
Try this in your controller

$data=Insertion::get()->toArray();
    return Excel::create('yourfilename', function($excel) use ($data) {
        $excel->sheet('mySheet', function($sheet) use ($data)
        {
            $sheet->cell('A1:C1',function($cell)
            {
                $cell->setAlignment('center');
                $cell->setFontWeight('bold');
            });

            $sheet->cell('A:C',function($cell)
            {
                $cell->setAlignment('center');
            });

            $sheet->cell('A1', function($cell)
            {
                $cell->setValue('S.No');

            });
            $sheet->cell('B1', function($cell)
            {
                $cell->setValue('Name');
            });
            $sheet->cell('C1', function($cell)
            {
                $cell->setValue('Father Name');
            });
            if (!empty($data)) {
                $sno=1;
                foreach ($data as $key => $value)
                {
                    $i= $key+2;
                    $sheet->cell('A'.$i, $sno);
                    $sheet->cell('B'.$i, $value['name']);
                    $sheet->cell('C'.$i, $value['fathername']);
                    $sno++;
                }
            }
        });
    })->download(xlsx);