问:
throw new ERR_INVALID_ARG_TYPE('first argument', nodeJS
I am having the following error and do not understan why. My objective is to do a post request when triggering a firebase function however I am getting an really weird error.

I am trying to do a post request in nodeJs and firebase however it gives me the following error:

```<code>
    functions: Beginning execution of "Klarna"
    ⚠  External network resource requested!
       - URL: "https://api.playground.klarna.com/payments/v1/sessions"
     - Be careful, this may be a production service.
    >  _http_outgoing.js:661
    >      throw new ERR_INVALID_ARG_TYPE('first argument',
    >      ^
    >
    >  TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer. Received an instance of Object
    >      at write_ (_http_outgoing.js:661:11)
    >      at ClientRequest.write (_http_outgoing.js:629:15)
    >      at Request.write (/Users/pedromiguell/Work/Nortb/8. software/foliepapper/node_modules/request/request.js:1494:27)
    >      at end (/Users/pedromiguell/Work/Nortb/8. software/foliepapper/node_modules/request/request.js:549:18)
    >      at Immediate._onImmediate (/Users/pedromiguell/Work/Nortb/8. software/foliepapper/node_modules/request/request.js:578:7)
    >      at processImmediate (internal/timers.js:456:21) {
    >    code: 'ERR_INVALID_ARG_TYPE'
    >  }

</code>```

this is the function:

```<code>exports.Klarna = functions.https.onRequest(async (req, res) => {
    const creds = req.body
    const Headers = () => {
            const token = `Basic  ${Buffer.from(
              `${"xxx"}:${"xxx"}`
            ).toString("base64")}`;
            return {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              Authorization: token,
            };
          };

    const url = "https://api.playground.klarna.com/payments/v1/sessions"

    request("https://api.playground.klarna.com/payments/v1/sessions", {
        method: 'POST',
        url: url,
        headers: Headers,
        body: creds
    },
        function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body)
            }
        }
    )
})
</code>```

答:
solved it</p>

```<code>exports.Klarna = functions.https.onRequest((req, res) => {
  const url = "https://api.playground.klarna.com/payments/v1/sessions";
  const creds = req.body;
  const token = `Basic  ${Buffer.from(
    `${"xxx"}:${"xxx"}`
  ).toString("base64")}`;

  request(
    "https://api.playground.klarna.com/payments/v1/sessions",
    {
      method: "POST",
      url: url,
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        Authorization: token,
      },
      Authorization: token,
      body: creds,
      json: true,
    },
    function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body);
      }
    }
  );
});
</code>```

Body:
I am having the following error and do not understan why. My objective is to do a post request when triggering a firebase function however I am getting an really weird error.

I am trying to do a post request in nodeJs and firebase however it gives me the following error:

    functions: Beginning execution of "Klarna"
    ⚠  External network resource requested!
       - URL: "https://api.playground.klarna.com/payments/v1/sessions"
     - Be careful, this may be a production service.
    >  _http_outgoing.js:661
    >      throw new ERR_INVALID_ARG_TYPE('first argument',
    >      ^
    >
    >  TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer. Received an instance of Object
    >      at write_ (_http_outgoing.js:661:11)
    >      at ClientRequest.write (_http_outgoing.js:629:15)
    >      at Request.write (/Users/pedromiguell/Work/Nortb/8. software/foliepapper/node_modules/request/request.js:1494:27)
    >      at end (/Users/pedromiguell/Work/Nortb/8. software/foliepapper/node_modules/request/request.js:549:18)
    >      at Immediate._onImmediate (/Users/pedromiguell/Work/Nortb/8. software/foliepapper/node_modules/request/request.js:578:7)
    >      at processImmediate (internal/timers.js:456:21) {
    >    code: 'ERR_INVALID_ARG_TYPE'
    >  }

this is the function:

exports.Klarna = functions.https.onRequest(async (req, res) => {
    const creds = req.body
    const Headers = () => {
            const token = `Basic  ${Buffer.from(
              `${"xxx"}:${"xxx"}`
            ).toString("base64")}`;
            return {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              Authorization: token,
            };
          };

    const url = "https://api.playground.klarna.com/payments/v1/sessions"

    request("https://api.playground.klarna.com/payments/v1/sessions", {
        method: 'POST',
        url: url,
        headers: Headers,
        body: creds
    },
        function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body)
            }
        }
    )
})

Body:
solved it

exports.Klarna = functions.https.onRequest((req, res) => {
  const url = "https://api.playground.klarna.com/payments/v1/sessions";
  const creds = req.body;
  const token = `Basic  ${Buffer.from(
    `${"xxx"}:${"xxx"}`
  ).toString("base64")}`;

  request(
    "https://api.playground.klarna.com/payments/v1/sessions",
    {
      method: "POST",
      url: url,
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        Authorization: token,
      },
      Authorization: token,
      body: creds,
      json: true,
    },
    function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body);
      }
    }
  );
});


来源: stackexchange

问:
how to choose a specific direcrory entry within directory iterator
My question is very specific, sorry for that.

From this code:

```<code>int i = 0;
for(auto& p: recursive_directory_iterator("stru1")) {
    ++i;
    cout << "Index no." << i <<  p.path() << '\n';
</code>```

in this the loop will iterates over every entity in the directory and output the path with their index number.

My question is if there is anyway where, after the loop is done, I can choose a specific index and display the content of the index's directory?

答:
The only way to be certain you get the same entry (if there are concurrent modifications to that directory) would be to build a vector during iteration:</p>

```<code>std::size_t i = 0;
std::vector<std::filesystem::directory_entry> entries;
for(auto& p: std::filesystem::recursive_directory_iterator("stru1")) {
    ++i;
    std::cout << "Index no." << i <<  p.path() << '\n';
    entries.push_back(p);
}

if (std::cin >> i && i >= 1 && i <= entries.size()) {
    auto const & entry = entries[i - 1];
    // use entry
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My question is very specific, sorry for that.

From this code:

int i = 0;
for(auto& p: recursive_directory_iterator("stru1")) {
    ++i;
    cout << "Index no." << i <<  p.path() << '\n';

in this the loop will iterates over every entity in the directory and output the path with their index number.

My question is if there is anyway where, after the loop is done, I can choose a specific index and display the content of the index's directory?

Body:
The only way to be certain you get the same entry (if there are concurrent modifications to that directory) would be to build a vector during iteration:

std::size_t i = 0;
std::vector<std::filesystem::directory_entry> entries;
for(auto& p: std::filesystem::recursive_directory_iterator("stru1")) {
    ++i;
    std::cout << "Index no." << i <<  p.path() << '\n';
    entries.push_back(p);
}

if (std::cin >> i && i >= 1 && i <= entries.size()) {
    auto const & entry = entries[i - 1];
    // use entry
}


问:
Application failure in Release mode
I have a problem with my ASP.NET application. It has been developed for about a year or so without disabling Debug mode. I wanted to test if it works without debug and it isn't but, when I set debug="true", it works fine.

When I try to open application for the first time it gives me "Server not available" error. In the events log I have two errors:

.NET Runtime 2.0 error - Faulting application aspnet_wp.exe, version 2.0.50727.3082, stamp 492b8702, faulting module kernel32.dll, version 5.1.2600.3119, stamp 46239c44, debug? 0, fault address 0x00012a5b.

ASP.NET 2.0.50727.0 - Unexpected end of process aspnet_wp.exe (PID: 4932) (it may be written a little different, it's translated).

My IIS version is 5.1 running on Windows XP.

I'll be grateful for any suggestions.

UPDATE:
Change of debug mode is made in the web.config

答:
Try clearing the temporary DLLs

```<code>iisreset /stop
del "%windir%\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\*.*" /s/f
iisreset /start
</code>```

Make sure you are properly freeing unmanaged resources. Using USING and .Dispose.

OwnerDisplayName: Migol

ContentLicense: CC BY-SA 2.5

Title: Application failure in Release mode

LastEditorDisplayName: Pax

Body:
Try clearing the temporary DLLs

iisreset /stop
del "%windir%\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\*.*" /s/f
iisreset /start

Make sure you are properly freeing unmanaged resources. Using USING and .Dispose.

OwnerDisplayName: Hafthor

LastEditorDisplayName: Hafthor


问:
How to use ServiceStack OpenApiFeature/Swagger with api description and response examples?
Is there a way to add a description to the api (not just to individual routes) and update api version and add example responses/resquests using the OpenApiFeature in ServiceStack? I can't find anything in the documentation about these pieces of the swagger ui.

I tried using the Api attribute to add the description but that doesn't seem to work.

答:
The only declarative Attributes that can annotate individual Services are documented on the Open API docs. Here's a fully annotated example:

```<code>[Tag("TheTag")]
[Api("SwaggerTest Service Description")]
[ApiResponse(HttpStatusCode.BadRequest, "Your request was not understood")]
[ApiResponse(HttpStatusCode.InternalServerError, "Oops, something broke")]
[Route("/swagger", "GET", Summary = @"GET / Summary", Notes = "GET / Notes")]
[Route("/swagger/{Name}", "GET", Summary = @"GET Summary", Notes = "GET /Name Notes")]
[Route("/swagger/{Name}", "POST", Summary = @"POST Summary", Notes = "POST /Name Notes")]
public class SwaggerExample
{
    [ApiMember(Description = "Color Description",
               ParameterType = "path", DataType = "string", IsRequired = true)]
    [ApiAllowableValues("Name", typeof(MyColor))] //Enum
    public string Name { get; set; }

    [ApiMember]
    [ApiAllowableValues("Color", typeof(MyColor))] //Enum
    public MyColor Color { get; set; }

    [ApiMember(Description = "Aliased Description", DataType="string", IsRequired=true)]
    [DataMember(Name = "Aliased")]
    public string Original { get; set; }

    [ApiMember(Description = "Not Aliased", DataType="string", IsRequired=true)]
    public string NotAliased { get; set; }

    [ApiMember(IsRequired = false, AllowMultiple = true)]
    public DateTime[] MyDateBetween { get; set; }

    [ApiMember(Description = "Nested model 1", DataType = "SwaggerNestedModel")]
    public SwaggerNestedModel NestedModel1 { get; set; }

