问:
How to persist Cookies in WKWebview iOS Swift - iOS 13 SwiftUI
I am looking for solution for iOS 13 SDK WKWebview based app built with SwiftUI in order to make cookies saved between different sessions of app usage.

This problem has been numerously discussed acrossed stackoverflow provided with different soltuions for ObjectiveC and Swift with Storyboards.

I am asking the community if there is ready to use code examlpe of how to provide WKWebView Cookie Persistency on iOS 13 WKWebView app with SwiftUI used

To make it clear: my app accesses remote web server with web site designed to be like mobile app. It's not local web app with need to manipulate cookies locally. Simply to make cookies manipulation in web site from remote server in Jquery JS code of the page in order to work and be saved across different sessions of app,

My current version of code:

```<code>import SwiftUI
import WebKit

struct ContentView: View {
  var body: some View {
    WebView().edgesIgnoringSafeArea(.all)
  }
}

struct WebView: UIViewRepresentable {
  func makeUIView(context: Context) -> WKWebView {
    let webView = WKWebView()
    webView.scrollView.isScrollEnabled = false
    return webView
  }

  func updateUIView(_ webView: WKWebView, context: Context) {
    let liveView = "https://example.com/projectname/index.html"
    if let url = URL(string: liveView) {
       let request = URLRequest(url: url)
       webView.load(request)
    }
  }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
#endif
</code>```

答:
Set the configuration webView.configuration.websiteDataStore.httpCookieStore

see this answer for an example

Body:
I am looking for solution for iOS 13 SDK WKWebview based app built with SwiftUI in order to make cookies saved between different sessions of app usage.

This problem has been numerously discussed acrossed stackoverflow provided with different soltuions for ObjectiveC and Swift with Storyboards.

I am asking the community if there is ready to use code examlpe of how to provide WKWebView Cookie Persistency on iOS 13 WKWebView app with SwiftUI used

To make it clear: my app accesses remote web server with web site designed to be like mobile app. It's not local web app with need to manipulate cookies locally. Simply to make cookies manipulation in web site from remote server in Jquery JS code of the page in order to work and be saved across different sessions of app,

My current version of code:

import SwiftUI
import WebKit

struct ContentView: View {
  var body: some View {
    WebView().edgesIgnoringSafeArea(.all)
  }
}

struct WebView: UIViewRepresentable {
  func makeUIView(context: Context) -> WKWebView {
    let webView = WKWebView()
    webView.scrollView.isScrollEnabled = false
    return webView
  }