    [ApiMember(Description = "Nested model 2", DataType = "SwaggerNestedModel2")]
    public SwaggerNestedModel2 NestedModel2 { get; set; }
}
</code>```

The other annotation Open API allows is grouping logical operations by Tag which you would use annotate in ServiceStack with the [Tag] attribute that you can then provide a description for when registering the OpenApiFeature Plugin, e.g:

```<code>Plugins.Add(new OpenApiFeature
{
    Tags =
    {
        new OpenApiTag
        {
            Name = "TheTag",
            Description = "TheTag Description",
            ExternalDocs = new OpenApiExternalDocumentation
            {
                Description = "Link to External Docs Desc",
                Url = "http://example.org/docs/path",
            }
        }
    }
});
</code>```

Body:
The only declarative Attributes that can annotate individual Services are documented on the Open API docs. Here's a fully annotated example:

[Tag("TheTag")]
[Api("SwaggerTest Service Description")]
[ApiResponse(HttpStatusCode.BadRequest, "Your request was not understood")]
[ApiResponse(HttpStatusCode.InternalServerError, "Oops, something broke")]
[Route("/swagger", "GET", Summary = @"GET / Summary", Notes = "GET / Notes")]
[Route("/swagger/{Name}", "GET", Summary = @"GET Summary", Notes = "GET /Name Notes")]
[Route("/swagger/{Name}", "POST", Summary = @"POST Summary", Notes = "POST /Name Notes")]
public class SwaggerExample
{
    [ApiMember(Description = "Color Description",
               ParameterType = "path", DataType = "string", IsRequired = true)]
    [ApiAllowableValues("Name", typeof(MyColor))] //Enum
    public string Name { get; set; }

    [ApiMember]
    [ApiAllowableValues("Color", typeof(MyColor))] //Enum
    public MyColor Color { get; set; }

    [ApiMember(Description = "Aliased Description", DataType="string", IsRequired=true)]
    [DataMember(Name = "Aliased")]
    public string Original { get; set; }

    [ApiMember(Description = "Not Aliased", DataType="string", IsRequired=true)]
    public string NotAliased { get; set; }

    [ApiMember(IsRequired = false, AllowMultiple = true)]
    public DateTime[] MyDateBetween { get; set; }

    [ApiMember(Description = "Nested model 1", DataType = "SwaggerNestedModel")]
    public SwaggerNestedModel NestedModel1 { get; set; }

    [ApiMember(Description = "Nested model 2", DataType = "SwaggerNestedModel2")]
    public SwaggerNestedModel2 NestedModel2 { get; set; }
}

The other annotation Open API allows is grouping logical operations by Tag which you would use annotate in ServiceStack with the [Tag] attribute that you can then provide a description for when registering the OpenApiFeature Plugin, e.g:

Plugins.Add(new OpenApiFeature
{
    Tags =
    {
        new OpenApiTag
        {
            Name = "TheTag",
            Description = "TheTag Description",
            ExternalDocs = new OpenApiExternalDocumentation
            {
                Description = "Link to External Docs Desc",
                Url = "http://example.org/docs/path",
            }
        }
    }
});


问:
Merge two dataframes based on an exact match in one column and match within an error in another column in R
I have a dataframe

```<code>df1:

A  time B  C
a1 t1   b1 c1
a2 t2   b2 c2
a3 t3   b3 c3
</code>```

and another dataframe

```<code>df2:

A  time D E
a1 t4   d1 e1
a2 t5   d2 e2
a3 t6   d3 e3
</code>```

Assume time is in the format yyyy-mm-dd hh:mm:ss e.g. 2019-08-16 15:06:38

and lets assume:

```<code>t4 - t1 = 40 seconds
t5 - t2 = -5 seconds
t6 - t3 = 120 seconds
</code>```

I would like to merge these dataframes based on exact match on A and a match on column time with some acceptable difference between the dataframes , for example with in 1 min.

So my output would look like:

```<code>df3 :

A  B  C  D  E time(from df1)
a1 b1 c1 d1 e1 t1
a2 b2 c2 d2 e2 t2
</code>```

See that a3 is not there because even though it matches on column A the difference in time exceeded the acceptable limit.

How can I do this? If not for the "acceptable difference" part I would do like:

```<code>merge(df1, df2, by = c("A", "time"))
</code>```

答: I've done similar joins using sqldf or foverlaps from data.table.

Body:
I have a dataframe

df1:

A  time B  C
a1 t1   b1 c1
a2 t2   b2 c2
a3 t3   b3 c3

and another dataframe

df2:

A  time D E
a1 t4   d1 e1
a2 t5   d2 e2
a3 t6   d3 e3

Assume time is in the format yyyy-mm-dd hh:mm:ss e.g. 2019-08-16 15:06:38

and lets assume:

t4 - t1 = 40 seconds
t5 - t2 = -5 seconds
t6 - t3 = 120 seconds

I would like to merge these dataframes based on exact match on A and a match on column time with some acceptable difference between the dataframes , for example with in 1 min.

So my output would look like:

df3 :

A  B  C  D  E time(from df1)
a1 b1 c1 d1 e1 t1
a2 b2 c2 d2 e2 t2

See that a3 is not there because even though it matches on column A the difference in time exceeded the acceptable limit.

How can I do this? If not for the "acceptable difference" part I would do like:

merge(df1, df2, by = c("A", "time"))


问:
GetProperties() order is not consistent (.NET Core 2 & .NET Core 3)
I use reflection to get the property list of a class. I need to get the names in the exact same order as they are declared in the code.

When I only call typeof(TypeOfClass).GetProperties() I get the properties in the good order.

Some code added in my project made some reflection reads that brake my build.

It took a while to find it but after a couple hours, I've found that you get a property by name GetProperty("name") it can change the order on further call of GetProperties()

Here is the code (Console App) to reproduce the same issue:

class Program
    {
        private class SomeClass
        {
            public int IntProperty { get; set; }
            public string StringProperty { get; set; }
            public DateTime DateProperty { get; set; }

        }
        static void Main(string[] args)
        {
            PropertyInfo[] propertyInfos = typeof(SomeClass).GetProperties();
            Console.WriteLine(string.Join(", ",propertyInfos.Select(p => p.Name)));
            //Output: IntProperty, StringProperty, DateProperty
        }
    }
```

<p>Same code with an access to <code>GetProperty</code> before <code>GetProperties</code></p>

<pre class="lang-cs prettyprint-override"><code>class Program
    {
        private class SomeClass
        {
            public int IntProperty { get; set; }
            public string StringProperty { get; set; }
            public DateTime DateProperty { get; set; }

        }

        static void Main(string[] args)
        {
            PropertyInfo dateProp = typeof(SomeClass).GetProperty("DateProperty");

            PropertyInfo[] propertyInfos = typeof(SomeClass).GetProperties();
            Console.WriteLine(string.Join(", ",propertyInfos.Select(p => p.Name)));
            //Output: DateProperty, IntProperty, StringProperty
        }
    }
</code>```

If you execute the 2nd code block, it will return the properties with the DateProperty as the first index!?

Does anybody knows why, Is there a way to ensure that GetProperties will always return the same list in the same order?

PS: I've only tried this with .netcore 3.1. I assume that this might not be a bug in previous versions.

Thanks

答:
Short answer: you can't. As stated in the documentation:

The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.

The order in which the properties are returned are considered an implementation detail, and you cannot rely on that order.

To determine the order in which the properties are defined in the source code, you'll need access to the source code.

Body:
I use reflection to get the property list of a class. I need to get the names in the exact same order as they are declared in the code.

When I only call typeof(TypeOfClass).GetProperties() I get the properties in the good order.

Some code added in my project made some reflection reads that brake my build.

It took a while to find it but after a couple hours, I've found that you get a property by name GetProperty("name") it can change the order on further call of GetProperties()

Here is the code (Console App) to reproduce the same issue:

class Program
    {
        private class SomeClass
        {
            public int IntProperty { get; set; }
            public string StringProperty { get; set; }
            public DateTime DateProperty { get; set; }

        }
        static void Main(string[] args)
        {
            PropertyInfo[] propertyInfos = typeof(SomeClass).GetProperties();
            Console.WriteLine(string.Join(", ",propertyInfos.Select(p => p.Name)));
            //Output: IntProperty, StringProperty, DateProperty
        }
    }

Same code with an access to GetProperty before GetProperties

class Program
    {
        private class SomeClass
        {
            public int IntProperty { get; set; }
            public string StringProperty { get; set; }
            public DateTime DateProperty { get; set; }

        }

        static void Main(string[] args)
        {
            PropertyInfo dateProp = typeof(SomeClass).GetProperty("DateProperty");

            PropertyInfo[] propertyInfos = typeof(SomeClass).GetProperties();
            Console.WriteLine(string.Join(", ",propertyInfos.Select(p => p.Name)));
            //Output: DateProperty, IntProperty, StringProperty
        }
    }

If you execute the 2nd code block, it will return the properties with the DateProperty as the first index!?

Does anybody knows why, Is there a way to ensure that GetProperties will always return the same list in the same order?

PS: I've only tried this with .netcore 3.1. I assume that this might not be a bug in previous versions.

Thanks


问:
Number of words in a Swift String for word count calculation
I want to make a procedure to  find out how many words are there in a string, separated by space, or comma, or some other character. And then add up the total later.

I'm making an average calculator, so I want the total count of data and then add up all the words.

答:
If you are aiming at fresh operating systems (such as iOS13) there is no need to reinvent the wheel trying to count words by yourself. You can benefit from a powerful API specially dedicated for this purpose. It can split text into words for many languages you don't even know about, it can and classify parts of speech show lemmas, detect script and more.
Check this in playground.

```<code>import NaturalLanguage
let taggerLexical = NLTagger(tagSchemes: [.lexicalClass, .lemma])
let txt = "I'm an architector  by 90%. My family  and I live in ."
taggerLexical.string = txt
let lexicalTags = NSCountedSet()
taggerLexical.enumerateTags(in: txt.startIndex..<txt.endIndex, unit: .word, scheme: .lexicalClass, options: [.omitPunctuation, .omitWhitespace]) { tag, tokenRange in
    if let tag = tag {
        lexicalTags.add(tag)
        let lemma = taggerLexical.tag(at: tokenRange.lowerBound, unit: .word, scheme: .lemma).0?.rawValue ?? ""
        let word = String(txt[tokenRange])
        print("\(word): \(tag.rawValue)\(word == lemma ? "" : " | Lemma: \(lemma) " )")
    }
    return true
}
let sortedLexicalTagCount = lexicalTags.allObjects.map({ (($0 as! NLTag), lexicalTags.count(for: $0))}).sorted(by: {$0.1 > $1.1})
print("Total word count: \(sortedLexicalTagCount.map({ $0.1}).reduce(0, +)) \nTotal word count without grapheme clusters: \(sortedLexicalTagCount.compactMap({ $0.0 == NLTag.otherWord ? nil : $0.1 }).reduce(0, +)) \nDetails: \(sortedLexicalTagCount.map {($0.0.rawValue, $0.1)})")
</code>```

```<code>// Output:
I: Pronoun
'm: Verb | Lemma: be
an: Determiner
architector: Adjective | Lemma:
: OtherWord | Lemma:
by: Preposition
90: Number | Lemma:
My: Determiner | Lemma: I
family: Noun
: OtherWord | Lemma:
and: Conjunction
I: Pronoun
live: Verb
in: Preposition
: OtherWord | Lemma:
Total word count: 15
Total word count without grapheme clusters: 12
Details: [("OtherWord", 3), ("Pronoun", 2), ("Determiner", 2), ("Verb", 2), ("Preposition", 2), ("Number", 1), ("Noun", 1), ("Conjunction", 1), ("Adjective", 1)]
</code>```

For older Apple operating systems using preceding linguisticTags API is an option.

```<code>import Foundation
let linguisticTags = txt.linguisticTags(in: text.startIndex..., scheme: NSLinguisticTagScheme.tokenType.rawValue)
print("Total word count: \(linguisticTags.filter({ [NSLinguisticTag.word.rawValue, NSLinguisticTag.other.rawValue].contains($0) }).count)\nTotal word count without grapheme clusters: \(linguisticTags.filter({ [NSLinguisticTag.word.rawValue].contains($0) }).count)")
// Output:
Total word count: 15
Total word count without grapheme clusters: 12
</code>```

Another option is to use NSRegularExpression. It knows how match word boundaries (\\b), word (\\w) and non-word (\\W) symbols.
Using .numberOfMatches(in: , range:..) looks better from the calculation effectiveness point of view since it returns only number of matches but not matches themselves. Yet there are issues for strings with emojis for this approach.

```<code>extension String {
    private var regexMatchWords: NSRegularExpression? { try? NSRegularExpression(pattern: "\\w+") }
    var aproxWordCount: Int {
        guard let regex = regexMatchWords else { return 0 }
        return regex.numberOfMatches(in: self, range: NSRange(self.startIndex..., in: self))
    }
    var wordCount: Int {
        guard let regex = regexMatchWords else { return 0 }
        return regex.matches(in: self, range: NSRange(self.startIndex..., in: self)).reduce(0) { (r, match) in
                    r + (Range(match.range, in: self) == nil ? 0 : 1)
                }

    }
    var words: [String] {
        var w = [String]()
        guard let regex = regexMatchWords else { return [] }
        regex.enumerateMatches(in: self, range: NSRange(self.startIndex..., in: self)) { (match, _, _) in
            guard  let match = match else { return }
            guard let range = Range(match.range, in: self) else { return }
            w.append(self[range])
        }
        return w
    }
}
let text = "We're a family  of 4. Next week we'll go to ."
print("Arpoximate word count: \(text.aproxWordCount)\nWord count: \(text.wordCount)\nWords:\(text.words)")
// Output:
Arpoximate word count: 15
Word count: 12
Words:["We", "re", "a", "family", "of", "4", "Next", "week", "we", "ll", "go", "to"]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you are aiming at fresh operating systems (such as iOS13) there is no need to reinvent the wheel trying to count words by yourself. You can benefit from a powerful API specially dedicated for this purpose. It can split text into words for many languages you don't even know about, it can and classify parts of speech show lemmas, detect script and more.
Check this in playground.

import NaturalLanguage
let taggerLexical = NLTagger(tagSchemes: [.lexicalClass, .lemma])
let txt = "I'm an architector  by 90%. My family  and I live in ."
taggerLexical.string = txt
let lexicalTags = NSCountedSet()
taggerLexical.enumerateTags(in: txt.startIndex..<txt.endIndex, unit: .word, scheme: .lexicalClass, options: [.omitPunctuation, .omitWhitespace]) { tag, tokenRange in
    if let tag = tag {
        lexicalTags.add(tag)
        let lemma = taggerLexical.tag(at: tokenRange.lowerBound, unit: .word, scheme: .lemma).0?.rawValue ?? ""
        let word = String(txt[tokenRange])
        print("\(word): \(tag.rawValue)\(word == lemma ? "" : " | Lemma: \(lemma) " )")
    }
    return true
}
let sortedLexicalTagCount = lexicalTags.allObjects.map({ (($0 as! NLTag), lexicalTags.count(for: $0))}).sorted(by: {$0.1 > $1.1})
print("Total word count: \(sortedLexicalTagCount.map({ $0.1}).reduce(0, +)) \nTotal word count without grapheme clusters: \(sortedLexicalTagCount.compactMap({ $0.0 == NLTag.otherWord ? nil : $0.1 }).reduce(0, +)) \nDetails: \(sortedLexicalTagCount.map {($0.0.rawValue, $0.1)})")

// Output:
I: Pronoun
'm: Verb | Lemma: be
an: Determiner
architector: Adjective | Lemma:
: OtherWord | Lemma:
by: Preposition
90: Number | Lemma:
My: Determiner | Lemma: I
family: Noun
: OtherWord | Lemma:
and: Conjunction
I: Pronoun
live: Verb
in: Preposition
: OtherWord | Lemma:
Total word count: 15
Total word count without grapheme clusters: 12
Details: [("OtherWord", 3), ("Pronoun", 2), ("Determiner", 2), ("Verb", 2), ("Preposition", 2), ("Number", 1), ("Noun", 1), ("Conjunction", 1), ("Adjective", 1)]

For older Apple operating systems using preceding linguisticTags API is an option.

import Foundation
let linguisticTags = txt.linguisticTags(in: text.startIndex..., scheme: NSLinguisticTagScheme.tokenType.rawValue)
print("Total word count: \(linguisticTags.filter({ [NSLinguisticTag.word.rawValue, NSLinguisticTag.other.rawValue].contains($0) }).count)\nTotal word count without grapheme clusters: \(linguisticTags.filter({ [NSLinguisticTag.word.rawValue].contains($0) }).count)")
// Output:
Total word count: 15
Total word count without grapheme clusters: 12

Another option is to use NSRegularExpression. It knows how match word boundaries (\\b), word (\\w) and non-word (\\W) symbols.
Using .numberOfMatches(in: , range:..) looks better from the calculation effectiveness point of view since it returns only number of matches but not matches themselves. Yet there are issues for strings with emojis for this approach.

extension String {
    private var regexMatchWords: NSRegularExpression? { try? NSRegularExpression(pattern: "\\w+") }
    var aproxWordCount: Int {
        guard let regex = regexMatchWords else { return 0 }
        return regex.numberOfMatches(in: self, range: NSRange(self.startIndex..., in: self))
    }
    var wordCount: Int {
        guard let regex = regexMatchWords else { return 0 }
        return regex.matches(in: self, range: NSRange(self.startIndex..., in: self)).reduce(0) { (r, match) in
                    r + (Range(match.range, in: self) == nil ? 0 : 1)
                }

    }
    var words: [String] {
        var w = [String]()
        guard let regex = regexMatchWords else { return [] }
        regex.enumerateMatches(in: self, range: NSRange(self.startIndex..., in: self)) { (match, _, _) in
            guard  let match = match else { return }
            guard let range = Range(match.range, in: self) else { return }
            w.append(self[range])
        }
        return w
    }
}
let text = "We're a family  of 4. Next week we'll go to ."
print("Arpoximate word count: \(text.aproxWordCount)\nWord count: \(text.wordCount)\nWords:\(text.words)")
// Output:
Arpoximate word count: 15
Word count: 12
Words:["We", "re", "a", "family", "of", "4", "Next", "week", "we", "ll", "go", "to"]


问:
How to use circular mode in stm32f429zi?
I am working on the DMA Peripheral , and i have some confusion about the circular mode`s parameters . i have tried to sort it out on my own . so i put an example and i want someone to tell me if i correctly understood it or i need someone to explain it for me
Assume that I want to keep transferring 128 Half-word from a peripheral to a memory .
assume:-

```<code>PSIZE=Half-Word(2bytes)
MSIZE=WORD(4bytes)
PBURST=16
</code>```

so according to the PSIZE being a half-word that means the beat is a half-word so in each burts i am going to transfer 16beats which are 16half-words correct?
according to the reference manual it is noted that

```<code>NDTR=multipleof(PBURST * (MSIZE/PSIZE))
</code>```

so in my example the NDTR is multiple of (32) correct?
up till now if i am correct , what is the value that should be written in the NDTR according to these configurations?and if i am wrong please guide me to the correct answer

答: I think the documentation is self explanatory:

Body:
I am working on the DMA Peripheral , and i have some confusion about the circular mode`s parameters . i have tried to sort it out on my own . so i put an example and i want someone to tell me if i correctly understood it or i need someone to explain it for me
Assume that I want to keep transferring 128 Half-word from a peripheral to a memory .
assume:-

PSIZE=Half-Word(2bytes)
MSIZE=WORD(4bytes)
PBURST=16

so according to the PSIZE being a half-word that means the beat is a half-word so in each burts i am going to transfer 16beats which are 16half-words correct?
according to the reference manual it is noted that

NDTR=multipleof(PBURST * (MSIZE/PSIZE))

so in my example the NDTR is multiple of (32) correct?
up till now if i am correct , what is the value that should be written in the NDTR according to these configurations?and if i am wrong please guide me to the correct answer