  func updateUIView(_ webView: WKWebView, context: Context) {
    let liveView = "https://example.com/projectname/index.html"
    if let url = URL(string: liveView) {
       let request = URLRequest(url: url)
       webView.load(request)
    }
  }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
#endif


来源: stackexchange

问:
remove header from the reult of a solr query
my code looks like this

```<code>username = 'user'
password = 'user'
url = 'http://di4301sw:8081/solr/metadone/select?fl=file.contenu&q=patient.ipp:3456&rows=14'
r = requests.get(url, auth=(username, password))
data = r.json()
with open('data.json', 'w') as f:
    json.dump(data, f)
</code>```

and my result looks like this

```<code>{"responseHeader": {"status": 0, "QTime": 0, "params": {"q": "patient.ipp:3456", "fl": "file.contenu", "rows": "14"}}, "response": {"numFound": 14, "start": 0, "docs": [{"file.contenu": "Biochimie d'urgence Dr F. Beyerle, Dr L. Chardon, A. Varennes Tel Secr\u00e9tariat
</code>```

i want the result to start from "file.contenu" i.e. i dont want the header
Thanks in anticipation

答:
you should parse the response in order to get the desired result:

```<code>data_to_dump=data['response']['docs'][0]
</code>```

hope this helps

ContentLicense: CC BY-SA 4.0

Body:
my code looks like this

username = 'user'
password = 'user'
url = 'http://di4301sw:8081/solr/metadone/select?fl=file.contenu&q=patient.ipp:3456&rows=14'
r = requests.get(url, auth=(username, password))
data = r.json()
with open('data.json', 'w') as f:
    json.dump(data, f)

and my result looks like this

{"responseHeader": {"status": 0, "QTime": 0, "params": {"q": "patient.ipp:3456", "fl": "file.contenu", "rows": "14"}}, "response": {"numFound": 14, "start": 0, "docs": [{"file.contenu": "Biochimie d'urgence Dr F. Beyerle, Dr L. Chardon, A. Varennes Tel Secr\u00e9tariat

i want the result to start from "file.contenu" i.e. i dont want the header
Thanks in anticipation

Body:
you should parse the response in order to get the desired result:

data_to_dump=data['response']['docs'][0]

hope this helps


问:
How do I deal with an HTTP 410 when web scraping?
I can access a web site through my browser, for example:

https://waset.org/conferences-in-february-2020-in-london

... but if I try and web scrape this web site (I am using php simplehtmldom), I get an HTTP Error 410 (which means the page is gone, but it is there as I can see it through my browser).

Other web sites (from the same family, e.g. https://waset.org/conferences-in-february-2021-in-london), I can scrape just fine.

Does anybody know why I get a 410, when the web page is there, and what I can do about it.

答:
When you load the page in a browser, the server responds with a 410 as well – see attached imag. They probably want to convey the message that the conferences are expired.

The rest of the data is loaded as expected...


问:
How to put nodes into parent node?
I would like to add a parent node with attribute and put nodes inside of this parent node. I have the following xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<foo>
   <row>
      <PHONE_NUM>124</PHONE_NUM>
      <PHONE_ORDER>1</PHONE_ORDER>
   </row>
   <row>
      <PHONE_NUM>123</PHONE_NUM>
      <PHONE_ORDER>2</PHONE_ORDER>
   </row>
   <row>
      <PHONE_NUM>181</PHONE_NUM>
      <PHONE_ORDER>3</PHONE_ORDER>
   </row>
</foo>
</code>```

I've tried this approach:

```<code>var xmlString = @"<?xml version=""1.0"" encoding=""UTF-8""?>
    <foo>
       <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
       </row>
    </foo>";

var report = XDocument.Parse(xmlString);
var newdoc = new XDocument();
newdoc.Add(new XElement("testsuites"));
newdoc.Root.Add(report.Root);
</code>```

But the above code generates is withoud id and order books has become a root :

```<code><books>
  <foo>
      <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
      </row>
      <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
      </row>
      <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
      </row>
      </foo>
  </books>
</code>```

What I am trying to achieve is:

```<code><?xml version=""1.0"" encoding=""UTF-8""?>
<foo>
    <books id=""1"">
       <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
       </row>
    </books>
</foo>
</code>```

If it is possible, it would be great if XmlDocument class will be used. Any help would be greatly appreciated.

答:
This process helps you create a new child and move all nodes under this new child.

create a new element first..

Move all the nodes under this new element

Add the new element where you needed in the XML.

```<code>XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(xmlString);

var newElement = doc2.CreateElement("body");
newElement.SetAttribute("id", "1");

var moveNodes = doc2.DocumentElement.SelectNodes("//row");
foreach(XmlNode node in moveNodes)
    newElement.AppendChild(node);

doc2.GetElementsByTagName("foo")[0].AppendChild(newElement);
</code>```

Output

```<code><?xml version="1.0" encoding="UTF-8"?>
<foo>
    <body id="1">
        <row>
            <PHONE_NUM>124</PHONE_NUM>
            <PHONE_ORDER>1</PHONE_ORDER>
        </row>
        <row>
            <PHONE_NUM>123</PHONE_NUM>
            <PHONE_ORDER>2</PHONE_ORDER>
        </row>
        <row>
            <PHONE_NUM>181</PHONE_NUM>
            <PHONE_ORDER>3</PHONE_ORDER>
        </row>
    </body>
</foo>
</code>```

Title: How to put nodes into parent node?

Body:
I would like to add a parent node with attribute and put nodes inside of this parent node. I have the following xml:

<?xml version="1.0" encoding="UTF-8"?>
<foo>
   <row>
      <PHONE_NUM>124</PHONE_NUM>
      <PHONE_ORDER>1</PHONE_ORDER>
   </row>
   <row>
      <PHONE_NUM>123</PHONE_NUM>
      <PHONE_ORDER>2</PHONE_ORDER>
   </row>
   <row>
      <PHONE_NUM>181</PHONE_NUM>
      <PHONE_ORDER>3</PHONE_ORDER>
   </row>
</foo>

I've tried this approach:

var xmlString = @"<?xml version=""1.0"" encoding=""UTF-8""?>
    <foo>
       <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
       </row>
    </foo>";

var report = XDocument.Parse(xmlString);
var newdoc = new XDocument();
newdoc.Add(new XElement("testsuites"));
newdoc.Root.Add(report.Root);

But the above code generates is withoud id and order books has become a root :

<books>
  <foo>
      <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
      </row>
      <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
      </row>
      <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
      </row>
      </foo>
  </books>

What I am trying to achieve is:

<?xml version=""1.0"" encoding=""UTF-8""?>
<foo>
    <books id=""1"">
       <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
       </row>
    </books>
</foo>

If it is possible, it would be great if XmlDocument class will be used. Any help would be greatly appreciated.

Body:
This process helps you create a new child and move all nodes under this new child.

create a new element first..

Move all the nodes under this new element

Add the new element where you needed in the XML.

XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(xmlString);

var newElement = doc2.CreateElement("body");
newElement.SetAttribute("id", "1");

var moveNodes = doc2.DocumentElement.SelectNodes("//row");
foreach(XmlNode node in moveNodes)
    newElement.AppendChild(node);

doc2.GetElementsByTagName("foo")[0].AppendChild(newElement);

Output

<?xml version="1.0" encoding="UTF-8"?>
<foo>
    <body id="1">
        <row>
            <PHONE_NUM>124</PHONE_NUM>
            <PHONE_ORDER>1</PHONE_ORDER>
        </row>
        <row>
            <PHONE_NUM>123</PHONE_NUM>
            <PHONE_ORDER>2</PHONE_ORDER>
        </row>
        <row>
            <PHONE_NUM>181</PHONE_NUM>
            <PHONE_ORDER>3</PHONE_ORDER>
        </row>
    </body>
</foo>


问:
Print par numbers
I want to print some par numbers in a range between (32, 321), but it's not working. I am using this code :

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UFT-8">
  <title> </title>
</head>
<body>

    <script>
    function pares(x, y) {

    while (x<y){
        if((x%2) === 0){
            console.log(x)
            x++
        }
        else {
            return false
        }
    }
    }
    pares(32, 321);
    </script>
</body>
</html>
</code>```

I am receiving 32 only. How can I make it work?

答:
return statement terminates the function as soon it is encountered. You don't need a return statement here.

```<code>function printEvenNumbers(x, y) {

    while (x < y) {
        if(x %2 === 0){
            console.log(x);
        }
        x++;
    }
 }
</code>```

Visualize Execution Here

Title: Print par numbers

Body:
I want to print some par numbers in a range between (32, 321), but it's not working. I am using this code :

<!DOCTYPE html>

  <meta charset="UFT-8">
  <title> </title>

I am receiving 32 only. How can I make it work?

Body:
return statement terminates the function as soon it is encountered. You don't need a return statement here.

function printEvenNumbers(x, y) {

    while (x < y) {
        if(x %2 === 0){
            console.log(x);
        }
        x++;
    }
 }

<a href="http://pythontutor.com/visualize.html#code=function%20printEvenNumbers%28x,%20y%29%20%7B%0A%0A%20%20%20%20while%20%28x%20%3C%20y%29%20%7B%0A%20%20%20%20%20%20%20%20if%28x%20%252%20%3D%3D%3D%200%29%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20console.log%28x%29%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20x%2B%2B%3B%0A%20%20%20%20%7D%0A%20%7D%0A%20%0A%20printEvenNumbers%285,19%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=js&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow noreferrer">Visualize Execution Here


问:
Django inspectdb not respecting primary key on two columns (postgres)
I am hooking up to an existing Postgres database with Django, using inspectdb to generate my models.py file.
The tables in the Postgres were created like this:

```<code>CREATE TABLE "a"
(
  "id" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
  CONSTRAINT "PK.a" PRIMARY KEY ("id")
)
CREATE TABLE "c"
(
  "id" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
  CONSTRAINT "PK.c" PRIMARY KEY ("id")
)
CREATE TABLE "b"
(
  "aid" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
  "cid" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
 CONSTRAINT "PK.b" PRIMARY KEY ("aid","cid"),
 CONSTRAINT "FK_a" FOREIGN KEY ("aid")
      REFERENCES "a" ("id") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE,
 CONSTRAINT "FK_c" FOREIGN KEY ("cid")
      REFERENCES "c" ("id") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)
</code>```

I then run python manage.py inspectdb --database primary > models_test.py, which results in the following models_test.py.

```<code>class A(models.Model):
    id = models.UUIDField(primary_key=True)

    class Meta:
        managed = False
        db_table = 'a'

class B(models.Model):
    aid = models.OneToOneField(A, models.DO_NOTHING, db_column='aid', primary_key=True)
    cid = models.ForeignKey('C', models.DO_NOTHING, db_column='cid')

    class Meta:
        managed = False
        db_table = 'b'
        unique_together = (('aid', 'cid'),)

class C(models.Model):
    id = models.UUIDField(primary_key=True)

    class Meta:
        managed = False
        db_table = 'c'
</code>```

note the OneToOneField defined on aid.

If I instead create table b as:

```<code>CREATE TABLE "b"
(
  "aid" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
  "cid" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
 CONSTRAINT "PK.b" PRIMARY KEY ("cid","aid"),
 CONSTRAINT "FK_a" FOREIGN KEY ("aid")
      REFERENCES "a" ("id") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE,
 CONSTRAINT "FK_c" FOREIGN KEY ("cid")
      REFERENCES "c" ("id") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)

</code>```

then rerun inspectdb I get the following output:

```<code>class A(models.Model):
    id = models.UUIDField(primary_key=True)

    class Meta:
        managed = False
        db_table = 'a'

class B(models.Model):
    aid = models.ForeignKey(A, models.DO_NOTHING, db_column='aid')
    cid = models.OneToOneField('C', models.DO_NOTHING, db_column='cid', primary_key=True)

    class Meta:
        managed = False
        db_table = 'b'
        unique_together = (('cid', 'aid'),)

class C(models.Model):
    id = models.UUIDField(primary_key=True)

    class Meta:
        managed = False
        db_table = 'c'
</code>```

note the OneToOneField is now on cid. I suspect this is a bug, but I am inexperienced so wanted to ask here before reporting.
Secondary question: if this is a bug, is it worth reporting? Maybe the database design is very poor or uncommon?

答:
I suspect this is a bug, but I am inexperienced so wanted to ask here before reporting.

Not really. Django does not work with primary keys that span over two or more columns, or at least not at the moment of writing. It has been requested, for example by ticket #373, but the designers decided to set this on "wontfix".

The documentation furthermore explains this:

Do Django models support multiple-column primary keys?

No. Only single-column primary keys are supported.

But this isn’t an issue in practice, because there’s nothing stopping
  you from adding other constraints (using the unique_together model
  option or creating the constraint directly in your database), and
  enforcing the uniqueness at that level. Single-column primary keys are
  needed for things such as the admin interface to work; e.g., you need
  a single value to specify an object to edit or delete.

Likely you will not be able to do that in the (near) future, since a lot of Django tooling is built with the assumption that primary keys are "scalar" entities.

You thus likely should slightly redesign your existing database, and try to run inspectdb after that.

Body:
I am hooking up to an existing Postgres database with Django, using inspectdb to generate my models.py file.
The tables in the Postgres were created like this:

CREATE TABLE "a"
(
  "id" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
  CONSTRAINT "PK.a" PRIMARY KEY ("id")
)
CREATE TABLE "c"
(
  "id" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
  CONSTRAINT "PK.c" PRIMARY KEY ("id")
)
CREATE TABLE "b"
(
  "aid" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
  "cid" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
 CONSTRAINT "PK.b" PRIMARY KEY ("aid","cid"),
 CONSTRAINT "FK_a" FOREIGN KEY ("aid")
      REFERENCES "a" ("id") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE,
 CONSTRAINT "FK_c" FOREIGN KEY ("cid")
      REFERENCES "c" ("id") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)

I then run python manage.py inspectdb --database primary > models_test.py, which results in the following models_test.py.

class A(models.Model):
    id = models.UUIDField(primary_key=True)

    class Meta:
        managed = False
        db_table = 'a'

class B(models.Model):
    aid = models.OneToOneField(A, models.DO_NOTHING, db_column='aid', primary_key=True)
    cid = models.ForeignKey('C', models.DO_NOTHING, db_column='cid')

    class Meta:
        managed = False
        db_table = 'b'
        unique_together = (('aid', 'cid'),)

class C(models.Model):
    id = models.UUIDField(primary_key=True)

    class Meta:
        managed = False
        db_table = 'c'

note the OneToOneField defined on aid.

If I instead create table b as:

CREATE TABLE "b"
(
  "aid" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
  "cid" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
 CONSTRAINT "PK.b" PRIMARY KEY ("cid","aid"),
 CONSTRAINT "FK_a" FOREIGN KEY ("aid")
      REFERENCES "a" ("id") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE,
 CONSTRAINT "FK_c" FOREIGN KEY ("cid")
      REFERENCES "c" ("id") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)

then rerun inspectdb I get the following output:

class A(models.Model):
    id = models.UUIDField(primary_key=True)

    class Meta:
        managed = False
        db_table = 'a'

class B(models.Model):
    aid = models.ForeignKey(A, models.DO_NOTHING, db_column='aid')
    cid = models.OneToOneField('C', models.DO_NOTHING, db_column='cid', primary_key=True)

    class Meta:
        managed = False
        db_table = 'b'
        unique_together = (('cid', 'aid'),)

class C(models.Model):
    id = models.UUIDField(primary_key=True)

    class Meta:
        managed = False
        db_table = 'c'

note the OneToOneField is now on cid. I suspect this is a bug, but I am inexperienced so wanted to ask here before reporting.
Secondary question: if this is a bug, is it worth reporting? Maybe the database design is very poor or uncommon?


问:
Write CSV file from scraped data with Beautiful Soup
This is how I scraped the data using Beautifulsoup.

```<code>comments =[]
users_list = []
users = driver.find_elements_by_class_name('_6lAjh')

for user in users:
    users_list.append(user.text)

i = 0
texts_list = []
texts = driver.find_elements_by_class_name('C4VMK')

for txt in texts:
    texts_list.append(txt.text.split(users_list[i])[1].replace("\r"," ").replace("\n"," "))
    i += 1
    comments_count = len(users_list)

for i in range(1, comments_count):
    user = users_list[i]
    text = texts_list[i]
    print("User ",user)
    print("Text ",text)
    print()
    comments.append(users_list[i])
    comments.append(texts_list[i])
    idxs = [m.start() for m in re.finditer('@', text)]
    for idx in idxs:
        handle = text[idx:].split(" ")[0]

print(handle)
</code>```

This is the text data I have which are username, comments, and number of likes from instagram.
' heyyy 3w1 likeReply' -> 'heyyy' is comment in here, 3w means the comment was written 3weeks ago, 1 like is number of likes

```<code>print(comments)
</code>```

```<code>['User1',
 '  3w1 likeReply',
 'User2',
 '  3w1 likeReply',
 'User3',
 ' Looking good! Collab, DM "bruteimpact.fashion 3wReply',
 'User4',
 ' heyyy 3w5 likeReply']
</code>```

I want to save this into CSV file that looks like this(three columns- ID, Comments, likes_count):

```<code>ID  Comments  likes_count
User1        0
User2        1
User3 Looking good! Collab, DM "bruteimpact.fashion  0
User4 heyyy    5
</code>```

so far this is the code I wrote but is far from the result I want to get and I do not know how to get to the final destination at all. Plus, I have no idea how to make separate 'likes_count' by detaching the number of likes from the comment data I have. However, I would be satisfied with CSV file with just "ID" and "Text" column without "likes_count". Please help me!

```<code>fields = ["User", "Text"]
rows = [comments]
filename = "insta_records.csv"
with open(filename, 'w', encoding='utf-8') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(fields)
    csvwriter.writerows(rows)
</code>```

答:
You have flat list so you could use zip to group user and its comment

```<code>comments = ['User1',
 '  3w1 likeReply',
 'User2',
 '  3w1 likeReply',
 'User3',
 ' Looking good! Collab, DM "bruteimpact.fashion 3wReply',
 'User4',
 ' heyyy 3w5 likeReply']

rows = []
for user, text in zip(comments[::2], comments[1::2]):
    print(user, text)
    #rows.append([user, text])

fields = ["User", "Text"]
filename = "insta_records.csv"
with open(filename, 'w', encoding='utf-8') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(fields)
    csvwriter.writerows(rows)
</code>```

Result on screen

```<code>User1   3w1 likeReply
User2   3w1 likeReply
User3  Looking good! Collab, DM "bruteimpact.fashion 3wReply
User4  heyyy 3w5 likeReply
</code>```

And in file

```<code>User,Text
User1,  3w1 likeReply
User2,  3w1 likeReply
User3," Looking good! Collab, DM ""bruteimpact.fashion 3wReply"
User4, heyyy 3w5 likeReply
</code>```

To create other columns you would have to first edit comments - split(), replace(),
slice [start:end],  etc.

```<code>rows = []
for user, text in zip(comments[::2], comments[1::2]):
    parts = text.rsplit(' ', 2)#[:-1]
    parts.insert(0, user)
    print(parts)
    rows.append(parts)
</code>```

Result on screen

```<code>['User1', ' ', '3w1', 'likeReply']
['User2', ' ', '3w1', 'likeReply']
['User3', ' Looking good! Collab, DM', '"bruteimpact.fashion', '3wReply']
['User4', ' heyyy', '3w5', 'likeReply']
</code>```

but there is missing space in '3wReply' so it doesn't split it correctly and it would need more work to split it correctly.

BTW: when you have 3w5 then you can split('w') to get ['3', '5'] but in HTML can be other text instead of w so it would need more work. Maybe using more complex rules in BeautifulSoup you could better split it.

Body:
This is how I scraped the data using Beautifulsoup.

comments =[]
users_list = []
users = driver.find_elements_by_class_name('_6lAjh')

for user in users:
    users_list.append(user.text)

i = 0
texts_list = []
texts = driver.find_elements_by_class_name('C4VMK')

for txt in texts:
    texts_list.append(txt.text.split(users_list[i])[1].replace("\r"," ").replace("\n"," "))
    i += 1
    comments_count = len(users_list)

for i in range(1, comments_count):
    user = users_list[i]
    text = texts_list[i]
    print("User ",user)
    print("Text ",text)
    print()
    comments.append(users_list[i])
    comments.append(texts_list[i])
    idxs = [m.start() for m in re.finditer('@', text)]
    for idx in idxs:
        handle = text[idx:].split(" ")[0]

print(handle)

This is the text data I have which are username, comments, and number of likes from instagram.
' heyyy 3w1 likeReply' -> 'heyyy' is comment in here, 3w means the comment was written 3weeks ago, 1 like is number of likes

print(comments)

['User1',
 '  3w1 likeReply',
 'User2',
 '  3w1 likeReply',
 'User3',
 ' Looking good! Collab, DM "bruteimpact.fashion 3wReply',
 'User4',
 ' heyyy 3w5 likeReply']

I want to save this into CSV file that looks like this(three columns- ID, Comments, likes_count):

ID  Comments  likes_count
User1        0
User2        1
User3 Looking good! Collab, DM "bruteimpact.fashion  0
User4 heyyy    5

so far this is the code I wrote but is far from the result I want to get and I do not know how to get to the final destination at all. Plus, I have no idea how to make separate 'likes_count' by detaching the number of likes from the comment data I have. However, I would be satisfied with CSV file with just "ID" and "Text" column without "likes_count". Please help me!

fields = ["User", "Text"]
rows = [comments]
filename = "insta_records.csv"
with open(filename, 'w', encoding='utf-8') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(fields)
    csvwriter.writerows(rows)

Body:
You have flat list so you could use zip to group user and its comment

comments = ['User1',
 '  3w1 likeReply',
 'User2',
 '  3w1 likeReply',
 'User3',
 ' Looking good! Collab, DM "bruteimpact.fashion 3wReply',
 'User4',
 ' heyyy 3w5 likeReply']

rows = []
for user, text in zip(comments[::2], comments[1::2]):
    print(user, text)
    #rows.append([user, text])

fields = ["User", "Text"]
filename = "insta_records.csv"
with open(filename, 'w', encoding='utf-8') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(fields)
    csvwriter.writerows(rows)

Result on screen

User1   3w1 likeReply
User2   3w1 likeReply
User3  Looking good! Collab, DM "bruteimpact.fashion 3wReply
User4  heyyy 3w5 likeReply

And in file

User,Text
User1,  3w1 likeReply
User2,  3w1 likeReply
User3," Looking good! Collab, DM ""bruteimpact.fashion 3wReply"
User4, heyyy 3w5 likeReply

To create other columns you would have to first edit comments - split(), replace(),
slice [start:end],  etc.

rows = []
for user, text in zip(comments[::2], comments[1::2]):
    parts = text.rsplit(' ', 2)#[:-1]
    parts.insert(0, user)
    print(parts)
    rows.append(parts)

Result on screen

['User1', ' ', '3w1', 'likeReply']
['User2', ' ', '3w1', 'likeReply']
['User3', ' Looking good! Collab, DM', '"bruteimpact.fashion', '3wReply']
['User4', ' heyyy', '3w5', 'likeReply']

but there is missing space in '3wReply' so it doesn't split it correctly and it would need more work to split it correctly.

BTW: when you have 3w5 then you can split('w') to get ['3', '5'] but in HTML can be other text instead of w so it would need more work. Maybe using more complex rules in BeautifulSoup you could better split it.


问:
How to know if an image is created using OpenCV in Python?
I'm in a situation where I need to identify different kinds of input, including files, folders, images, etc. In case of images, I need to specifically know if an image is created using OpenCV (for the fact that it may be BGR), or any other types of images.

I noticed images created using skimage.io.imread, matplotlib.pyplot.imread, and opencvs cv2.imread(), are all numpy.ndarray, and there is no way I can distinguish between them.

I tried to use opencv's cv2.cvtColor(img, cv2.COLOR_BGR2RGB) on the input image, hoping the non-opencv images would cause an exception and thus I can identify if the image is opencvs or not.

Unfortunately only PIL, images fail this this and both matplotlibs and skimages run just fine (they change from RGB to BGR so thats not good either).

I tried to find the underlying dtype, but they are all the same(uint8).
I tried to find an attribute specific to opencv so others cant have it, so by querying that attribute, I may be able to know if that's an opencv image to no avail!

I only receive an object from the input and in case of images, there is no way of knowing in advance, what was the source of the sent image (was it read using opencv? should I use the conversion to RGB, or else, you get the idea and down the pipeline, each input has its own set of operations to execute.

Update:

Using type(), I can distinguish between all images except matplotlibs and opencvs. I cant seem to find a way to distiguish between these two!

答: After a long discussion, the answer is clear. The question you are asking, "Can you distinguish between images loaded with matplotlib and openvc?" has to be answered with no.


问:
How to customize ModelMapper
I want to use ModelMapper to convert entity to DTO and back. Mostly it works, but how do I customize it. It has has so many options that it's hard to figure out where to start. What's best practice?

I'll answer it myself below, but if another answer is better I'll accept it.

答:
```<code>import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EntityDtoConversionUtil {

    @Autowired
    private ModelMapper modelMapper;

    public Object convert(Object object,Class<?> type) {

        Object MapperObject=modelMapper.map(object, type);

        return MapperObject;

    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to customize ModelMapper


问:
How to convert server datatime to clients datetime ? C#.NET
I am having a issue that the when clients saves their data it saves the data in server date..Due to this they are unable to fetch their data according to date and time..Server Time is in Usa and clients time is in India ? Your ideas will be welcome </p>

答:
You could try to get Indian Local Time

```<code>                DateTime dateTime = DateTime.Now;

                DateTime utcTime = dateTime.ToUniversalTime();

                TimeZoneInfo indZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

                DateTime yourLocalTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, indZone);
</code>```

For further customization you could follow below Interface on screen
  shot. Just explore it by pressing F12 on FindSystemTimeZoneById on
  above mentioned code.

If you want to know more details about different time conversion please refer to this official docs additionally this docs

Body:
You could try to get Indian Local Time

                DateTime dateTime = DateTime.Now;

                DateTime utcTime = dateTime.ToUniversalTime();

                TimeZoneInfo indZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

                DateTime yourLocalTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, indZone);

For further customization you could follow below Interface on screen
  shot. Just explore it by pressing F12 on FindSystemTimeZoneById on
  above mentioned code.

If you want to know more details about different time conversion please refer to this official docs additionally this docs


问:
Saving input value to a variable instantly
Hello,

I need to instantly save the value of an input into a variable , adding keyup or keydown event listeners only updates the variable with the previous value of the input.

Is there any better solution than using setTimeout() ?

```<code>document.getElementById('project').addEventListener('keydown', function projectNameVerifyInit() {
  let projectName = document.getElementById('project').value;
  console.log(projectName);
});
</code>```

<input type="text" name="project" id="project" placeholder="Project Name" autofocus required>

Thanks

答:
Use Input event.</p>

```<code>document.getElementById('project').addEventListener('input', function (evt) {
    let projectName = document.getElementById('project').value;
    console.log(projectName);
})
</code>```

Body:
Hello,

I need to instantly save the value of an input into a variable , adding keyup or keydown event listeners only updates the variable with the previous value of the input.

Is there any better solution than using setTimeout() ?

document.getElementById('project').addEventListener('keydown', function projectNameVerifyInit() {
  let projectName = document.getElementById('project').value;
  console.log(projectName);
});

<input type="text" name="project" id="project" placeholder="Project Name" autofocus required>

Thanks

Body:
Use Input event.

document.getElementById('project').addEventListener('input', function (evt) {
    let projectName = document.getElementById('project').value;
    console.log(projectName);
})


问:
Angular Material navbar - can't see labels
Here is my code for navbar:

```<code><nav mat-tab-nav-bar>
    <a mat-tab-link
      *ngFor="let link of navLinks"
      [routerLink]="link.link"
      routerLinkActive #rla="routerLinkActive"
      [active]="rla.isActive">
    </a>
</nav>
</code>```

And component:

```<code>export class SettingsComponent implements OnInit {
  navLinks: any[];
  activeLinkIndex = -1;
  constructor(private router: Router) {
    this.navLinks = [
        {
            label: 'First',
            link: 'syspref',
            index: 0
        }, {
            label: 'Second',
            link: 'userpref',
            index: 1
        }
    ];
}
ngOnInit(): void {
    this.router.events.subscribe((res) => {
        this.activeLinkIndex = this.navLinks.indexOf(this.navLinks.find(tab => tab.link === '.' + this.router.url));
    });
  }
}
</code>```

It works fine except that I dont see labels. Any idea why?

Thanks

答:
Found it. I was missing {{link.label}}:</p>

```<code><nav mat-tab-nav-bar>
    <a mat-tab-link
      *ngFor="let link of navLinks"
      [routerLink]="link.link"
      routerLinkActive #rla="routerLinkActive"
      [active]="rla.isActive">{{link.label}}
    </a>
</nav>
</code>```

Body:
Here is my code for navbar:

And component:

export class SettingsComponent implements OnInit {
  navLinks: any[];
  activeLinkIndex = -1;
  constructor(private router: Router) {
    this.navLinks = [
        {
            label: 'First',
            link: 'syspref',
            index: 0
        }, {
            label: 'Second',
            link: 'userpref',
            index: 1
        }
    ];
}
ngOnInit(): void {
    this.router.events.subscribe((res) => {
        this.activeLinkIndex = this.navLinks.indexOf(this.navLinks.find(tab => tab.link === '.' + this.router.url));
    });
  }
}

It works fine except that I dont see labels. Any idea why?

Thanks

Body:
Found it. I was missing {{link.label}}:

<nav mat-tab-nav-bar>
    <a mat-tab-link
      *ngFor="let link of navLinks"
      [routerLink]="link.link"
      routerLinkActive #rla="routerLinkActive"
      [active]="rla.isActive">{{link.label}}
    </a>
</nav>


问:
Rendering a new component inside componentDidMount - React
I will have to render a new component after all the expected components are loaded. I will need a timeout based on which the the new component has to be rendered. So this new component has to show up after 5 minutes after the page has loaded.
I need to render a component called new_component that extends React.component

```<code>public componentDidMount(): void {
      if (visited) {
      setTimeout(() => {
        console.log('Reached the timeout')
        //Render the new conponent here. (Not sure how to call the render function of another component here)
      }, timeout);
    }
</code>```

Can someone help me call the render function of new_component inside componentDidMount please. i tried new_component.render(). But that does not seem to work.

答:
You can go with this code, wait and then render new one:

```<code>cosnt FIVE_MIN = 5 * 60 * 1000

class Example {
  this.state = { isShowComponent: false }
  timer

  componentDidMount() {
    this.timer = setTimeout(() => {
      this.setState({ isShowComponent: true })
    }, FIVE_MIN)
  }

  componentWilllUnmount() {
    clearTimeout(this.timer)
  }

  render() {
    if (this.state.isShowComponent) return <NewComponent />

    return <Component />
  }
}
</code>```

:)

Body:
I will have to render a new component after all the expected components are loaded. I will need a timeout based on which the the new component has to be rendered. So this new component has to show up after 5 minutes after the page has loaded.
I need to render a component called new_component that extends React.component

public componentDidMount(): void {
      if (visited) {
      setTimeout(() => {
        console.log('Reached the timeout')
        //Render the new conponent here. (Not sure how to call the render function of another component here)
      }, timeout);
    }

Can someone help me call the render function of new_component inside componentDidMount please. i tried new_component.render(). But that does not seem to work.

Body:
You can go with this code, wait and then render new one:

cosnt FIVE_MIN = 5 * 60 * 1000

class Example {
  this.state = { isShowComponent: false }
  timer

  componentDidMount() {
    this.timer = setTimeout(() => {
      this.setState({ isShowComponent: true })
    }, FIVE_MIN)
  }

  componentWilllUnmount() {
    clearTimeout(this.timer)
  }

  render() {
    if (this.state.isShowComponent) return <NewComponent />

    return <Component />
  }
}

:)


问:
Kotlin filter Search EditText in RecyclerView
In my android app Api 28 with Kotlin, I create an Interface "listOfCountry.xml", an editText for search and a recycler view that contains all the list of country as the following code:

```<code>           <EditText
                android:id="@+id/search"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:padding="5dp"
                android:layout_weight="1"
                android:background="@android:color/transparent"
                android:fontFamily="@font/cairo"
                android:hint="Search..."
                android:imeOptions="actionSearch"
                android:maxLines="1"
                android:singleLine="true"
                android:textSize="14sp"/>

    <TextView
        android:id="@+id/cancelSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/cairo"
        android:layout_marginTop="15dp"
        android:layout_marginStart="20dp"
        android:text="@string/cancel_msg"
        android:textSize="14sp" />

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerViewGovernmentOrSectionList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginStart="20dp"
    android:layout_marginEnd="20dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/lyt_search" />
</code>```

I want to get a country from the list with the search filter, the following code is the description of my adapter :

```<code>class CountryItemAdapter(var countries: Array<AddressesData>, var mListener: OnItemClickListener) : RecyclerView.Adapter<CountryItemAdapter.ViewHolder>()
        , Filterable {

    private var selectedPos = -1
    var searchableList: MutableList<AddressesData> = arrayListOf()
    private var onNothingFound: (() -> Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_country, parent, false)
        return ViewHolder(view)
    }
    override fun getItemCount() = countries.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item: AddressesData = countries[position]
        holder.tickImage.visibility = (if (selectedPos == position) View.VISIBLE else View.GONE)
        holder.country.text = item.englishName.toString()

        holder.itemView.setOnClickListener {
            selectedPos = position
            mListener.onItemClick(holder.itemView, item)
            notifyDataSetChanged()
        }

    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val country: TextView = itemView.counrty
        val tickImage: ImageView = itemView.tickGovernment
    }

    interface OnItemClickListener {
        fun onItemClick(view: View, viewModel: AddressesData)
    }
    override fun getFilter(): Filter {
        return object : Filter() {
            private val filterResults = FilterResults()
            override fun performFiltering(constraint: CharSequence?): FilterResults {
                searchableList.clear()
                if (constraint.isNullOrBlank()) {
                    searchableList.addAll(countries)
                } else {
                    val filterPattern = constraint.toString().toLowerCase().trim { it <= ' ' }
                    for (item in 0..countries.size) {
                        if (countries[item].englishName!!.toLowerCase().contains(filterPattern)) {
                            searchableList.add(countries[item])
                        }
                    }}
                    return filterResults.also {
                        it.values = searchableList
                    }
                }

                override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
                    if (searchableList.isNullOrEmpty())
                        onNothingFound?.invoke()
                    notifyDataSetChanged()

                }
</code>```

and I add the following code in my activity :

```<code>search.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                adapter.filter.filter(charSequence.toString())

            }

            override fun afterTextChanged(editable: Editable) {}
        })
</code>```

The filter didn't work, I would like to know where's the problem in my code and How can I correct it to make the filter work ?

答: I think you lost getItemCount method in your adapter, it must return actual size of items in adapter.

Body:
In my android app Api 28 with Kotlin, I create an Interface "listOfCountry.xml", an editText for search and a recycler view that contains all the list of country as the following code:

           <EditText
                android:id="@+id/search"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:padding="5dp"
                android:layout_weight="1"
                android:background="@android:color/transparent"
                android:fontFamily="@font/cairo"
                android:hint="Search..."
                android:imeOptions="actionSearch"
                android:maxLines="1"
                android:singleLine="true"
                android:textSize="14sp"/>

    <TextView
        android:id="@+id/cancelSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/cairo"
        android:layout_marginTop="15dp"
        android:layout_marginStart="20dp"
        android:text="@string/cancel_msg"
        android:textSize="14sp" />

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerViewGovernmentOrSectionList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginStart="20dp"
    android:layout_marginEnd="20dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/lyt_search" />

I want to get a country from the list with the search filter, the following code is the description of my adapter :

class CountryItemAdapter(var countries: Array<AddressesData>, var mListener: OnItemClickListener) : RecyclerView.Adapter<CountryItemAdapter.ViewHolder>()
        , Filterable {

    private var selectedPos = -1
    var searchableList: MutableList<AddressesData> = arrayListOf()
    private var onNothingFound: (() -> Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_country, parent, false)
        return ViewHolder(view)
    }
    override fun getItemCount() = countries.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item: AddressesData = countries[position]
        holder.tickImage.visibility = (if (selectedPos == position) View.VISIBLE else View.GONE)
        holder.country.text = item.englishName.toString()

        holder.itemView.setOnClickListener {
            selectedPos = position
            mListener.onItemClick(holder.itemView, item)
            notifyDataSetChanged()
        }

    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val country: TextView = itemView.counrty
        val tickImage: ImageView = itemView.tickGovernment
    }

    interface OnItemClickListener {
        fun onItemClick(view: View, viewModel: AddressesData)
    }
    override fun getFilter(): Filter {
        return object : Filter() {
            private val filterResults = FilterResults()
            override fun performFiltering(constraint: CharSequence?): FilterResults {
                searchableList.clear()
                if (constraint.isNullOrBlank()) {
                    searchableList.addAll(countries)
                } else {
                    val filterPattern = constraint.toString().toLowerCase().trim { it <= ' ' }
                    for (item in 0..countries.size) {
                        if (countries[item].englishName!!.toLowerCase().contains(filterPattern)) {
                            searchableList.add(countries[item])
                        }
                    }}
                    return filterResults.also {
                        it.values = searchableList
                    }
                }

                override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
                    if (searchableList.isNullOrEmpty())
                        onNothingFound?.invoke()
                    notifyDataSetChanged()

                }

and I add the following code in my activity :

search.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                adapter.filter.filter(charSequence.toString())

            }

            override fun afterTextChanged(editable: Editable) {}
        })

The filter didn't work, I would like to know where's the problem in my code and How can I correct it to make the filter work ?


问:
Increasing limit of outgoing TCP connections on MacOS
Short version of question is: How to tune\configure macOS (Mojave 10.14.3) settings to allow more then 10k outgoing TCP connections per process and more then 16k connections in total.

Details:

I'm trying to make MacBookPro (16Gb RAM, Core i7) usable for stress-testing tcp server. Server itself hosted on separate pc, so right now the question is about outgoing connections only.

Below advices already processed and helped me significantly increase initial os limits.

1) I used [launchctl] ("Too many open files" when executing gatling on Mac) to increase maxfiles limit to 1 million.

2) I used sysctl to set\check kern.maxfiles limits. Actually (as I understand) this is the same as #1.

3) I played with ulimit. Actually I didn't notice any effect of this tool on my OS. But any way...

So now I MacOS can establish ~10k connections per process and 16k total connections in the system.

For simplicity my tool just open TCP connections in a infinite loop and waits.

```<code>try
{
  while (true)
  {
    CreateAndConnectSocket(); //add socket to list
    ++connectedSockets;
  }
}
catch(Exception e)
{
  LogWrite("Connected sockets:" + connectedSockets);
  LogWrite(e);
  WaitForAnyKey();
}
</code>```

Then I follow below steps.

1) Launch server on separate PC.
2) Open two terminals on mac.

3) Execute in first terminal window:

```<code>$ sudo launchctl limit maxfiles 1048576 1048600
$ ulimit -S -n 1048576
</code>```

4) Verify that changes applied in first terminal:

```<code>$ ulimit -S -n
1048576
$ launchctl limit maxfiles
    maxfiles    1048576        1048600
$ sysctl kern.maxfilesperproc
kern.maxfilesperproc: 1048576
$ sysctl kern.maxfiles
kern.maxfiles: 1048600
</code>```

5) Launch "ulimit -S -n 1048576" in second terminal (Not sure that ulimit is required at all.)

6) Verify that all changes applied in second terminal window (same as #4).
7) Launch "test client" in first terminal.

8) Launch "test client" in second terminal.

Result:

After step 7 in first terminal I can see, that tool opened 10k connections (10202 to be precise) and fell down with exception "Too many open files in system".  Have no idea why opened files is an issue with 1 million limit.

After step 8 in second terminal I can see that tool opened 6k connectoins and fell down with exception "Can't assign requested address".

While sockets remain opened (tools wait for key press), no other connections can be created in the system - browsers can't establish connections to google.com, etc.

And ofcourse tcp server remains accessible from another PCs.

Since I was able to tune "Windows 10 Home" for higher connection numbers, I believe that MacOS can be tuned too.

答:
16383 TCP connections (from the same IP to the same port) is the limit imposed by default in MacOs (at least in Mojave).

This limit is defined by the ephemeral port range:

```<code>$ sudo sysctl net.inet.ip.portrange

net.inet.ip.portrange.lowfirst: 1023
net.inet.ip.portrange.lowlast: 600
net.inet.ip.portrange.first: 49152
net.inet.ip.portrange.last: 65535
net.inet.ip.portrange.hifirst: 49152
net.inet.ip.portrange.hilast: 65535
</code>```

By default the range starts from 49152 (net.inet.ip.portrange.first) and ends to 65535 (net.inet.ip.portrange.last). That is, 65535 - 49152 = 16383.

You can make the ephemeral port range starting from 32768:

```<code>sudo sysctl -w net.inet.ip.portrange.first=32768
</code>```

This way you double the available ephemeral ports (65535 - 32768 = 32767).

Body:
Short version of question is: How to tune\configure macOS (Mojave 10.14.3) settings to allow more then 10k outgoing TCP connections per process and more then 16k connections in total.

Details:

I'm trying to make MacBookPro (16Gb RAM, Core i7) usable for stress-testing tcp server. Server itself hosted on separate pc, so right now the question is about outgoing connections only.

Below advices already processed and helped me significantly increase initial os limits.

1) I used [launchctl] ("Too many open files" when executing gatling on Mac) to increase maxfiles limit to 1 million.

2) I used sysctl to set\check kern.maxfiles limits. Actually (as I understand) this is the same as #1.

3) I played with ulimit. Actually I didn't notice any effect of this tool on my OS. But any way...

So now I MacOS can establish ~10k connections per process and 16k total connections in the system.

For simplicity my tool just open TCP connections in a infinite loop and waits.

try
{
  while (true)
  {
    CreateAndConnectSocket(); //add socket to list
    ++connectedSockets;
  }
}
catch(Exception e)
{
  LogWrite("Connected sockets:" + connectedSockets);
  LogWrite(e);
  WaitForAnyKey();
}

Then I follow below steps.

1) Launch server on separate PC.
2) Open two terminals on mac.

3) Execute in first terminal window:

$ sudo launchctl limit maxfiles 1048576 1048600
$ ulimit -S -n 1048576

4) Verify that changes applied in first terminal:

$ ulimit -S -n
1048576
$ launchctl limit maxfiles
    maxfiles    1048576        1048600
$ sysctl kern.maxfilesperproc
kern.maxfilesperproc: 1048576
$ sysctl kern.maxfiles
kern.maxfiles: 1048600

5) Launch "ulimit -S -n 1048576" in second terminal (Not sure that ulimit is required at all.)

6) Verify that all changes applied in second terminal window (same as #4).
7) Launch "test client" in first terminal.

8) Launch "test client" in second terminal.

Result:

After step 7 in first terminal I can see, that tool opened 10k connections (10202 to be precise) and fell down with exception "Too many open files in system".  Have no idea why opened files is an issue with 1 million limit.

After step 8 in second terminal I can see that tool opened 6k connectoins and fell down with exception "Can't assign requested address".

While sockets remain opened (tools wait for key press), no other connections can be created in the system - browsers can't establish connections to google.com, etc.

And ofcourse tcp server remains accessible from another PCs.

Since I was able to tune "Windows 10 Home" for higher connection numbers, I believe that MacOS can be tuned too.

Body:
16383 TCP connections (from the same IP to the same port) is the limit imposed by default in MacOs (at least in Mojave).

This limit is defined by the ephemeral port range:

$ sudo sysctl net.inet.ip.portrange

net.inet.ip.portrange.lowfirst: 1023
net.inet.ip.portrange.lowlast: 600
net.inet.ip.portrange.first: 49152
net.inet.ip.portrange.last: 65535
net.inet.ip.portrange.hifirst: 49152
net.inet.ip.portrange.hilast: 65535

By default the range starts from 49152 (net.inet.ip.portrange.first) and ends to 65535 (net.inet.ip.portrange.last). That is, 65535 - 49152 = 16383.

You can make the ephemeral port range starting from 32768:

sudo sysctl -w net.inet.ip.portrange.first=32768

This way you double the available ephemeral ports (65535 - 32768 = 32767).


答:
you can render your component by your state.</p>

```<code>class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isTimeout: false,
    };
  }
  componentDidUpdate(prevProps, prevState) {
    this.checkTimeout = setTimeout(() => {
      this.setState(() => ({isTimeout: true}))
    }, 500);
  }
  componentWillUnmount() {
    // clean it up when the component is unmounted.
    clearTimeout(this.checkTimeout);
  }
  render () {
    if (isTimeout) {
        return (k<h1>time is running out</h1>)
    }

    return (<h1>hello world.</h1>)
  }
}
</code>```

Title: Rendering a new component inside componentDidMount - React

Body:
you can render your component by your state.

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isTimeout: false,
    };
  }
  componentDidUpdate(prevProps, prevState) {
    this.checkTimeout = setTimeout(() => {
      this.setState(() => ({isTimeout: true}))
    }, 500);
  }
  componentWillUnmount() {
    // clean it up when the component is unmounted.
    clearTimeout(this.checkTimeout);
  }
  render () {
    if (isTimeout) {
        return (k<h1>time is running out</h1>)
    }

    return (<h1>hello world.</h1>)
  }
}


问:
struct/constructor/pointer - C programming language
I have an issue on a problem involving creating a data structure that encapsulates an input buffer. My problem is currently with malloc but I feel it is probably actually some pointer defining that I am getting wrong

I have to create a constructor that takes an 10x10 8-bit two dimensional array and creates a copy of it for processing.

It must use the following function declaration and struct definition.

```<code>file - SP.h
typedef struct SP_struct    {
    uint8_t *   base_of_buffer;
    uint16_t    width;
    uint16_t    height;
    uint16_t    x0;
    uint16_t    y0;
    uint8_t     pixel_size;
} SP_struct;

SP_struct*             SP_create           (const unsigned char* s, int width, int height); // constructor

</code>```

```<code>#include "pixel_sum.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main()
{
    uint16_t i = 0;
    unsigned char dummy_array[4][4] = {0,1,0,1,
                                        1,2,1,0,
                                        0,1,4,1,
                                        1,0,1,0};

    printf( "\nMain loop\n" );
    printf( "*dummy_array = %d\n",*dummy_array);

    struct SP_struct *SP_struct_ptr = SP_create(* dummy_array, 4, 4);
    struct SP_struct *SP_struct_ptr2 = SP_create(* dummy_array, 4, 4); // if this line is un commented it works fine
    printf("FINISHED MAIN LOOP");

}

SP_struct*     SP_create(const unsigned char* s, int width, int height){
    uint16_t i = 0;
    printf( "--------------SP_create\n" );
    printf( "*s = %d\n",*s); // This gets value
    printf( "s = %d\n",s); // This gets value

    // printf( "%d\n",width);
    // printf( "%d\n",height);

    SP_struct *p = malloc(width*height*sizeof(p->pixel_size));;
    printf( "p = %d\n",p); // This gets value
    printf( "&p = %d\n",&p); // This gets value
     p->x0 = 12;
     p->y0 = 12;
    //p
    printf( "p->base_of_buffer = %d\n",p->base_of_buffer);
    printf( "&p->x0 = %d\n",&p->x0);
    printf( "p->x0 = %d\n",p->x0);
    printf( "p->y0 = %d\n",p->y0);
    for(i = 0; i< width*height; i++) {
        p->base_of_buffer[0+i] = s[i];
        //printf( "%d . ",i);
        printf( "%d\n",p->base_of_buffer[0+i]);
    }

    return p    ;
}
</code>```

When I run it with the line for SP_struct_ptr2 commented out it runs fine and gives me a pointer and correct addresses..

but when I comment back in the SP_struct_ptr2  line I get..

Has any got any ideas? I am using gcc 6.3.0 on windows 64-bit and these are the only files in compilation.

答:
You need to allocate SP_struct and base_of_buffer separately. Your code probably should be something like this:

```<code>SP_struct*     SP_create(const unsigned char* s, int width, int height){
    ...
    SP_struct *p = malloc(sizeof(*p));
    if (p) {
        p->pixel_size = PIXEL_SIZE;
        p->base_of_buffer = malloc(width*height*sizeof(p->pixel_size)*sizeof(*p->base_of_buffer));
        ...
    }
    return p;
}
</code>```

Body:
I have an issue on a problem involving creating a data structure that encapsulates an input buffer. My problem is currently with malloc but I feel it is probably actually some pointer defining that I am getting wrong

I have to create a constructor that takes an 10x10 8-bit two dimensional array and creates a copy of it for processing.

It must use the following function declaration and struct definition.

file - SP.h
typedef struct SP_struct    {
    uint8_t *   base_of_buffer;
    uint16_t    width;
    uint16_t    height;
    uint16_t    x0;
    uint16_t    y0;
    uint8_t     pixel_size;
} SP_struct;

SP_struct*             SP_create           (const unsigned char* s, int width, int height); // constructor

#include "pixel_sum.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main()
{
    uint16_t i = 0;
    unsigned char dummy_array[4][4] = {0,1,0,1,
                                        1,2,1,0,
                                        0,1,4,1,
                                        1,0,1,0};

    printf( "\nMain loop\n" );
    printf( "*dummy_array = %d\n",*dummy_array);

    struct SP_struct *SP_struct_ptr = SP_create(* dummy_array, 4, 4);
    struct SP_struct *SP_struct_ptr2 = SP_create(* dummy_array, 4, 4); // if this line is un commented it works fine
    printf("FINISHED MAIN LOOP");

}

SP_struct*     SP_create(const unsigned char* s, int width, int height){
    uint16_t i = 0;
    printf( "--------------SP_create\n" );
    printf( "*s = %d\n",*s); // This gets value
    printf( "s = %d\n",s); // This gets value

    // printf( "%d\n",width);
    // printf( "%d\n",height);

    SP_struct *p = malloc(width*height*sizeof(p->pixel_size));;
    printf( "p = %d\n",p); // This gets value
    printf( "&p = %d\n",&p); // This gets value
     p->x0 = 12;
     p->y0 = 12;
    //p
    printf( "p->base_of_buffer = %d\n",p->base_of_buffer);
    printf( "&p->x0 = %d\n",&p->x0);
    printf( "p->x0 = %d\n",p->x0);
    printf( "p->y0 = %d\n",p->y0);
    for(i = 0; i< width*height; i++) {
        p->base_of_buffer[0+i] = s[i];
        //printf( "%d . ",i);
        printf( "%d\n",p->base_of_buffer[0+i]);
    }

    return p    ;
}

When I run it with the line for SP_struct_ptr2 commented out it runs fine and gives me a pointer and correct addresses..

but when I comment back in the SP_struct_ptr2  line I get..

Has any got any ideas? I am using gcc 6.3.0 on windows 64-bit and these are the only files in compilation.

Body:
You need to allocate SP_struct and base_of_buffer separately. Your code probably should be something like this:

SP_struct*     SP_create(const unsigned char* s, int width, int height){
    ...
    SP_struct *p = malloc(sizeof(*p));
    if (p) {
        p->pixel_size = PIXEL_SIZE;
        p->base_of_buffer = malloc(width*height*sizeof(p->pixel_size)*sizeof(*p->base_of_buffer));
        ...
    }
    return p;
}


问:
Android license status unknown and a weird problem

Steps to Reproduce

I am running flutter in windows 10. I previously had a running android setup. After cloning the flutter repo and updating path, I ran flutter doctor -v. The logs are below. Now after searching a bit for solving the problem, I came across to this solution from various stackoverflow answers: Flutter.io Android License Status Unknown
I at first executed this:
set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee

Though I don't know how to make it permanent. Then after running flutter doctor again, I came with another message, see log ###2

So it says Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses
[!] Android Studio (version 3.4). So I ran flutter doctor --android-licenses accordingly. And it gives another error, that is:
A newer version of the Android SDK is required. To update, run:
C:\Users\imazi\AppData\Local\Android\sdk\tools\bin\sdkmanager --update

Well, so I ran C:\Users\imazi\AppData\Local\Android\sdk\tools\bin\sdkmanager --update to update it. And it kinda updated successfully outputting [=======================================] 100% Computing updates...

So I thought the issue is solved and ran flutter doctor again but it seems that nothing has been changed the problem still remains. It is like a loop. I do everything and the problem remains as it is. The output of the last flutter doctor is in log ### 3

My java version is:

10.0.2 2018-07-17

Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13)

Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode)

Please help.

!! also opened a github issue here: https://github.com/flutter/flutter/issues/39637

Logs

1 flutter doctor -v

O:\Flutter installation>flutter doctor -v

```<code> [âˆš] Flutter (Channel stable, v1.7.8+hotfix.4, on Active code page: 1252
 Microsoft Windows [Version 10.0.18362.295], locale en-US)

â€¢ Flutter version 1.7.8+hotfix.4 at O:\Work_Anon\Flutter installation\flutter
â€¢ Framework revision 20e59316b8 (6 weeks ago), 2019-07-18 20:04:33 -0700
â€¢ Engine revision fee001c93f
â€¢ Dart version 2.4.0
</code>```

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.1)

```<code>
    **â€¢ Android SDK at C:\Users\imazi\AppData\Local\Android\sdk
    â€¢ Android NDK location not configured (optional; useful for native profiling support)
    â€¢ Platform android-29, build-tools 29.0.1
    â€¢ Java binary at: O:\Work_Anon\Android Studio\jre\bin\java
    â€¢ Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
    **X Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit
      https://flutter.dev/setup/#android-setup for detailed instructions.****
</code>```

[!] Android Studio (version 3.4)

```<code>â€¢ Android Studio at O:\Work_Anon\Android Studio
X Flutter plugin not installed; this adds Flutter specific functionality.
X Dart plugin not installed; this adds Dart specific functionality.
â€¢ Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
</code>```

[!] Connected device

```<code>! No devices available
</code>```

2 flutter doctor after set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee

[âˆš] Flutter (Channel stable, v1.7.8+hotfix.4, on Active code page: 1252

Microsoft Windows [Version 10.0.18362.295], locale en-US)

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.1)
       ! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses
[!] Android Studio (version 3.4)
       X Flutter plugin not installed; this adds Flutter specific functionality.
       X   Dart plugin not installed; this adds Dart specific functionality.
[!] Connected device
       ! No devices available

3 last flutter doctor

Doctor summary (to see all details, run flutter doctor -v):
[âˆš] Flutter (Channel stable, v1.7.8+hotfix.4, on Active code page: 1252

Microsoft Windows [Version 10.0.18362.295], locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.1))
    ! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses
[!] Android Studio (version 3.4)
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.

[!] Connected device
    ! No devices available

答:
I uninstall the java jdk from my system and then let my flutter doctor arise that error of " [!] Android toolchain - develop for Android devices (Android SDK version 29.0.1)"
and then followed the solution that flutter doctor was giving as it says to run the command " flutter doctor --android-licenses " and then type " y " as it says you to accept the licenses provided to solve this problem of "[!] Android toolchain - develop for Android devices (Android SDK version 29.0.1)" and then I again ran flutter doctor and the problem was resolved.</p>

Body:
Steps to Reproduce

I am running flutter in windows 10. I previously had a running android setup. After cloning the flutter repo and updating path, I ran flutter doctor -v. The logs are below. Now after searching a bit for solving the problem, I came across to this solution from various stackoverflow answers: Flutter.io Android License Status Unknown
I at first executed this:
set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee

Though I don't know how to make it permanent. Then after running flutter doctor again, I came with another message, see log ###2

So it says Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses
[!] Android Studio (version 3.4). So I ran flutter doctor --android-licenses accordingly. And it gives another error, that is:
A newer version of the Android SDK is required. To update, run:
C:\Users\imazi\AppData\Local\Android\sdk\tools\bin\sdkmanager --update

Well, so I ran C:\Users\imazi\AppData\Local\Android\sdk\tools\bin\sdkmanager --update to update it. And it kinda updated successfully outputting [=======================================] 100% Computing updates...

So I thought the issue is solved and ran flutter doctor again but it seems that nothing has been changed the problem still remains. It is like a loop. I do everything and the problem remains as it is. The output of the last flutter doctor is in log ### 3

My java version is:

10.0.2 2018-07-17

Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13)

Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode)

Please help.

!! also opened a github issue here: https://github.com/flutter/flutter/issues/39637

Logs

1 flutter doctor -v

O:\Flutter installation>flutter doctor -v

 [âˆš] Flutter (Channel stable, v1.7.8+hotfix.4, on Active code page: 1252
 Microsoft Windows [Version 10.0.18362.295], locale en-US)

â€¢ Flutter version 1.7.8+hotfix.4 at O:\Work_Anon\Flutter installation\flutter
â€¢ Framework revision 20e59316b8 (6 weeks ago), 2019-07-18 20:04:33 -0700
â€¢ Engine revision fee001c93f
â€¢ Dart version 2.4.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.1)

    **â€¢ Android SDK at C:\Users\imazi\AppData\Local\Android\sdk
    â€¢ Android NDK location not configured (optional; useful for native profiling support)
    â€¢ Platform android-29, build-tools 29.0.1
    â€¢ Java binary at: O:\Work_Anon\Android Studio\jre\bin\java
    â€¢ Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
    **X Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit
      https://flutter.dev/setup/#android-setup for detailed instructions.****

[!] Android Studio (version 3.4)

â€¢ Android Studio at O:\Work_Anon\Android Studio
X Flutter plugin not installed; this adds Flutter specific functionality.
X Dart plugin not installed; this adds Dart specific functionality.
â€¢ Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)

[!] Connected device

! No devices available

2 flutter doctor after set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee

[âˆš] Flutter (Channel stable, v1.7.8+hotfix.4, on Active code page: 1252

Microsoft Windows [Version 10.0.18362.295], locale en-US)

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.1)
       ! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses
[!] Android Studio (version 3.4)
       X Flutter plugin not installed; this adds Flutter specific functionality.
       X   Dart plugin not installed; this adds Dart specific functionality.
[!] Connected device
       ! No devices available

3 last flutter doctor

Doctor summary (to see all details, run flutter doctor -v):
[âˆš] Flutter (Channel stable, v1.7.8+hotfix.4, on Active code page: 1252

Microsoft Windows [Version 10.0.18362.295], locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.1))
    ! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses
[!] Android Studio (version 3.4)
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.

[!] Connected device
    ! No devices available


问:
How do I rotate a html canvas shape by only using a transform?
I am wondering how you can rotate an image by only using the transform function. From my understanding this is not possible, since the only things you can do with transform are the following:

Horizontal scaling

Horizontal skewing

Vertical skewing

Vertical scaling

Horizontal moving

Vertical moving

Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations

And I don't see how any of these would be able to rotate the shape, is this even possible. I assume it must be possible, since rotate is in-fact a type transformation.

答:
You have ctx.rotate(radians) function.
Read below:

https://www.w3schools.com/tags/canvas_rotate.asp


问:
How do extract path without variables in Akka Http?
I wish to obtain path without variables, for example, having api/test/132/123 I would like to get api/test. What is the best way of doing it? Can I get this done by using path directives - pathPrefix? So far I can image something like this, e.g., pass variables and remove them from string.

```<code>class UriSpec extends WordSpecLike with Matchers with ScalatestRouteTest {

  "Uri" should {

    "remain without identifiers" in new Scope {
      Get("/api/test/132/123") ~> testRoute ~> check {
        status should be(OK)
        responseAs[String] should be("/api/test")
      }
    }
  }

  private trait Scope extends Directives {

    def testRoute: Route =
      path("api" / "test" / LongNumber / LongNumber) { (n1, n2) =>
        extractMatchedPath { path =>
          complete(OK -> path.toString.replace(s"/$n1", "").replace(s"/$n2", ""))
        }
      }
  }
}
</code>```

Thank you for your help. Sorry, I didn't managed to figure out how to use existing directives, nor find existing solution.

答:
Your idea to use pathPrefix was along the right lines.  You can use that to deal with the base path and then have a separate level to deal with the variables, extracting out the current matched path in between:

```<code>      def testRoute: Route =
         pathPrefix("api" / "test") {
            extractMatchedPath { basePath =>
               path(LongNumber / LongNumber) { (n1, n2) =>
                  complete(OK -> basePath.toString)
               }
            }
         }
</code>```

That means you then have the base path separated out without the need to remove the variable parts.

Body:
I wish to obtain path without variables, for example, having api/test/132/123 I would like to get api/test. What is the best way of doing it? Can I get this done by using path directives - pathPrefix? So far I can image something like this, e.g., pass variables and remove them from string.

class UriSpec extends WordSpecLike with Matchers with ScalatestRouteTest {

  "Uri" should {

    "remain without identifiers" in new Scope {
      Get("/api/test/132/123") ~> testRoute ~> check {
        status should be(OK)
        responseAs[String] should be("/api/test")
      }
    }
  }

  private trait Scope extends Directives {

    def testRoute: Route =
      path("api" / "test" / LongNumber / LongNumber) { (n1, n2) =>
        extractMatchedPath { path =>
          complete(OK -> path.toString.replace(s"/$n1", "").replace(s"/$n2", ""))
        }
      }
  }
}

Thank you for your help. Sorry, I didn't managed to figure out how to use existing directives, nor find existing solution.

Body:
Your idea to use pathPrefix was along the right lines.  You can use that to deal with the base path and then have a separate level to deal with the variables, extracting out the current matched path in between:

      def testRoute: Route =
         pathPrefix("api" / "test") {
            extractMatchedPath { basePath =>
               path(LongNumber / LongNumber) { (n1, n2) =>
                  complete(OK -> basePath.toString)
               }
            }
         }

That means you then have the base path separated out without the need to remove the variable parts.


问:
Display result without loading/refreshing the page using php,mysql,html,javascript
I'm using php(insert.php) to store/insert data in mysql.

I'm also using another php file(display.php) to display the result.

I'd like to ask , every time when I insert, how can show the inserted data of insert.php to display.php without loading/ refreshing display.php immediately.

Thanks.

答: Use AJAX or Fetch API. On display.php in setInverval() once in few milliseconds send a request to the server. Also you can realize long polling via AJAX or Fetch API.


问:
How to import OR-Tools on Android Studio?
I am trying to implement Google's OR-Tools as mentioned in their TSP example in Android Studio.

However, I can't seem to find out how to import OR tools, and I have no experience on implementing anything outside of writing my own code.

I cannot seem to find any examples of doing this as well. Would appreciate if anyone could explain how to do this, preferably in an easy to understand manner.

答:
OR-Tools uses native C++ libraries for the solver.
We do not provide arm based compilation. So, at best, you will be able to use it an x64 based architectures.

We recommend using a android client/server based architecture.


问:
C++: Using a single get function to return the variables related to an object
I am a novice programmer working on a coding project for school.

The problem domain is as follows:

Write a C++ program related to a clock

Define a class called Clock , saved in a separate file, that includes the following members:

three member variables related to the hours, minutes and seconds

one accessor function that returns the values of the three variables (hint: use pointers)

one mutator function that modifies all variables (hint: use three arguments)

functions to increment each variable with 1 (hint: three function)

overloading functions to increment the variables with a value entered by the user (hint: the value is the argument of the function)

one default constructor that sets the clock to 0 hours, 0 minutes and 0 seconds

an overloading constructor that sets the clock to a given time (hr, min, sec)

Define a second class, saved in a separate file, that includes

a static member variable

a static member function

Include in the previously defined files C++ code that insures that a class will not be loaded twice in the main program

Define a main program, saved in a separate file, that

instantiates three objects, one with the default constructor of Clock, one with the overloaded constructor of Clock, and one based on the second class

uses the objects to call all the functions defined in the two classes:

use several ”cin” statement to read from the user the desired time and use the values as parameters for the corresponding functions that required

call each function only once, using one of the defined objects

use the accessor function to print the time after each function call that modifies the variables of the Clock class

includes code that uses the static members of the second class

we have done many examples in class where we are able to use separate get\set functions but this is the first time we are trying to do this with a single get function and pointers. Quite frankly, I am lost

Here is the contents of my header file:

```<code>// default class definition
#ifndef CLOCK1_H
#define CLOCK1_H

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class Clock
{
private:
    int hours;
    int minutes;
    int seconds;

public:
    int Clock::getInitialTime();
    int Clock::setClockTime();
    Clock::Clock();             // default constructor
    Clock::~Clock();                // default destructor
};
#endif
</code>```

Here is the contents of my source code file:

```<code>// function declarations \ main program
//

#include "stdafx.h"
#include "Clock1.h"
#include <iostream>
#include <conio.h>
using namespace std;

int Clock::getInitialTime()
{
    return hours, minutes, seconds;
}

//void Clock::setClockTime(int hr,min,sec)
//{
//  hours=hr;
//  minutes=min;
//  seconds=sec;
//}

// default constructor
Clock::Clock()
{
    hours=0;
    minutes=0;
    seconds=0;
}

// default destructor
Clock::~Clock()
{
    cin.get();
    cin.get();
}

int main()
{
    Clock defaultObj;
    defaultObj.getInitialTime();
    cout << "The initial time is " << defaultObj.getInitialTime() << endl;
    return 0;
}
</code>```

I am trying to take this in small steps, the first goal being to be able to output the initial values for the hours, minutes, seconds. once this is done, I can add additional constructor(s) with additional arguments.

My first guess is that I need to add the following:

Constructor:
add the appropriate arguments to the default constructor

```<code>Clock::Clock(int *hourPrt, int *minutePtr, int *secondPrt)
</code>```

create the pointers

```<code>Clock *hourPtr;
Clock *minutePtr;
Clock *secondPtr;
</code>```

associate them with the object's attributes

```<code>hourPrt=defaultObj.hours
minutePtr=defaultObj.minutes
secondPrt=defaultObj.seconds
</code>```

getInitialTime function
modify it some how

function call in main
modify it some how

Can anyone help me with this?

Thanks

答: You could either create a struct which contains the three values and return that, or you could return a pointer to an array of 3 ints -- make the element [0] be hours, [1] be minutes, etc. Note that if you're going to go that way in real C++ code you'd want to use something like vector so that the client doesn't have to call delete [] on the returned array later. :)

Body:
I am a novice programmer working on a coding project for school.

The problem domain is as follows:

Write a C++ program related to a clock

Define a class called Clock , saved in a separate file, that includes the following members:

three member variables related to the hours, minutes and seconds

one accessor function that returns the values of the three variables (hint: use pointers)

one mutator function that modifies all variables (hint: use three arguments)

functions to increment each variable with 1 (hint: three function)

overloading functions to increment the variables with a value entered by the user (hint: the value is the argument of the function)

one default constructor that sets the clock to 0 hours, 0 minutes and 0 seconds

an overloading constructor that sets the clock to a given time (hr, min, sec)

Define a second class, saved in a separate file, that includes

a static member variable

a static member function

Include in the previously defined files C++ code that insures that a class will not be loaded twice in the main program

Define a main program, saved in a separate file, that

instantiates three objects, one with the default constructor of Clock, one with the overloaded constructor of Clock, and one based on the second class

uses the objects to call all the functions defined in the two classes:

use several ”cin” statement to read from the user the desired time and use the values as parameters for the corresponding functions that required

call each function only once, using one of the defined objects

use the accessor function to print the time after each function call that modifies the variables of the Clock class

includes code that uses the static members of the second class

we have done many examples in class where we are able to use separate get\set functions but this is the first time we are trying to do this with a single get function and pointers. Quite frankly, I am lost

Here is the contents of my header file:

// default class definition
#ifndef CLOCK1_H
#define CLOCK1_H

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class Clock
{
private:
    int hours;
    int minutes;
    int seconds;

public:
    int Clock::getInitialTime();
    int Clock::setClockTime();
    Clock::Clock();             // default constructor
    Clock::~Clock();                // default destructor
};
#endif

Here is the contents of my source code file:

// function declarations \ main program
//

#include "stdafx.h"
#include "Clock1.h"
#include <iostream>
#include <conio.h>
using namespace std;

int Clock::getInitialTime()
{
    return hours, minutes, seconds;
}

//void Clock::setClockTime(int hr,min,sec)
//{
//  hours=hr;
//  minutes=min;
//  seconds=sec;
//}

// default constructor
Clock::Clock()
{
    hours=0;
    minutes=0;
    seconds=0;
}

// default destructor
Clock::~Clock()
{
    cin.get();
    cin.get();
}

int main()
{
    Clock defaultObj;
    defaultObj.getInitialTime();
    cout << "The initial time is " << defaultObj.getInitialTime() << endl;
    return 0;
}

I am trying to take this in small steps, the first goal being to be able to output the initial values for the hours, minutes, seconds. once this is done, I can add additional constructor(s) with additional arguments.

My first guess is that I need to add the following:

Constructor:
add the appropriate arguments to the default constructor

Clock::Clock(int *hourPrt, int *minutePtr, int *secondPrt)

create the pointers

Clock *hourPtr;
Clock *minutePtr;
Clock *secondPtr;

associate them with the object's attributes

hourPrt=defaultObj.hours
minutePtr=defaultObj.minutes
secondPrt=defaultObj.seconds

getInitialTime function
modify it some how

function call in main
modify it some how

Can anyone help me with this?

Thanks


问:
How do you launch a background process in ASPNET Core 3.0?
I know that the new ASPNET Core 3.0 stack has a number of improvements around hosting processes.

I am curious about the best way to be able to define and execute a background process from a Razor PageModel? Meaning I have some logic that needs to start something in the background and then that Razor page doesn't need to monitor it's outcome, but I would like to be able to observe it too if that's not too hard.

Can someone show me a code sample or point me in the right direction?

答:
Since this is probably a follow-up from your previous question about IHostedService, I am going to assume that you want to have some background service (as a hosted service) within your ASP.NET Core application that is able to perform background tasks. And now you want to trigger such a task through a controller or Razor page action and have it executed in the background?

A common pattern for this is to have some central storage that keeps track of the tasks which both the background service and the web application can access. A simple way to do this is to make it a (thread-safe) singleton service that both sides can access.

The docs actually show a simple example using a BackgroundTaskQueue which is exactly that shared service/state. If you have a worker for a specific kind of job though, you could also implement it like this:

```<code>public class JobQueue<T>
{
    private readonly ConcurrentQueue<T> _jobs = new ConcurrentQueue<T>();
    private readonly SemaphoreSlim _signal = new SemaphoreSlim(0);

    public void Enqueue(T job)
    {
        _jobs.Enqueue(job);
        _signal.Release();
    }

    public async Task<T> DequeueAsync(CancellationToken cancellationToken = default)
    {
        await _signal.WaitAsync(cancellationToken);
        _jobs.TryDequeue(out var job);
        return job;
    }
}
</code>```

You can then register an implementation of this with the service collection along with a hosted background service that works on this queue:

```<code>services.AddSingleton<JobQueue<MyJob>>();
services.AddHostedService<MyJobBackgroundService>();
</code>```

The implementation of that hosted service could then look like this:

```<code>public class MyJobBackgroundService : BackgroundService
{
    private readonly ILogger<MyJobBackgroundService> _logger;
    private readonly JobQueue<MyJob> _queue;

    public MyJobBackgroundService(ILogger<MyJobBackgroundService> logger, JobQueue<MyJob> queue)
    {
        _logger = logger;
        _queue = queue;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var job = await _queue.DequeueAsync(stoppingToken);

            // do stuff
            _logger.LogInformation("Working on job {JobId}", job.Id);
            await Task.Delay(2000);
        }
    }
}
</code>```

In a controller action or a Razor page model, you then just need to inject the JobQueue<MyJob> and then call Enqueue on it to add a job to the list. Once the background service is ready to process it, it will then work on it.

Finally note that the queue is obviously in-memory, so if your application shuts down, the list of yet-to-do jobs is also gone. If you need, you could also persist this information within a database of course and set up the queue from the database.

Body:
Since this is probably a follow-up from your previous question about IHostedService, I am going to assume that you want to have some background service (as a hosted service) within your ASP.NET Core application that is able to perform background tasks. And now you want to trigger such a task through a controller or Razor page action and have it executed in the background?

A common pattern for this is to have some central storage that keeps track of the tasks which both the background service and the web application can access. A simple way to do this is to make it a (thread-safe) singleton service that both sides can access.

The docs actually show a simple example using a BackgroundTaskQueue which is exactly that shared service/state. If you have a worker for a specific kind of job though, you could also implement it like this:

public class JobQueue<T>
{
    private readonly ConcurrentQueue<T> _jobs = new ConcurrentQueue<T>();
    private readonly SemaphoreSlim _signal = new SemaphoreSlim(0);

    public void Enqueue(T job)
    {
        _jobs.Enqueue(job);
        _signal.Release();
    }

    public async Task<T> DequeueAsync(CancellationToken cancellationToken = default)
    {
        await _signal.WaitAsync(cancellationToken);
        _jobs.TryDequeue(out var job);
        return job;
    }
}

You can then register an implementation of this with the service collection along with a hosted background service that works on this queue:

services.AddSingleton<JobQueue<MyJob>>();
services.AddHostedService<MyJobBackgroundService>();

The implementation of that hosted service could then look like this:

public class MyJobBackgroundService : BackgroundService
{
    private readonly ILogger<MyJobBackgroundService> _logger;
    private readonly JobQueue<MyJob> _queue;

    public MyJobBackgroundService(ILogger<MyJobBackgroundService> logger, JobQueue<MyJob> queue)
    {
        _logger = logger;
        _queue = queue;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var job = await _queue.DequeueAsync(stoppingToken);

            // do stuff
            _logger.LogInformation("Working on job {JobId}", job.Id);
            await Task.Delay(2000);
        }
    }
}

In a controller action or a Razor page model, you then just need to inject the JobQueue<MyJob> and then call Enqueue on it to add a job to the list. Once the background service is ready to process it, it will then work on it.

Finally note that the queue is obviously in-memory, so if your application shuts down, the list of yet-to-do jobs is also gone. If you need, you could also persist this information within a database of course and set up the queue from the database.


问:
Why is more memory allocated than expected?
I'm playing around with BenchmarkDotNet and its MemoryDiagnoser feature.

Considering the following benchmark:

```<code>[Benchmark]
public void Dummy()
{
   var buffer = new byte[1];
}
</code>```

I expect it to allocate exactly 1 byte.

But the benchmark result shows that a total of 32 bytes were allocated. How come? I find this quite misleading.

```<code>| Method |     Mean |     Error |    StdDev |   Median | Ratio | Rank |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|------- |---------:|----------:|----------:|---------:|------:|-----:|-------:|------:|------:|----------:|
|  Dummy | 4.486 ns | 0.1762 ns | 0.5196 ns | 4.650 ns |  1.00 |    1 | 0.0038 |     - |     - |      32 B |

                                                                                why not 1 byte? ^^^^