问:
Debugging Chromecast app displays error message
I have a custom Chromecast receiver that isn't working and I'm trying to figure out why.  When I cast to it from Chrome on my desktop my app starts up on the Chromecast but the Chromecast dialog just says Connecting...

And although my app does start up on my TV correctly, it seems like the sender eventually times out and kills it.  I receive the following error message:

```<code>chrome.cast.Error {code: "session_error", description: null, details: null}
</code>```

So I decided I'd try to debug it by going to http://192.168.x.x:9222.  That page loads up fine, but when I click the Remote Debugging (AppEngine) link, I get sent to a blank white page at https://chrome-devtools-frontend.appspot.com/serve_rev/.........  In the Chrome dev tools I can see the following errors:

```<code>
shell.js:3123 Uncaught TypeError: document.registerElement is not a function
    at Object.UI.registerCustomElement (shell.js:3123)
    at shell.js:3135
    at shell.js:3137
UI.registerCustomElement @ shell.js:3123
(anonymous) @ shell.js:3135
(anonymous) @ shell.js:3137
devtools_app.js:2 Uncaught ReferenceError: SDK is not defined
    at devtools_app.js:2
(anonymous) @ devtools_app.js:2
inspector.js:2 Uncaught ReferenceError: SDK is not defined
    at inspector.js:2
</code>```

I'm using a 1st Gen Chromecast with firmware version 1.36.159268.

The error seems to be the same as described here: Unable to Open Chrome Inspector & Debug Chromecast Custom Receiver

答:
You can use an old version of Chromium -- can't find old versions of Chrome.

https://www.chromium.org/getting-involved/download-chromium
(under "Downloading old builds of Chrome / Chromium")

Here's an example of one (~version 77 for macOS):
https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Mac%2F668249%2Fchrome-mac.zip?generation=1560304902825342&alt=media

Body:
I have a custom Chromecast receiver that isn't working and I'm trying to figure out why.  When I cast to it from Chrome on my desktop my app starts up on the Chromecast but the Chromecast dialog just says Connecting...

And although my app does start up on my TV correctly, it seems like the sender eventually times out and kills it.  I receive the following error message:

chrome.cast.Error {code: "session_error", description: null, details: null}

So I decided I'd try to debug it by going to http://192.168.x.x:9222.  That page loads up fine, but when I click the Remote Debugging (AppEngine) link, I get sent to a blank white page at https://chrome-devtools-frontend.appspot.com/serve_rev/.........  In the Chrome dev tools I can see the following errors:

shell.js:3123 Uncaught TypeError: document.registerElement is not a function
    at Object.UI.registerCustomElement (shell.js:3123)
    at shell.js:3135
    at shell.js:3137
UI.registerCustomElement @ shell.js:3123
(anonymous) @ shell.js:3135
(anonymous) @ shell.js:3137
devtools_app.js:2 Uncaught ReferenceError: SDK is not defined
    at devtools_app.js:2
(anonymous) @ devtools_app.js:2
inspector.js:2 Uncaught ReferenceError: SDK is not defined
    at inspector.js:2

I'm using a 1st Gen Chromecast with firmware version 1.36.159268.

The error seems to be the same as described here: Unable to Open Chrome Inspector & Debug Chromecast Custom Receiver


问:
Using AWS Glue with Mysql in my EC2 Instance
I am trying to connect my ec2 installed/mysql with Glue, the purpose is to xtract some information and moved to redshift, but i am receiving the following error:

Check that your connection definition references your JDBC database with correct URL syntax, username, and password. Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

This is the format that i am using jdbc:mysql://host:3306/database

I am using the same vpc, same SG, same subnet for the instance.

i know the user/password are correct because i am connected to the database with sql developer.

What i need to check? Is it possible to use AWS Glue with mysql in my instance?

Thanks in advance.

答:
Yes, It is possible to use AWS Glue with your MySQL running in your EC2 Instance but Before, you should first use DMS to migrate your databases.

More over, your target database (Redshift) has a different schema than the source database (MySQL), that's what we call heterogeneous database migrations (the schema structure, data types, and database code of source databases are quite differents), you need AWS SCT.

Check this out :

As you can see, I'm not sure you can migrate straight from MySQL in an EC2 instance to Amazon Redshift.

Hope this helps


问:
How to read particular HASH in ARRAY using string key?
I want to ask you how can I read the specific hash from array [{},{},{}] using string key?

First is an initialization

There are 2x writing hashes to array

I need to read the particular hash using string key

How can I do that?

```<code>sub SpecComp {
    my ($this, $comp_name, $component, $index) = @_;
    if ($component) {
        $this->{specComp}[$index] =  $component;
    }
    my $ref = \$this; #?????

    return $ref; #?????
}

sub new {
    my $this = {};
    my $this->{specComp} = [];

    return $this;
}

#  Initialize
my $ts = new test();

#  I want to write - it is OK
my $Comp1 = {
    "ANOZZLE" => "first",
};

$ts->SpecComp("ANOZZLE", $Comp1, 1);

my $Comp2 = {
    "BBUCKET" => "second",
};

$ts->SpecComp("BBUCKET", $Comp2, 2);

#  I want to read - is not OK

my $out = SpecComp("ANOZZLE");

print $out; # ???????? I want output $Comp1
</code>```

答:
When using Object Orientation, use bless to actually bind a reference to a class.

To output a structure, use Data::Dumper.

It's possible to find an element in an array using grep (see below).

```<code>#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;

{   package My::Object;

    sub new {
        bless { specComp => [] }, shift
    }

    sub SpecComp {
        my ($self, $component, $index) = @_;
        if ($index) {
            $self->{specComp}[$index] =  $component;
        } else {
            return (grep $_ && exists $_->{$component},
                    @{ $self->{specComp} })[0];
        }
    }
}

my $ts = 'My::Object'->new;
my $Comp1 = {
    ANOZZLE => 'first',
};
$ts->SpecComp($Comp1, 1);

my $Comp2 = {
    BBUCKET => 'second',
};
$ts->SpecComp($Comp2, 2);

my $out = $ts->SpecComp('ANOZZLE');
print Dumper($out);
</code>```

But do you really need to store the hash references in an array? You don't show why you need it, and using just plain hash would make retrieval much easier.

```<code>#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;

{   package My::Object;

    sub new {
        bless { specComp => {} }, shift
    }

    sub SpecComp {
        my ($self, $component) = @_;
        if (ref $component) {
            my ($key) = keys %$component;
            $self->{specComp}{$key} = $component->{$key};
            $self->{index}{$key} = ++$self->{INDEX};
        } else {
            return { $component => $self->{specComp}{$component} }
        }
    }
}

my $ts = 'My::Object'->new;
my $Comp1 = {
    ANOZZLE => 'first',
};
$ts->SpecComp($Comp1);

my $Comp2 = {
    BBUCKET => 'second',
};
$ts->SpecComp($Comp2);

my $out = $ts->SpecComp('ANOZZLE');
print Dumper($out);
</code>```

Body:
I want to ask you how can I read the specific hash from array [{},{},{}] using string key?

First is an initialization

There are 2x writing hashes to array

I need to read the particular hash using string key

How can I do that?

sub SpecComp {
    my ($this, $comp_name, $component, $index) = @_;
    if ($component) {
        $this->{specComp}[$index] =  $component;
    }
    my $ref = \$this; #?????

    return $ref; #?????
}

sub new {
    my $this = {};
    my $this->{specComp} = [];

    return $this;
}

#  Initialize
my $ts = new test();

#  I want to write - it is OK
my $Comp1 = {
    "ANOZZLE" => "first",
};

$ts->SpecComp("ANOZZLE", $Comp1, 1);

my $Comp2 = {
    "BBUCKET" => "second",
};

$ts->SpecComp("BBUCKET", $Comp2, 2);

#  I want to read - is not OK

my $out = SpecComp("ANOZZLE");

print $out; # ???????? I want output $Comp1

Body:
When using Object Orientation, use bless to actually bind a reference to a class.

To output a structure, use Data::Dumper.

It's possible to find an element in an array using grep (see below).

#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;

{   package My::Object;

    sub new {
        bless { specComp => [] }, shift
    }

    sub SpecComp {
        my ($self, $component, $index) = @_;
        if ($index) {
            $self->{specComp}[$index] =  $component;
        } else {
            return (grep $_ && exists $_->{$component},
                    @{ $self->{specComp} })[0];
        }
    }
}

my $ts = 'My::Object'->new;
my $Comp1 = {
    ANOZZLE => 'first',
};
$ts->SpecComp($Comp1, 1);

my $Comp2 = {
    BBUCKET => 'second',
};
$ts->SpecComp($Comp2, 2);

my $out = $ts->SpecComp('ANOZZLE');
print Dumper($out);

But do you really need to store the hash references in an array? You don't show why you need it, and using just plain hash would make retrieval much easier.

#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;

{   package My::Object;

    sub new {
        bless { specComp => {} }, shift
    }

    sub SpecComp {
        my ($self, $component) = @_;
        if (ref $component) {
            my ($key) = keys %$component;
            $self->{specComp}{$key} = $component->{$key};
            $self->{index}{$key} = ++$self->{INDEX};
        } else {
            return { $component => $self->{specComp}{$component} }
        }
    }
}

my $ts = 'My::Object'->new;
my $Comp1 = {
    ANOZZLE => 'first',
};
$ts->SpecComp($Comp1);

my $Comp2 = {
    BBUCKET => 'second',
};
$ts->SpecComp($Comp2);

my $out = $ts->SpecComp('ANOZZLE');
print Dumper($out);


问:
Nothing as delimiter like sep=None or how to remove comma?
I am doing the cartesian product from 2 csv files with each 1 column. The outcome should be a new csv with with 1 column in which are all the products.
Since the default delimiter is comma and sep=None or similar isn't allowed, how is it possible to have the product in one column without any comma?
First I thought the imported file 00 would have the delimiter but with replace and delim_whitespace=False I guess I made sure it doesn't comes from there (its anyways just one column).
I also tried to merge or join column 1 and column 2 of the final file with the cartesian product but coulnd't figure out how. Further I tried it with replace(",", "") but it didn't change the outcome.

This is the code:

```<code>import pandas as pd

vornamen = pd.read_csv(...\00.csv",header=None, encoding= 'unicode_escape')
nachnamen = pd.read_csv(...\01.csv",header=None, encoding= 'unicode_escape')

vornamen['_tmp'] = 1
nachnamen['_tmp'] = 1

df = pd.merge(vornamen,nachnamen,on='_tmp').drop('_tmp',axis=1)
df.to_csv(...\03.csv",header=None,index=False, sep="\t")
</code>```

答:
Since the df.to_csv method creates a CSV file, it creates the same amount of columns in the output file as are in the dataframe. Since you have 2 columns in the df dataframe, pandas will try to save 2 columns:

...

>>> df = pd.merge(vornamen,nachnamen,on='_tmp').drop('mp',axis=1)
>>> df
   0_x      0_y
0  Jan     Hart
1  Jan  Johnson
2  Bob     Hart
3  Bob  Johnson
```

<p>In order to have a single column, you can combine these 2 columns into a pandas Series object like this:</p>

<pre class="lang-py prettyprint-override"><code>>>> names = (df['0_x'] + ' ' + df['0_y'])
>>> names
0       Jan Hart
1    Jan Johnson
2       Bob Hart
3    Bob Johnson
dtype: object

>>> names.to_csv('names.csv', header=None, index=False)
</code>```

If you then inspect the names.csv file, you can see that it contains the product of all the names in the 2 files:

➜  ~ cat names.csv
Jan Hart
Jan Johnson
Bob Hart
Bob Johnson
```

Body:
I am doing the cartesian product from 2 csv files with each 1 column. The outcome should be a new csv with with 1 column in which are all the products.
Since the default delimiter is comma and sep=None or similar isn't allowed, how is it possible to have the product in one column without any comma?
First I thought the imported file 00 would have the delimiter but with replace and delim_whitespace=False I guess I made sure it doesn't comes from there (its anyways just one column).
I also tried to merge or join column 1 and column 2 of the final file with the cartesian product but coulnd't figure out how. Further I tried it with replace(",", "") but it didn't change the outcome.

This is the code:

import pandas as pd

vornamen = pd.read_csv(...\00.csv",header=None, encoding= 'unicode_escape')
nachnamen = pd.read_csv(...\01.csv",header=None, encoding= 'unicode_escape')

vornamen['_tmp'] = 1
nachnamen['_tmp'] = 1

df = pd.merge(vornamen,nachnamen,on='_tmp').drop('_tmp',axis=1)
df.to_csv(...\03.csv",header=None,index=False, sep="\t")

Body:
Since the df.to_csv method creates a CSV file, it creates the same amount of columns in the output file as are in the dataframe. Since you have 2 columns in the df dataframe, pandas will try to save 2 columns:

...

>>> df = pd.merge(vornamen,nachnamen,on='_tmp').drop('mp',axis=1)
>>> df
   0_x      0_y
0  Jan     Hart
1  Jan  Johnson
2  Bob     Hart
3  Bob  Johnson

In order to have a single column, you can combine these 2 columns into a pandas Series object like this:

>>> names = (df['0_x'] + ' ' + df['0_y'])
>>> names
0       Jan Hart
1    Jan Johnson
2       Bob Hart
3    Bob Johnson
dtype: object

>>> names.to_csv('names.csv', header=None, index=False)

If you then inspect the names.csv file, you can see that it contains the product of all the names in the 2 files:

➜  ~ cat names.csv
Jan Hart
Jan Johnson
Bob Hart
Bob Johnson


问:
ReactJs - Unit Testing Using Mocha , Upgrading to Babel 7 from Babel 6
Did an upgrade from Babel v6 - v7 @latest today, And for some of the existing unit tests using Mocha and Enzyme (pretty standard) started crashing.
Getting this error in the console

```<code>\node_modules\reselect\lib\index.js:53
    throw new Error('Selector creators expect all input-selectors to be functions, ' + ('instead received the following types: [' + dependencyTypes + ']'));
</code>```

Further digging into the pattern of tests which are failing - Could spot that the test where have referenced i.e imported component from an index lookup is failing, If provide actual path it starts working fine.

By Index look mean below - All our components are categorized and then imported/exported. We have been using this pattern from 3 years now

```
import ABC from './common/Folder/ABC';
.
.
.
import XYZ from './common/Folder/XYZ';

export {
ABC,
.
.
XYZ
}
```

The error happens when in Unit Test file we import like below

```<code>1.import { ABC } from 'componentIndex';
</code>```

If direct path is provided starts working

```<code>2. import { ABC } from '../../ABC';
</code>```

Please let me know if for any questions you might have in this context.

Any suggestion what I might be missing that is causing this error. Any babel plugin ? Thanks !

答:
The problem turned out to be in the

1.import { ABC } from 'componentIndex';

When ABC was imported , seems like babel checked componentIndex for its correctness and in there was a reference to a files which had createSelector from reselect. While the unit test was executed, some of the selectors couldn't resolve and resulted in error.

Added console log in the selectors and ran only the subsets of tests related to selectors and fixed those to support TDD. Once selectors were unit testable, Ran the whole suites and didn't face the error earlier.

Not sure how they were working on version 6.

Body:
Did an upgrade from Babel v6 - v7 @latest today, And for some of the existing unit tests using Mocha and Enzyme (pretty standard) started crashing.
Getting this error in the console

\node_modules\reselect\lib\index.js:53
    throw new Error('Selector creators expect all input-selectors to be functions, ' + ('instead received the following types: [' + dependencyTypes + ']'));

Further digging into the pattern of tests which are failing - Could spot that the test where have referenced i.e imported component from an index lookup is failing, If provide actual path it starts working fine.

By Index look mean below - All our components are categorized and then imported/exported. We have been using this pattern from 3 years now

import ABC from './common/Folder/ABC';
.
.
.
import XYZ from './common/Folder/XYZ';

export {
ABC,
.
.
XYZ
}

The error happens when in Unit Test file we import like below

1.import { ABC } from 'componentIndex';

If direct path is provided starts working

2. import { ABC } from '../../ABC';

Please let me know if for any questions you might have in this context.

Any suggestion what I might be missing that is causing this error. Any babel plugin ? Thanks !


问:
How to extract a portion of a datframe column and create another column with that extraction
I have a Pandas dataframe like this:

```<code>id        Month
 1     Month  01
 1     Month  05
 2     Month  12
...
</code>```

And I wanted to extract the value from the Month column and add that extraction to a new column  Month_no and obtain this output:

```<code>id         Month     Month_no
 1     Month  01            1
 1     Month  05            5
 2     Month  12           12
...
</code>```

答:
Assuming Month column has Month and number separated by a whitespace, you can use str.split:

```<code>df['Month_no'] = df['Month'].str.split().str[1].astype(int)
</code>```

Example:

```<code>In [1168]: df
Out[1168]:
   id     Month
0   1  Month 01
1   1  Month 05
2   2  Month 12

In [1169]: df['Month_no'] = df['Month'].str.split().str[1].astype(int)

In [1170]: df
Out[1170]:
   id     Month  Month_no
0   1  Month 01         1
1   1  Month 05         5
2   2  Month 12        12
</code>```

Body:
I have a Pandas dataframe like this:

id        Month
 1     Month  01
 1     Month  05
 2     Month  12
...

And I wanted to extract the value from the Month column and add that extraction to a new column  Month_no and obtain this output:

id         Month     Month_no
 1     Month  01            1
 1     Month  05            5
 2     Month  12           12
...

Body:
Assuming Month column has Month and number separated by a whitespace, you can use str.split:

df['Month_no'] = df['Month'].str.split().str[1].astype(int)

Example:

In [1168]: df
Out[1168]:
   id     Month
0   1  Month 01
1   1  Month 05
2   2  Month 12

In [1169]: df['Month_no'] = df['Month'].str.split().str[1].astype(int)

In [1170]: df
Out[1170]:
   id     Month  Month_no
0   1  Month 01         1
1   1  Month 05         5
2   2  Month 12        12


问:
ValueError: invalid literal for int() with base 10: '[2,7,11,15]'
When I run this code in my pc it is ok but when I submit it on leetcode it gives runtime more like above. Error :

```<code>ValueError: invalid literal for int() with base 10: '[2,7,11,15]'
    if (int(arr[i])+int(arr[j]))==target and int(arr[i])!=int(arr[j]) and cnt<1:
Line 11 in <module> (Solution.py)
</code>```

Hoe should I fix this?

```<code>arr=[]

arr=input()
arr=arr.split()

target=int(input())
cnt=0
for i,num in enumerate(arr):
    for j,num1 in enumerate(arr):

        if (int(arr[i])+int(arr[j]))==target and int(arr[i])!=int(arr[j]) and cnt<1:
            li=[]

            li.append(i)
            li.append(j)
            li=sorted(li)
            print(li)
            cnt=cnt+1;