</code>```

答:
I suspect you are on “/platform:x64”. A byte array will take up space of "24byte + length" as each of its elements are of byte. Moreover on x64 all sizes are rounded up to the nearest 8 bytes.

Here is how you can measure the size.

```<code>private void TestMemory(){
    long before = GC.GetTotalMemory(true);
    // Allocation code
    long after = GC.GetTotalMemory(true);
    double diff = after – before;
    Console.WriteLine(“Per object: “ + diff / size);
    // Stop the GC from messing up our measurements
    GC.KeepAlive(array);
}
</code>```

As to your question, why? As mentioned in the comments, it is the implementation details of this high-level language.

※Because of alignment of memory← As mentioned in my answer

※Also arrays include some metadata, like their size to ensure you don't index out into random memory. ← This might be related to first star

Body:
I'm playing around with BenchmarkDotNet and its MemoryDiagnoser feature.

Considering the following benchmark:

[Benchmark]
public void Dummy()
{
   var buffer = new byte[1];
}

I expect it to allocate exactly 1 byte.

But the benchmark result shows that a total of 32 bytes were allocated. How come? I find this quite misleading.

| Method |     Mean |     Error |    StdDev |   Median | Ratio | Rank |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|------- |---------:|----------:|----------:|---------:|------:|-----:|-------:|------:|------:|----------:|
|  Dummy | 4.486 ns | 0.1762 ns | 0.5196 ns | 4.650 ns |  1.00 |    1 | 0.0038 |     - |     - |      32 B |

                                                                                why not 1 byte? ^^^^

Body:
I suspect you are on “/platform:x64”. A byte array will take up space of "24byte + length" as each of its elements are of byte. Moreover on x64 all sizes are rounded up to the nearest 8 bytes.

Here is how you can measure the size.

private void TestMemory(){
    long before = GC.GetTotalMemory(true);
    // Allocation code
    long after = GC.GetTotalMemory(true);
    double diff = after – before;
    Console.WriteLine(“Per object: “ + diff / size);
    // Stop the GC from messing up our measurements
    GC.KeepAlive(array);
}

As to your question, why? As mentioned in the comments, it is the implementation details of this high-level language.

※Because of alignment of memory← As mentioned in my answer

※Also arrays include some metadata, like their size to ensure you don't index out into random memory. ← This might be related to first star