</code>```

答:
This error suggest a conversion fail, probably when you try to cast arr[...] to integer.

As you can see on the error, you try to convert [2,7,11,15] to int which immediately failed. Your logic was probably wrong on arr.split: you assumed the input will be given with whitespaces (aka 2 7 11 15), while it is being given with commas to separate ([2, 7, 11, 15]).

For that exact input, you should use arr=arr.split(',') and also remove the '[' and ']' on the beginning & end of the string. You can do this with taking only substring of arr.

Fixed line: arr = arr[1:-1].split(',').

This should cover the specific input that cause a problem. Having said that, I'm not sure if it will cover all cases since you did not gave the full assignment. It depends on how you assume input will be given.

Body:
When I run this code in my pc it is ok but when I submit it on leetcode it gives runtime more like above. Error :

ValueError: invalid literal for int() with base 10: '[2,7,11,15]'
    if (int(arr[i])+int(arr[j]))==target and int(arr[i])!=int(arr[j]) and cnt<1:
Line 11 in <module> (Solution.py)

Hoe should I fix this?

arr=[]

arr=input()
arr=arr.split()

target=int(input())
cnt=0
for i,num in enumerate(arr):
    for j,num1 in enumerate(arr):

        if (int(arr[i])+int(arr[j]))==target and int(arr[i])!=int(arr[j]) and cnt<1:
            li=[]

            li.append(i)
            li.append(j)
            li=sorted(li)
            print(li)
            cnt=cnt+1;


问:
c# Class Names - Convention on how to name classes

Possible Duplicate:

  (Conventions) C# Class names

I use Entity framework (or even with Nhibernate or linq to sql) you usually have a series of entity classes that get passed around a solution. I usually, have these classes in a VS Project called [SolutionName].Data

At some stage these will be used by another class which might carryout some business logic prior to saving and deleting them. In this situation I then have these action classes in a project called [SolutionName].Core

I have seen some developers suffix these classes with Logic or Manager e.g. RegistrationManager which would then have a Save(), Delete(), Update(). A prime example of this is the open source NopCommerce.

Some put them into a  folder called Bll but leave the name unchanged e.g. the namespace would be [SolutionName].Core.Bll with a class in that called Registration. They would then reply on the namespace distinguishing whether this is a database entity or a business logic class.

The question is how should I be naming classes? Should I just suffix everything with Logic/Manager/Service or is there a better solution?

答:
I've always liked these:

http://10rem.net/articles/net-naming-conventions-and-programming-standards---best-practices


问:
firebase.storage().ref("image/").listAll() is not a function and undefined
package used is react-native firebase.</p>

```<code>firebase.storage().ref("image/").listAll().then( function (result){
  result.items.forEach( function (all) {
    console.log("image reference" + all.toString())
  });
 }).catch((error)=> {
   console.log(error);
   alert(error)
 });
</code>```

答:
Looks like you misspelled the image folder in firebase otherwise this code is working</p>

```<code>function ListAnother(){
firebase.storage().ref("images/").listAll().then( function (result){
    result.items.forEach( function (all) {
      console.log("image reference" + all.toString())
    });
   }).catch((error)=> {
     console.log(error);
     alert(error)
   });
}
</code>```

Body:
package used is react-native firebase.

firebase.storage().ref("image/").listAll().then( function (result){
  result.items.forEach( function (all) {
    console.log("image reference" + all.toString())
  });
 }).catch((error)=> {
   console.log(error);
   alert(error)
 });

Body:
Looks like you misspelled the image folder in firebase otherwise this code is working

function ListAnother(){
firebase.storage().ref("images/").listAll().then( function (result){
    result.items.forEach( function (all) {
      console.log("image reference" + all.toString())
    });
   }).catch((error)=> {
     console.log(error);
     alert(error)
   });
}


问:
How to properly connect MySQL database with C# application?
I am trying to connect my MySQL database with C# but it's not getting connected.

I am using

```<code>static string connstring = @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";
</code>```

but still I am getting

Authentication to host 'my.live.ip' for user 'user' using method 'mysql_native_password' failed with message: Access denied for user 'user'@'202.xxx.xxx.xxx' (using password: NO)`

I have searched on it but didn't find any suitable solution(s).

P.S: The live IP that I am using is of azure. i.e. MySQL database is hosted on azure server via xampp

Any help would be highly appreciated

答:
(using password: NO) says that no password was provided.  I am not familiar with the connection syntax for C#, but I would suspect that something is wrong with

```<code>static string connstring =
     @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";
</code>```

Or perhaps connstring is not being used.

Also check the MySQL side.  Do SHOW GRANTS FOR 'user'@'202%' or maybe SHOW GRANTS FOR 'user'@'202.xxx.xxx.xxx', depending on whether you used '202%' or '202.xxx.xxx.xxx' as the "host".

You should get back something like

```<code>GRANT ... ON dbname.* TO 'user'@'202%' WITH AUTHENTICATION 'mysql_native_password';
</code>```

Note: having a hostname versus an IP address may be an issue.

Body:
I am trying to connect my MySQL database with C# but it's not getting connected.

I am using

static string connstring = @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";

but still I am getting

Authentication to host 'my.live.ip' for user 'user' using method 'mysql_native_password' failed with message: Access denied for user 'user'@'202.xxx.xxx.xxx' (using password: NO)`

I have searched on it but didn't find any suitable solution(s).

P.S: The live IP that I am using is of azure. i.e. MySQL database is hosted on azure server via xampp

Any help would be highly appreciated

Body:
(using password: NO) says that no password was provided.  I am not familiar with the connection syntax for C#, but I would suspect that something is wrong with

static string connstring =
     @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";

Or perhaps connstring is not being used.

Also check the MySQL side.  Do SHOW GRANTS FOR 'user'@'202%' or maybe SHOW GRANTS FOR 'user'@'202.xxx.xxx.xxx', depending on whether you used '202%' or '202.xxx.xxx.xxx' as the "host".

You should get back something like

GRANT ... ON dbname.* TO 'user'@'202%' WITH AUTHENTICATION 'mysql_native_password';

Note: having a hostname versus an IP address may be an issue.


问:
How to name a audio file when saving into server with POST
I've being developing a solution for my webpage with Django and javascript, it's a record button so that the user can send feedback and I can store it into the server.

The plan is putting a text input where the user can introduce its name and a file is created with that name. This is my code by now. Can anyone help me with this?

Python views.py

```<code>def voice_request(request):
    f = open('./Grabaciones/file.wav', 'wb')
    f.write(request.body)
    f.close()
    return HttpResponse('audio received')
</code>```

Javascript part

```<code>function sendData(data) {
  let csrftoken = getCookie('csrftoken');
  let response=fetch("/salud/voice_request/", {
  method: "post",
  body: data,
  headers: { "X-CSRFToken": csrftoken },
  })
}
</code>```

答:
Welcome at SO.

You have to offer some text input form to the user in order to enable him to send some context.  On the backend site, you would then push the data to the database using a Django model which is basically the toolbox for handling data in Django.

Kindly refer to the docu to get a deep dive into it:

https://docs.djangoproject.com/en/3.0/topics/forms/

Body:
I've being developing a solution for my webpage with Django and javascript, it's a record button so that the user can send feedback and I can store it into the server.

The plan is putting a text input where the user can introduce its name and a file is created with that name. This is my code by now. Can anyone help me with this?

Python views.py

def voice_request(request):
    f = open('./Grabaciones/file.wav', 'wb')
    f.write(request.body)
    f.close()
    return HttpResponse('audio received')

Javascript part

function sendData(data) {
  let csrftoken = getCookie('csrftoken');
  let response=fetch("/salud/voice_request/", {
  method: "post",
  body: data,
  headers: { "X-CSRFToken": csrftoken },
  })
}


问:
symfony : myUser class => How to access custom property
I have enabled sfDoctrineGuardPlugin, so I have change myUser class to my class extends sfGuardSecurityUser.

I have overrided sfGuardUser schema to add my own relation

```<code>Personnage:
      local: id
      foreign: user_id
      type: one
      onUpdate: CASCADE
      onDelete: CASCADE
</code>```

When models are generated, if go on BasesfGuardUser.class.php, I can see in PHPDoc comments my relation is created and property Personnage has been added.

```<code> * @property Personnage $Personnage
</code>```

But I don't understand when I try to access this property, I can't.

In controller :

```<code>$user = $this->getUser();
$user->Personnage;
</code>```

In view :

```<code>echo $sf_user->Personnage
</code>```

And the error :

```<code>Notice: Undefined property: myUser::$Personnage
</code>```

How can I access to this property ?

答:
You're mixing up two things: the myUser, aka. the session, and the doctrine user, aka. the user's database record.

In symfony projects, the myUser class represents the current session (a wrapper on top of the $_SESSION superglobal).

You can access the database record in you controller via $this->getUser()->getGuardUser(), so your relation will work as $this->getUser()->getGuardUser()->Personnage.

Also see the part regarding user sessions of the Gentle Introduction to symfony book.

Body:
I have enabled sfDoctrineGuardPlugin, so I have change myUser class to my class extends sfGuardSecurityUser.

I have overrided sfGuardUser schema to add my own relation

Personnage:
      local: id
      foreign: user_id
      type: one
      onUpdate: CASCADE
      onDelete: CASCADE

When models are generated, if go on BasesfGuardUser.class.php, I can see in PHPDoc comments my relation is created and property Personnage has been added.

 * @property Personnage $Personnage

But I don't understand when I try to access this property, I can't.

In controller :

$user = $this->getUser();
$user->Personnage;

In view :

echo $sf_user->Personnage

And the error :

Notice: Undefined property: myUser::$Personnage

How can I access to this property ?


问:
Can you pass arguments to a function object in Python?
For the sake of organization, I outline an ML optimizer with the rest of my config constants at the top of my file:

```<code>optimizer = torch.optim.SGD()
</code>```

To use the optimizer, I have to pass in the model parameters, generated later on in the code

```<code>optimizer = torch.optim.SGD(model.parameters, lr=LEARNING_RATE)
</code>```

Is there any way for me to pass arguments into the variable optimizer?

edit:
I think my question is unclear, here's a simpler example of what I was asking:

```<code>#take the square of some arbitrary number

fn = math.prod()
x = 5

#how to feed x into the variable fn?
</code>```

答:
It sounds like you are asking about partial application. This is a way of "wrapping" a function and some arguments into a single, new callable, which takes fewer (or even no) arguments.</p>

```<code>>>> from functools import partial
>>> f = lambda x, y, z: x + y + z
>>> g = partial(f, 2, 3)
>>> g(4)
9
>>> h = partial(f, 1, 2, 3)
>>> h()
6
</code>```

Body:
For the sake of organization, I outline an ML optimizer with the rest of my config constants at the top of my file:

optimizer = torch.optim.SGD()

To use the optimizer, I have to pass in the model parameters, generated later on in the code

optimizer = torch.optim.SGD(model.parameters, lr=LEARNING_RATE)

Is there any way for me to pass arguments into the variable optimizer?

edit:
I think my question is unclear, here's a simpler example of what I was asking:

#take the square of some arbitrary number

fn = math.prod()
x = 5

#how to feed x into the variable fn?

Body:
It sounds like you are asking about partial application. This is a way of "wrapping" a function and some arguments into a single, new callable, which takes fewer (or even no) arguments.

>>> from functools import partial
>>> f = lambda x, y, z: x + y + z
>>> g = partial(f, 2, 3)
>>> g(4)
9
>>> h = partial(f, 1, 2, 3)
>>> h()
6


Title: Can you pass arguments to a function object in Python?

Body:
Sure!

>>> def add(x, y):
...    return x+y
...
>>> z = add
>>> z(1,1)
2


问:
Compile-time detection of missing user-defined to_string()
I want to provide a to_string(obj) function for every object type I create.
I found this question, applied the accepted answer, and it works. So far so good.

Then I created a new type, but forgot to write a to_string() for it (or better: I accidentally made it unreachable by ADL). The problem is: my program still compiles fine, and at runtime I get an obscure stack overflow(TM).

Is there a way to obtain a reasonable error message, instead?

Here is a small program to demonstrate the problem: an infinite recursion between notstd::to_string() and notstd::adl_helper::as_string().

```<code>#include <iostream>
#include <string>

namespace notstd {
  namespace adl_helper {
    using std::to_string;

    template<class T>
    std::string as_string( T&& t ) {
      return to_string( std::forward<T>(t) );
    }
  }
  template<class T>
  std::string to_string( T&& t ) {
    std::cout << "called" << std::endl; // <-- this is to show what's going on
    return adl_helper::as_string(std::forward<T>(t));
  }

  class A {
    /* both versions are needed, or the perfect forwarding candidate will
     * always be chosen by the compiler in case of a non-perfect match */
    //friend std::string to_string(A &a) { return std::string("a"); }
    //friend std::string to_string(const A &a) { return std::string("a"); }
  };
}

int main(int argc, char** argv) {

  notstd::A a;

  std::cout << to_string(a) << std::endl;
}
</code>```

I tried creating a wrapper function that accepts one more parameter, to be used to perform the an anti-recursion check, like this:

```<code>#include <iostream>
#include <string>
#include <cassert>

namespace notstd {
  namespace wrap_std {
    std::string to_string(double v, bool) { return std::to_string(v); }
    /* .... etc.....  */
  }

  namespace adl_helper {
    using wrap_std::to_string;

    template<class T>
    std::string as_string( T&& t ) {
      return to_string( std::forward<T>(t), true );
    }
  }
  template<class T>
  std::string to_string( T&& t, bool recurring = false ) {
    std::cout << "called" << std::endl;
    assert(!recurring);
    return adl_helper::as_string(std::forward<T>(t));
  }

  class A {
    /* both versions are needed, or the perfect forwarding candidate will
     * always be chosen by the compiler in case of a non-perfect match */
    //friend std::string to_string(A &a) { return std::string("A"); }
    //friend std::string to_string(const A &a) { return std::string("A"); }
  };
}

int main(int argc, char** argv) {

  notstd::A a;

  std::cout << to_string(a) << std::endl;
}
</code>```

The problems here are:

I'd have to wrap all std::to_string() overloads

I'll only get a runtime error, but I feel the problem could and should be detected ad compile time

I'm probably adding some overhead, for something useful only during development: maybe I could add some macros to deactivate all this in release mode, but it would add even more work

Maybe I could use a template to wrap std::to_string() and create specializations for my types... this would be a quite different beast, but at least it would provide a compile time error if a suitable specialization is not available. I would have, again, to wrap all std::to_string() overloads, and I'd probably have to (almost) forget about ADL, at least until c++20 is supported by all compilers, If I understand well.

Does anyone have a better solution?

Thanks!

答:
The idea of that accepted answer is different: you put A outside notstd namespace and then use qualified notstd::to_string instead of unqualified to_string. That is:

```<code>namespace notstd {
    // ...
}

class A {
    friend std::string to_string(const A&);
};

A a;
std::cout << notstd::to_string(a);
</code>```

Now your code won't compile if there is no friend function. Moreover, you need only one friend function (taking const A&), because notstd::to_string(T&&) won't be present in the overload set inside adl_helper::as_string(T&&).

Putting A inside notstd screws everything up. You have infinite recursion problem and you need two friends to handle both A and const A cases in the presence of notstd::to_string(T&&) candidate: if only one friend is defined, that candidate is a better match in one of the cases because const qualifier should be added/dropped to invoke the friend function.

Body:
I want to provide a to_string(obj) function for every object type I create.
I found this question, applied the accepted answer, and it works. So far so good.

Then I created a new type, but forgot to write a to_string() for it (or better: I accidentally made it unreachable by ADL). The problem is: my program still compiles fine, and at runtime I get an obscure stack overflow(TM).

Is there a way to obtain a reasonable error message, instead?

Here is a small program to demonstrate the problem: an infinite recursion between notstd::to_string() and notstd::adl_helper::as_string().

#include <iostream>
#include <string>

namespace notstd {
  namespace adl_helper {
    using std::to_string;

    template<class T>
    std::string as_string( T&& t ) {
      return to_string( std::forward<T>(t) );
    }
  }
  template<class T>
  std::string to_string( T&& t ) {
    std::cout << "called" << std::endl; // <-- this is to show what's going on
    return adl_helper::as_string(std::forward<T>(t));
  }

  class A {
    /* both versions are needed, or the perfect forwarding candidate will
     * always be chosen by the compiler in case of a non-perfect match */
    //friend std::string to_string(A &a) { return std::string("a"); }
    //friend std::string to_string(const A &a) { return std::string("a"); }
  };
}

int main(int argc, char** argv) {

  notstd::A a;

  std::cout << to_string(a) << std::endl;
}

I tried creating a wrapper function that accepts one more parameter, to be used to perform the an anti-recursion check, like this:

#include <iostream>
#include <string>
#include <cassert>

namespace notstd {
  namespace wrap_std {
    std::string to_string(double v, bool) { return std::to_string(v); }
    /* .... etc.....  */
  }

  namespace adl_helper {
    using wrap_std::to_string;

    template<class T>
    std::string as_string( T&& t ) {
      return to_string( std::forward<T>(t), true );
    }
  }
  template<class T>
  std::string to_string( T&& t, bool recurring = false ) {
    std::cout << "called" << std::endl;
    assert(!recurring);
    return adl_helper::as_string(std::forward<T>(t));
  }

  class A {
    /* both versions are needed, or the perfect forwarding candidate will
     * always be chosen by the compiler in case of a non-perfect match */
    //friend std::string to_string(A &a) { return std::string("A"); }
    //friend std::string to_string(const A &a) { return std::string("A"); }
  };
}

int main(int argc, char** argv) {

  notstd::A a;

  std::cout << to_string(a) << std::endl;
}

The problems here are:

I'd have to wrap all std::to_string() overloads

I'll only get a runtime error, but I feel the problem could and should be detected ad compile time

I'm probably adding some overhead, for something useful only during development: maybe I could add some macros to deactivate all this in release mode, but it would add even more work

Maybe I could use a template to wrap std::to_string() and create specializations for my types... this would be a quite different beast, but at least it would provide a compile time error if a suitable specialization is not available. I would have, again, to wrap all std::to_string() overloads, and I'd probably have to (almost) forget about ADL, at least until c++20 is supported by all compilers, If I understand well.

Does anyone have a better solution?

Thanks!

Body:
The idea of that accepted answer is different: you put A outside notstd namespace and then use qualified notstd::to_string instead of unqualified to_string. That is:

namespace notstd {
    // ...
}

class A {
    friend std::string to_string(const A&);
};

A a;
std::cout << notstd::to_string(a);

Now your code won't compile if there is no friend function. Moreover, you need only one friend function (taking const A&), because notstd::to_string(T&&) won't be present in the overload set inside adl_helper::as_string(T&&).

Putting A inside notstd screws everything up. You have infinite recursion problem and you need two friends to handle both A and const A cases in the presence of notstd::to_string(T&&) candidate: if only one friend is defined, that candidate is a better match in one of the cases because const qualifier should be added/dropped to invoke the friend function.


答:
I figured it out, seems really simple but I'll leave it up because I couldn't find it online anywhere.

You can just pass the arguments to the new variable because it's now the same object as the function

```<code>optimizer(model.parameters, lr=LEARNING_RATE)
</code>```

Body:
I figured it out, seems really simple but I'll leave it up because I couldn't find it online anywhere.

You can just pass the arguments to the new variable because it's now the same object as the function

optimizer(model.parameters, lr=LEARNING_RATE)


问:
summing number of different columns
I want to return the list of data frames with the number of different columns apart from the name column, which I want to return the same. So for this example, it would return </p>

```<code>list3$dfa

     names X  Y   Z
1    Ben   1  1   2

list3$dfb

   names  X  Y  Z
1  John   2  2  2

</code>```

<p>Kindly let me know how I would do this, please.  </p>

答:
We can use map2 from purrr

```<code>library(dplyr)
library(purrr)
map2(list1, list2, ~
      tibble(Name = select(.x, names) %>% slice(1),
      map2_dfc(.x[-1], .y[-1],  ~ 100 *mean(.x != .y))))
#$dfa
# A tibble: 1 x 4
#  Name$names     X     Y     Z
#  <chr>      <dbl> <dbl> <dbl>
#1 Ben         33.3  33.3  66.7

#$dfb
# A tibble: 1 x 4
#  Name$names     X     Y     Z
#  <chr>      <dbl> <dbl> <dbl>
#1 John          50    50    75
</code>```

Title: summing number of different columns

Body:
I want to return the list of data frames with the number of different columns apart from the name column, which I want to return the same. So for this example, it would return

list3$dfa

     names X  Y   Z
1    Ben   1  1   2

list3$dfb

   names  X  Y  Z
1  John   2  2  2

Kindly let me know how I would do this, please.

Body:
We can use map2 from purrr

library(dplyr)
library(purrr)
map2(list1, list2, ~
      tibble(Name = select(.x, names) %>% slice(1),
      map2_dfc(.x[-1], .y[-1],  ~ 100 *mean(.x != .y))))
#$dfa
# A tibble: 1 x 4
#  Name$names     X     Y     Z
#  <chr>      <dbl> <dbl> <dbl>
#1 Ben         33.3  33.3  66.7

#$dfb
# A tibble: 1 x 4
#  Name$names     X     Y     Z
#  <chr>      <dbl> <dbl> <dbl>
#1 John          50    50    75


问:
How to convert web site language into user selected language - React JS
I have developed a site with React js in English language but I want to have the feature of changing site language to user preferred language. How can I achieve this?.

答:
a better library I'll suggest will be the i18next. it's quite straight forward and easy to implemente:

brief explanation here: https://dev.to/ksushiva/how-to-translate-your-react-js-app-with-i18next-12mn

official doc: https://www.i18next.com/overview/comparison-to-others


问:
is it possible to explain why this returns 21
Hello this isn't an assignment or anything but can you explain why this returns 2 1.</p>
```<code>#include <string>
using namespace std;
void fun(int);
int main()
{
    int a = 0;
    fun(a);
    return 0;
}

void fun(int n)
{
    if (n < 2)
    {
        fun(++n);
        cout << n<<" ";
    }
}
</code>```

答:
This code does not return anything, except for the main function that returns 0 exit code. The function fun just prints.

It prints 2 1, because it computes this:

```<code>void fun0()
{
   fun1();
   cout << 1 <<" ";
}

void fun1()
{
   cout << 2 <<" ";
}
</code>```

Therefore it first prints 2 and then prints 1 after the code returns from fun1.

Body:
Hello this isn't an assignment or anything but can you explain why this returns 2 1.

#include <string>
using namespace std;
void fun(int);
int main()
{
    int a = 0;
    fun(a);
    return 0;
}

void fun(int n)
{
    if (n < 2)
    {
        fun(++n);
        cout << n<<" ";
    }
}

Body:
This code does not return anything, except for the main function that returns 0 exit code. The function fun just prints.

It prints 2 1, because it computes this:

void fun0()
{
   fun1();
   cout << 1 <<" ";
}

void fun1()
{
   cout << 2 <<" ";
}

Therefore it first prints 2 and then prints 1 after the code returns from fun1.


问:
Count which cycle of the alphabet this letter is in [python]
I have this alphabetic cycle A B C D which represent the phase an item is in. An item can cycle through the phase more than once, so I need to find out if an item is in its first phase A, or its second phase A.

Letters can be missing which makes this a bit tricky. See correct outputs:

```<code>test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]
</code>```

Note that in test_2 we accurately note the first occurrence of phase C is in the 2nd cycle.

My attempts are below:

```<code>import itertools

test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]

valid_phase_seq=['A','B','C','D']

def count_phases(phase_list):
    '''
    We will see whether this is the 1st phase A, or the 2nd phase A.
    :param phase_list:
    :return: int list
    '''
    phase_counts = []
    valid_iter = itertools.cycle(valid_phase_seq)
    count = 1

    # failed approach #2
    while len(phase_counts) != len(phase_list):
        for valid_phase in valid_iter:
            for curr_phase in phase_list:
                if valid_phase == curr_phase:
                    phase_counts.append(count)
            count += 1

    # failed approach #1
    # for curr_phase in phase_list:
    #     # Look at a phase
    #     curr_valid = next(valid_iter)
    #
    #     # We are in another cycle
    #     if curr_valid == 'A' and len(phase_counts) > 1:
    #         count += 1
    #         valid_iter = itertools.cycle(valid_phase_seq)
    #         curr_valid = next(valid_iter)
    #
    #     # We are in the same cycle
    #     #if curr_phase == curr_valid:
    #     phase_counts.append(count)

    return phase_counts

</code>```

答:
Trying to cycle through the valid phases is overthinking it. Just cycle through the actual data:</p>

```<code>def number_cycles(phases):
    cycles = []
    current_cycle, previous_phase = 1, None
    for current_phase in phases:
        if previous_phase is not None and previous_phase >= current_phase:
            current_cycle += 1
        previous_phase = current_phase # for next loop
        cycles.append(current_cycle)
    return cycles
</code>```

Body:
I have this alphabetic cycle A B C D which represent the phase an item is in. An item can cycle through the phase more than once, so I need to find out if an item is in its first phase A, or its second phase A.

Letters can be missing which makes this a bit tricky. See correct outputs:

test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]

Note that in test_2 we accurately note the first occurrence of phase C is in the 2nd cycle.

My attempts are below:

import itertools

test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]

valid_phase_seq=['A','B','C','D']

def count_phases(phase_list):
    '''
    We will see whether this is the 1st phase A, or the 2nd phase A.
    :param phase_list:
    :return: int list
    '''
    phase_counts = []
    valid_iter = itertools.cycle(valid_phase_seq)
    count = 1

    # failed approach #2
    while len(phase_counts) != len(phase_list):
        for valid_phase in valid_iter:
            for curr_phase in phase_list:
                if valid_phase == curr_phase:
                    phase_counts.append(count)
            count += 1

    # failed approach #1
    # for curr_phase in phase_list:
    #     # Look at a phase
    #     curr_valid = next(valid_iter)
    #
    #     # We are in another cycle
    #     if curr_valid == 'A' and len(phase_counts) > 1:
    #         count += 1
    #         valid_iter = itertools.cycle(valid_phase_seq)
    #         curr_valid = next(valid_iter)
    #
    #     # We are in the same cycle
    #     #if curr_phase == curr_valid:
    #     phase_counts.append(count)

    return phase_counts

Body:
Trying to cycle through the valid phases is overthinking it. Just cycle through the actual data:

def number_cycles(phases):
    cycles = []
    current_cycle, previous_phase = 1, None
    for current_phase in phases:
        if previous_phase is not None and previous_phase >= current_phase:
            current_cycle += 1
        previous_phase = current_phase # for next loop
        cycles.append(current_cycle)
    return cycles


问:
inspect delphi control object without modify source code
I have an Stock program which developed by Delphi,  I want a tools which can read the data from the stock program, for example, the stock price in Delphi grid object.

The Stock program under test is close source, so no chance modify source code which QTP/Robot inspector required.  I cannot tell out which Delphi version it is using, neither the object is a standard delphi control.

So anyone can tell out is it possible to inspect that delphi program object data through other technology ?

thanks in advance.

答:
Trying to read data out of a Delphi grid control is not going to work out for you. It's not like a standard Windows edit control which you could just call GetWindowText on.

If you really want to get the information from this existing program then you'd need to poke at its internal memory or do an OCR on a screen grab. All pretty horrible to contemplate.


问:
How can I update the stable toolchain when I get the error "some components unavailable for target i386-apple-ios/armv7s-apple-ios"?
I try to run

rustup update stable
```

<p>and I get the following output.</p>

<pre class="lang-none prettyprint-override"><code>info: syncing channel updates for 'stable-x86_64-unknown-linux-gnu'
info: latest update on 2020-05-07, rust version 1.43.1 (8d69840ab 2020-05-04)
error: some components unavailable for download for channel stable: 'rust-std' for target 'i386-apple-ios', 'rust-std' for target 'armv7s-apple-ios', 'rust-std' for target 'armv7-apple-ios'
If you require these components, please install and use the latest successful build version,
which you can find at <https://rust-lang.github.io/rustup-components-history>.

After determining the correct date, install it with a command such as:

    rustup toolchain install nightly-2018-12-27

Then you can use the toolchain with commands such as:

    cargo +nightly-2018-12-27 build
</code>```

While I can install the latest stable toolchain using

rustup toolchain install stable-2020-05-07
```

<p>That creates a separate toolchain.</p>

<pre class="lang-none prettyprint-override"><code>rustup toolchain list
stable-2020-05-07-x86_64-unknown-linux-gnu (default)
stable-x86_64-unknown-linux-gnu
nightly-2020-05-07-x86_64-unknown-linux-gnu
</code>```

I can use this new toolchain as the default (as I am now), but it's going to be a pain moving forward as I can't just use rustup update.

Running rustup toolchain install stable yields the same error.

How can I get the stable Rust toolchain to update via rustup update run?

答:
The Rust team regrets to announce that Rust 1.41.0 (to be released on January 30th, 2020) will be the last release with the current level of support for 32-bit Apple targets. Starting from Rust 1.42.0, those targets will be demoted to Tier 3.

Reducing support for 32-bit Apple targets

You will need to remove those components using rustup component remove. I can't test the exact invocation, but something like:

```<code>rustup component remove --toolchain stable --target i386-apple-ios rust-std
rustup component remove --toolchain stable --target armv7s-apple-ios rust-std
rustup component remove --toolchain stable --target armv7-apple-ios rust-std
</code>```

Once removed, you can update your compiler.

Body:
I try to run

rustup update stable

and I get the following output.

info: syncing channel updates for 'stable-x86_64-unknown-linux-gnu'
info: latest update on 2020-05-07, rust version 1.43.1 (8d69840ab 2020-05-04)
error: some components unavailable for download for channel stable: 'rust-std' for target 'i386-apple-ios', 'rust-std' for target 'armv7s-apple-ios', 'rust-std' for target 'armv7-apple-ios'
If you require these components, please install and use the latest successful build version,
which you can find at <https://rust-lang.github.io/rustup-components-history>.

After determining the correct date, install it with a command such as:

    rustup toolchain install nightly-2018-12-27

Then you can use the toolchain with commands such as:

    cargo +nightly-2018-12-27 build

While I can install the latest stable toolchain using

rustup toolchain install stable-2020-05-07

That creates a separate toolchain.

rustup toolchain list
stable-2020-05-07-x86_64-unknown-linux-gnu (default)
stable-x86_64-unknown-linux-gnu
nightly-2020-05-07-x86_64-unknown-linux-gnu

I can use this new toolchain as the default (as I am now), but it's going to be a pain moving forward as I can't just use rustup update.

Running rustup toolchain install stable yields the same error.

How can I get the stable Rust toolchain to update via rustup update run?

Body:
The Rust team regrets to announce that Rust 1.41.0 (to be released on January 30th, 2020) will be the last release with the current level of support for 32-bit Apple targets. Starting from Rust 1.42.0, those targets will be demoted to Tier 3.

Reducing support for 32-bit Apple targets

You will need to remove those components using rustup component remove. I can't test the exact invocation, but something like:

rustup component remove --toolchain stable --target i386-apple-ios rust-std
rustup component remove --toolchain stable --target armv7s-apple-ios rust-std
rustup component remove --toolchain stable --target armv7-apple-ios rust-std

Once removed, you can update your compiler.