问:
How to get an document in a table and join it with a second table mogodb, Getting Error : .find(...).aggregate is not a function
I am working with mongodb and I have two tables, a users and a books one. I want to get an specific user and join it with the second table. Example:

Document Example of table users:

```<code>var user = {
 _id: ObjectId('asduiasbdiuasbduiasbduib'),
 username: 'raos',
 last_login: '12-01-2020'
}
</code>```

Document Example of table book:

```<code>var book = {
  _id: ObjectId('jkngsjilsdhioh'),
  bookTitle: 'Lost in space',
  available: false,
  rented_by:  'asduiasbdiuasbduiasbduib'
}
</code>```

I tried the next thing:

```<code>F.db.collection('users').find({_id: 'asduiasbdiuasbduiasbduib'}).aggregate([
    {
        $lookup:{
            from: 'books',
            localField: '_id',
            foreignField: 'rented_by',
            as: 'books'

        }
    }
]).toArray((err, res) => {
    console.log(res);
});
// Error showed:
//F.db.collection(...).find(...).aggregate is not a function
</code>```

答:
```<code>function something(userId) {
  return new Promise((resolve, reject) => {
    var aggregate = user.aggregate();
    aggregate
      .match({
        _id: ObjectId(userId)
      })
      .lookup({
        localField: '_id',
        from: 'books',
        foreignField: 'rented_by',
        as: 'book'
      })
    aggregate.exec(function (err, books) {
      if (err) return reject(err);
      return resolve(books);
    });
  });
}
</code>```

Does it solved your problem?

Body:
I am working with mongodb and I have two tables, a users and a books one. I want to get an specific user and join it with the second table. Example:

Document Example of table users:

var user = {
 _id: ObjectId('asduiasbdiuasbduiasbduib'),
 username: 'raos',
 last_login: '12-01-2020'
}

Document Example of table book:

var book = {
  _id: ObjectId('jkngsjilsdhioh'),
  bookTitle: 'Lost in space',
  available: false,
  rented_by:  'asduiasbdiuasbduiasbduib'
}

I tried the next thing:

F.db.collection('users').find({_id: 'asduiasbdiuasbduiasbduib'}).aggregate([
    {
        $lookup:{
            from: 'books',
            localField: '_id',
            foreignField: 'rented_by',
            as: 'books'

        }
    }
]).toArray((err, res) => {
    console.log(res);
});
// Error showed:
//F.db.collection(...).find(...).aggregate is not a function

Body:
function something(userId) {
  return new Promise((resolve, reject) => {
    var aggregate = user.aggregate();
    aggregate
      .match({
        _id: ObjectId(userId)
      })
      .lookup({
        localField: '_id',
        from: 'books',
        foreignField: 'rented_by',
        as: 'book'
      })
    aggregate.exec(function (err, books) {
      if (err) return reject(err);
      return resolve(books);
    });
  });
}

Does it solved your problem?


来源: stackexchange

问:
Making a combo box list in the spreadsheet (not in the userform)
I am trying to add a list to my Combobox that's on a spreadsheet. I tried using the code below but nothing happens. I rather not go on properties and fill from what sheet, instead use vba code, just in case there are changes.</p>

```<code>
Sub DropDown1_Change()
    Dim ws As Worksheet
    Set ws = Sheets("Hours")

    ActiveSheet.Shapes("Drop Down 1").List = ws.Range("F2:F6").Text
End Sub

</code>```

答:
Not really sure what your object actually is since combobox names use no spaces.

Maybe your are confusing data validation drop downs with acombobox.
But if it's a combobox and you name it without spaces, this will work.

```<code>Sub add_items()
Set ws = ActiveSheet
        With ws.Drop_Down_1
            For i = 2 To 6
                .AddItem ws.Range("F" & i).Value
            Next i
        End With
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to add a list to my Combobox that's on a spreadsheet. I tried using the code below but nothing happens. I rather not go on properties and fill from what sheet, instead use vba code, just in case there are changes.

Sub DropDown1_Change()
    Dim ws As Worksheet
    Set ws = Sheets("Hours")

    ActiveSheet.Shapes("Drop Down 1").List = ws.Range("F2:F6").Text
End Sub

Body:
Not really sure what your object actually is since combobox names use no spaces.

Maybe your are confusing data validation drop downs with acombobox.
But if it's a combobox and you name it without spaces, this will work.

Sub add_items()
Set ws = ActiveSheet
        With ws.Drop_Down_1
            For i = 2 To 6
                .AddItem ws.Range("F" & i).Value
            Next i
        End With
End Sub


问:
Copy and retain previous output for backup of transformed json data
I have a perl script that transforms json data to perl and saves output in files called teams.txt, backyard, and also a file called backup.txt, where the output of teams.txt is copied from. The following are two snippets from the script/the part of it that writes the data to the text files:

```<code>my %manager_to_directs;
my %user_to_manager;
my @users;
my $url = "https://xxxxxxxxxxxxxx.com/api/v1/reports/active/week";

my $useragent = LWP::UserAgent->new();
my $response = $useragent->get(($url));
if ($response->code !~ "200" || $response->code !~ "204" ){

while ($url && $url ne "Null") {
  my $data = fetch_json($url);
  last if !defined $data;

  $url  = $data->{next};
.
.
.

# write backyard.txt
open my $backyard_fh, ">", "backyard.txt";
foreach my $user (sort keys %user_to_management_chain) {
  my $chain = join ',', @{$user_to_management_chain{$user}};
  print $backyard_fh "$user:$chain\n";
}
close $backyard_fh;

# write teams.txt
open my $team_fh, ">", "teams.txt";
foreach my $user (sort @users) {
  my $followers = $manager_to_followers{$user};
  my $followers_joined = $followers ? join (',', sort @$followers) : "";
  print $team_fh "$user:$followers_joined\n";
}
close $team_fh;

# write backup.txt, backup for teams.txt
open my $backup_fh, ">", "backup.txt";
copy("teams.txt", "backup.txt")
    or die ("Can't copy teams.txt \n");
close $backup_fh;
</code>```

This works almost exactly how I want it to, but now I've been testing with a negative scenario, where the .json url provided in the script is false/nonexistent, and I have to make sure that not another teams.txt file is created and the backup.txt file is still retained from the last execution.

I tested by replacing

```<code>my $url = "https://xxxxxxxxxxxxxx.com/api/v1/reports/active/week";
</code>```

with

```<code>my $url = "https://fakeUrl.com/api/v1/reports/active/week";
</code>```

And in this scenario, 404 would be passed and the program is supposed to fail. With this test, I noticed that the the contents of teams.txt and backyard.txt get wiped, but the backup.txt file gets wiped too...and that's not good.

I'm fine with teams.txt and backyard.txt being overwritten per each run of the script, but I need the backup.txt file to be retained no matter what, unless the program runs successfully and there's new content from teams.txt to be copied over to backup.txt.

Any help I can get is highly appreciated!

答:
Following code snippets taken almost directly from documentation for modules.

May be you should try this approach.

```<code>use strict;
use warnings;
use feature 'say';

use LWP::UserAgent ();

my $url = 'https://metacpan.org/pod/HTTP::Tiny';
   $url = 'https://fakeUrl.com/api/v1/reports/active/week';
my $ua = LWP::UserAgent->new(timeout => 10);
$ua->env_proxy;

my $response = $ua->get($url);
my $data;

if ($response->is_success) {
    $data = $response->decoded_content;
}
else {
    die $response->status_line;
}

# Process further data
say $data;
</code>```

Output

```<code>500 Can't connect to fakeUrl.com:443 (Bad file descriptor) at C:\....\http_lwp.pl line 19.
</code>```

```<code>use strict;
use warnings;
use feature 'say';

use HTTP::Tiny;

my $url = 'https://metacpan.org/pod/HTTP::Tiny';
   $url = 'https://fakeUrl.com/api/v1/reports/active/week';
my $data;

my $response = HTTP::Tiny->new->get($url);

if( $response->{success} ) {
    $data = $response->{content};
} else {
    say "$response->{status} $response->{reason}";
    exit 1;
}

# Process further data
say $data;
</code>```

Output

```<code>403 Forbidden
</code>```

Body:
I have a perl script that transforms json data to perl and saves output in files called teams.txt, backyard, and also a file called backup.txt, where the output of teams.txt is copied from. The following are two snippets from the script/the part of it that writes the data to the text files:

my %manager_to_directs;
my %user_to_manager;
my @users;
my $url = "https://xxxxxxxxxxxxxx.com/api/v1/reports/active/week";

my $useragent = LWP::UserAgent->new();
my $response = $useragent->get(($url));
if ($response->code !~ "200" || $response->code !~ "204" ){

while ($url && $url ne "Null") {
  my $data = fetch_json($url);
  last if !defined $data;

  $url  = $data->{next};
.
.
.

# write backyard.txt
open my $backyard_fh, ">", "backyard.txt";
foreach my $user (sort keys %user_to_management_chain) {
  my $chain = join ',', @{$user_to_management_chain{$user}};
  print $backyard_fh "$user:$chain\n";
}
close $backyard_fh;

# write teams.txt
open my $team_fh, ">", "teams.txt";
foreach my $user (sort @users) {
  my $followers = $manager_to_followers{$user};
  my $followers_joined = $followers ? join (',', sort @$followers) : "";
  print $team_fh "$user:$followers_joined\n";
}
close $team_fh;

# write backup.txt, backup for teams.txt
open my $backup_fh, ">", "backup.txt";
copy("teams.txt", "backup.txt")
    or die ("Can't copy teams.txt \n");
close $backup_fh;

This works almost exactly how I want it to, but now I've been testing with a negative scenario, where the .json url provided in the script is false/nonexistent, and I have to make sure that not another teams.txt file is created and the backup.txt file is still retained from the last execution.

I tested by replacing

my $url = "https://xxxxxxxxxxxxxx.com/api/v1/reports/active/week";

with

my $url = "https://fakeUrl.com/api/v1/reports/active/week";

And in this scenario, 404 would be passed and the program is supposed to fail. With this test, I noticed that the the contents of teams.txt and backyard.txt get wiped, but the backup.txt file gets wiped too...and that's not good.

I'm fine with teams.txt and backyard.txt being overwritten per each run of the script, but I need the backup.txt file to be retained no matter what, unless the program runs successfully and there's new content from teams.txt to be copied over to backup.txt.

Any help I can get is highly appreciated!

Body:
Following code snippets taken almost directly from documentation for modules.

May be you should try this approach.

use strict;
use warnings;
use feature 'say';

use LWP::UserAgent ();

my $url = 'https://metacpan.org/pod/HTTP::Tiny';
   $url = 'https://fakeUrl.com/api/v1/reports/active/week';
my $ua = LWP::UserAgent->new(timeout => 10);
$ua->env_proxy;

my $response = $ua->get($url);
my $data;

if ($response->is_success) {
    $data = $response->decoded_content;
}
else {
    die $response->status_line;
}

# Process further data
say $data;

Output

500 Can't connect to fakeUrl.com:443 (Bad file descriptor) at C:\....\http_lwp.pl line 19.

use strict;
use warnings;
use feature 'say';

use HTTP::Tiny;

my $url = 'https://metacpan.org/pod/HTTP::Tiny';
   $url = 'https://fakeUrl.com/api/v1/reports/active/week';
my $data;

my $response = HTTP::Tiny->new->get($url);

if( $response->{success} ) {
    $data = $response->{content};
} else {
    say "$response->{status} $response->{reason}";
    exit 1;
}

# Process further data
say $data;

Output

403 Forbidden


问:
Python read csv file columns into lists, ignoring headers
I have a file 'data.csv' that looks something like

```<code>ColA, ColB, ColC
1,2,3
4,5,6
7,8,9
</code>```

I want to open and read the file columns into lists, with the 1st entry of that list omitted, e.g.

```<code>dataA = [1,4,7]
dataB = [2,5,8]
dataC = [3,6,9]
</code>```

In reality there are more than 3 columns and the lists are very long, this is just an example of the format. I've tried:

```<code>csv_file = open('data.csv','rb')
csv_array = []

for row in csv.reader(csv_file, delimiter=','):
    csv_array.append(row)
</code>```

Where I would then allocate each index of csv_array to a list, e.g.

```<code>dataA = [int(i) for i in csv_array[0]]
</code>```

But I'm getting errors:

```<code>_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
</code>```

Also it feels like a very long winded way of just saving data to a few lists...

Thanks!

edit:

Here is how I solved it:

```<code>import pandas as pd

df = pd.read_csv('data.csv', names = ['ColA','ColB','ColC']

dataA = map(int,(df.ColA.tolist())[1:3])
</code>```

and repeat for the rest of the columns.

答:
use csv.DictReader() to select specific columns

```<code>dataA = []
dataB = []
with open('data.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter=',')
    for row in csv_reader:
        dataA.append(row['ColA'])
        dataB.append(row['ColB'])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a file 'data.csv' that looks something like

ColA, ColB, ColC
1,2,3
4,5,6
7,8,9

I want to open and read the file columns into lists, with the 1st entry of that list omitted, e.g.

dataA = [1,4,7]
dataB = [2,5,8]
dataC = [3,6,9]

In reality there are more than 3 columns and the lists are very long, this is just an example of the format. I've tried:

csv_file = open('data.csv','rb')
csv_array = []

for row in csv.reader(csv_file, delimiter=','):
    csv_array.append(row)

Where I would then allocate each index of csv_array to a list, e.g.

dataA = [int(i) for i in csv_array[0]]

But I'm getting errors:

_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

Also it feels like a very long winded way of just saving data to a few lists...

Thanks!

edit:

Here is how I solved it:

import pandas as pd

df = pd.read_csv('data.csv', names = ['ColA','ColB','ColC']

dataA = map(int,(df.ColA.tolist())[1:3])

and repeat for the rest of the columns.

Body:
use csv.DictReader() to select specific columns

dataA = []
dataB = []
with open('data.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter=',')
    for row in csv_reader:
        dataA.append(row['ColA'])
        dataB.append(row['ColB'])


问:
Can't assign multiple HTML elements in the .css() function
I have 4 divs filter1, filter2, filter3, filter4 and I have an anchor tag inside of them and an image, I want to make it so that when you hover on a filter div, the anchor tag gets the other color, the only problem is that I cannot change the color via JavaScript, which is what I am trying to achieve.

I want to change the color of the anchor when I hover (or in JS mouseOver) any of the filter div.

The only problem is I cannot define multiple HTML tags in the .css function in JavaScript.

I am trying to achieve this:

$(".filter1").mouseover(function () {
  $(".filter , li , a").css("color", "pink");
});
```

<p>The only problem is, now every .filter function, every <code>li</code> tag and every <code>anchor</code> tag in my HTML documents get color pink when I hover over any of these.</p>

<p>What I have right now:</p>

<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
  $(".filter1").mouseover(function () {
    $(".filter ").css("color", "pink");
  });
  $(".filter1").mouseout(function () {
    $(".filter li a").css("color", "#FFFF");
  });

  //also filter2, filter3, filter4 etc

});
</code>```

How can I resolve this?

答:
You can try this: Put the mouseover in the div and assign it a number </p>

```<code><div onmousover='colorChange(1)' onmouseout='colorRevert(1)' class='filter1'>
</code>```

<p>then in the jquery : </p>

```<code>function colorChange(i){
     $(".filter" + i).css("color", "pink");
}
function colorRevert(i) {
     $(".filter" + i + " li a").css("color", "#FFFF");
}
</code>```

Body:
I have 4 divs filter1, filter2, filter3, filter4 and I have an anchor tag inside of them and an image, I want to make it so that when you hover on a filter div, the anchor tag gets the other color, the only problem is that I cannot change the color via JavaScript, which is what I am trying to achieve.

I want to change the color of the anchor when I hover (or in JS mouseOver) any of the filter div.

The only problem is I cannot define multiple HTML tags in the .css function in JavaScript.

I am trying to achieve this:

$(".filter1").mouseover(function () {
  $(".filter , li , a").css("color", "pink");
});

The only problem is, now every .filter function, every li tag and every anchor tag in my HTML documents get color pink when I hover over any of these.

What I have right now:

$(document).ready(function () {
  $(".filter1").mouseover(function () {
    $(".filter ").css("color", "pink");
  });
  $(".filter1").mouseout(function () {
    $(".filter li a").css("color", "#FFFF");
  });

  //also filter2, filter3, filter4 etc

});

How can I resolve this?

Body:
You can try this: Put the mouseover in the div and assign it a number

<div onmousover='colorChange(1)' onmouseout='colorRevert(1)' class='filter1'>

then in the jquery :

function colorChange(i){
     $(".filter" + i).css("color", "pink");
}
function colorRevert(i) {
     $(".filter" + i + " li a").css("color", "#FFFF");
}


问:
How do I get diffs of all the files in a pending Perforce changelist?
I want to get diffs on files in a specific pending changelist.  I wish I could do this:

```<code>p4 diff -c 999
</code>```

Can someone help me string together some csh magic to make this happen?

Maybe take the output of p4 opened -c 999 and piping it to p4 diff?

答:
For Unshelved Changes( Changes still not in depot)

```<code>p4 opened -c 999 | awk 'BEGIN { FS = "#" } // { print "p4 diff " $1 }' | bash
</code>```

For Shelved Changes( Changes that in depot ( p4 shelve -c 999)

```<code>p4 describe -S -du3 -O 999
</code>```

Body:
I want to get diffs on files in a specific pending changelist.  I wish I could do this:

p4 diff -c 999

Can someone help me string together some csh magic to make this happen?

Maybe take the output of p4 opened -c 999 and piping it to p4 diff?

Body:
For Unshelved Changes( Changes still not in depot)

p4 opened -c 999 | awk 'BEGIN { FS = "#" } // { print "p4 diff " $1 }' | bash

For Shelved Changes( Changes that in depot ( p4 shelve -c 999)

p4 describe -S -du3 -O 999


问:
How do I unit test a C# function when that function must write to stdout
I have a function whose specification calls for it to write to stdout.  When I test, stdout is MIA and I can't find it.  I need to catch it so I can assert expected responses.  The method will be called by a command pipeline.

In addition, I will be writing some pipeline functions:  ==stdin==> method ==stdout==>.  That means my unit tests need to push test data into stdin.

I am planning the test scenario before writing the methods and not finding a lot of recent information.  I am hoping that MSTest might have some helper methods for this.  If not, I could use some guidance regarding how I might go about writing my own.

答:
I would suggest passing in a TextReader and a TextWriter, maybe as optional parameters. You can then read from the reader and write to the writer. Then either the caller passes in Console.Out and Console.In, or you can do it in the method:

public void Foo(TextReader reader = null, TextWriter writer = null)
{
    reader = reader ?? Console.In;
    writer = writer ?? Console.Out;
    // Read and write
}
```

(Or use a parameterless overload that calls an overload with two required parameters.)

In your unit tests, use a StringReader and a StringWriter.

If you can required the caller to pass in the reader and the writer, it would allow you to avoid coupling your code tightly to the console, leading to generally cleaner code - I can imagine a whole series of methods all of which accept a reader/writer (or use fields for them) so that only the very top level code "knows" that it's dealing with the console.

Body:
I would suggest passing in a TextReader and a TextWriter, maybe as optional parameters. You can then read from the reader and write to the writer. Then either the caller passes in Console.Out and Console.In, or you can do it in the method:

public void Foo(TextReader reader = null, TextWriter writer = null)
{
    reader = reader ?? Console.In;
    writer = writer ?? Console.Out;
    // Read and write
}

(Or use a parameterless overload that calls an overload with two required parameters.)

In your unit tests, use a StringReader and a StringWriter.

If you can required the caller to pass in the reader and the writer, it would allow you to avoid coupling your code tightly to the console, leading to generally cleaner code - I can imagine a whole series of methods all of which accept a reader/writer (or use fields for them) so that only the very top level code "knows" that it's dealing with the console.


问:
Change src in HTML5 video tag in .net
Im wondering if there is a way to easily change the src in the video tag in HTML5 from codebehind?

my solution now is to use different WebUserControl's and place them in a PlaceHolder when their button is clicked, but this fast leads to a lot of control's.

There has to be a better way.

maybe like placing a label, bind of some sort in the src

答:
Any tag can have attributes added to it in code-behind as long as you add a runat="server", so yes, there is.

in .aspx page:

```<code><video id="videoTag" runat="server" />
</code>```

code-behind:

```<code>videoTag.Attributes["src"] = "bob";
</code>```

Alternatively you can write your own webcontrol. This involves more work and understanding of asp.net, but will be worth it if you're going to use this a lot.

And if you're using ASP.Net MVC, they've already released support for HTML5 in ASP.Net MVC 3 as I understand it.

Title: Change src in HTML5 video tag in .net

Body:
Any tag can have attributes added to it in code-behind as long as you add a runat="server", so yes, there is.

in .aspx page:

<video id="videoTag" runat="server" />

code-behind:

videoTag.Attributes["src"] = "bob";

Alternatively you can write your own webcontrol. This involves more work and understanding of asp.net, but will be worth it if you're going to use this a lot.

And if you're using ASP.Net MVC, they've already released support for HTML5 in ASP.Net MVC 3 as I understand it.


问:
To call a function from a class, does Python iterate through every function the class has until it finds the function to call?
For example, let's say I have this:

class RandomFunctions:
    def function_1:
        print('function 1 calling')

    def function_2:
        print('function_2 activated')

    def function_3:
        print('function_3 activated')

    def function_4:
        print('function_4 activated')

RandomFunctions().function_4()
```

To call function_4, does Python iterate through every other function in the class, checking if it's the right function, or directly calls it?

答:
function_4 is a class attribute whose name is stored in an object that implements the mapping protocol. Lookup is done by direct indexing of that object. There is no iteration involved, and the order in which the functions are defined is largely irrelevant.

```<code>>>> type(RandomeFunctions.__dict__)
<class 'mappingproxy'>
>>> RandomFunctions.__dict__['function_4'] is RandomFunctions.function_4
True
</code>```

Body:
For example, let's say I have this:

class RandomFunctions:
    def function_1:
        print('function 1 calling')

    def function_2:
        print('function_2 activated')

    def function_3:
        print('function_3 activated')

    def function_4:
        print('function_4 activated')

RandomFunctions().function_4()

To call function_4, does Python iterate through every other function in the class, checking if it's the right function, or directly calls it?

Body:
function_4 is a class attribute whose name is stored in an object that implements the mapping protocol. Lookup is done by direct indexing of that object. There is no iteration involved, and the order in which the functions are defined is largely irrelevant.

>>> type(RandomeFunctions.__dict__)
<class 'mappingproxy'>
>>> RandomFunctions.__dict__['function_4'] is RandomFunctions.function_4
True


问:
Android=Count clicks in Kotlin: How can I count number clicks Kotlin?
I want to show interstitial ads on clicking the button for specific number of times. How can I achieve it in kotlin?
Help me please
my MainActivity.java</p>
```<code>class MainActivity : Activity() {

private lateinit var mInterstitialAd: InterstitialAd

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
MobileAds.initialize(this) {}
    mInterstitialAd = InterstitialAd(this)
    mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
mInterstitialAd.loadAd(AdRequest.Builder().build())
mMyButton.setOnClickListener {
if (mInterstitialAd.isLoaded) {
    mInterstitialAd.show()
} else {
    Log.d("TAG", "The interstitial wasn't loaded yet.")
}
 }
  }
</code>```

答:
Here is the example code that can get you desired behaviour</p>

```<code>class MainActivity : AppCompatActivity() {

  var clickCount = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener {
           clickCount++
           if (clickCount >= 5 && interstitialAd.isLoaded()) {
           clickCount = 0 // reset count
           interstitialAd.show()
        }
   }
}
</code>```

Body:
I want to show interstitial ads on clicking the button for specific number of times. How can I achieve it in kotlin?
Help me please
my MainActivity.java

class MainActivity : Activity() {

private lateinit var mInterstitialAd: InterstitialAd

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
MobileAds.initialize(this) {}
    mInterstitialAd = InterstitialAd(this)
    mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
mInterstitialAd.loadAd(AdRequest.Builder().build())
mMyButton.setOnClickListener {
if (mInterstitialAd.isLoaded) {
    mInterstitialAd.show()
} else {
    Log.d("TAG", "The interstitial wasn't loaded yet.")
}
 }
  }

Body:
Here is the example code that can get you desired behaviour

class MainActivity : AppCompatActivity() {

  var clickCount = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener {
           clickCount++
           if (clickCount >= 5 && interstitialAd.isLoaded()) {
           clickCount = 0 // reset count
           interstitialAd.show()
        }
   }
}


问:
set of n objects, and show k-element subsets in python
Suppose you have a set of n objects, and you want to list its k-element subsets (that is, its
subsets with exactly m elements) solved by Recursive functions without using list(itertools.combinations)
for example k_subsets({1,2,3},2 )
 show the

```<code>[{1, 2}, {1, 3}, {2, 3}]
</code>```

答:
This will be the code of combination using recursion, and this will give you all the subsets of given list and the subsets of desired length.

```<code>l1 = [1, 2, 3]
s = 2
unique = []
def combination(set):
    if set == []:
        return [[]]

    sub = combination(set[1:])
    # This will give you all the subsets of given list and This is also the return variable of the function.
    all_combination = (sub + [[set[0]] + x for x in sub])
    ########################################################
    # This for loop will give you a subsets of desire length.
    for i in range(len(all_combination)):
        if int(len(all_combination[i])) == s and all_combination[i] not in unique:
            unique.append(all_combination[i])
    #########################################################
    return all_combination

print(combination(l1))
print(unique)
</code>```

Body:
Suppose you have a set of n objects, and you want to list its k-element subsets (that is, its
subsets with exactly m elements) solved by Recursive functions without using list(itertools.combinations)
for example k_subsets({1,2,3},2 )
 show the

[{1, 2}, {1, 3}, {2, 3}]

Body:
This will be the code of combination using recursion, and this will give you all the subsets of given list and the subsets of desired length.

l1 = [1, 2, 3]
s = 2
unique = []
def combination(set):
    if set == []:
        return [[]]

    sub = combination(set[1:])
    # This will give you all the subsets of given list and This is also the return variable of the function.
    all_combination = (sub + [[set[0]] + x for x in sub])
    ########################################################
    # This for loop will give you a subsets of desire length.
    for i in range(len(all_combination)):
        if int(len(all_combination[i])) == s and all_combination[i] not in unique:
            unique.append(all_combination[i])
    #########################################################
    return all_combination

print(combination(l1))
print(unique)


问:
Asp.Net MVC Form[GET]. Correct action url
I've got search form, which contains checkboxlist which is binded to my model. So when I set GET method to form I got long url:
(I even have exception:

```<code>The length of the query string for this request exceeds the configured maxQueryStringLength value.)
</code>```

it's expecting, [0].IsSelected=false&[0].Id=6&[1].IsSelected=false...

But I would like url like this

www.domain.com/Action/Comma-separated-selected-idx

for example:

www.domain.com/Search/1,6,7

How can I fix,edit form get action? Thanks

答: agreed, POST or JS are your best options, I'd opt for a POST. </p>

Body:
I've got search form, which contains checkboxlist which is binded to my model. So when I set GET method to form I got long url:
(I even have exception:

The length of the query string for this request exceeds the configured maxQueryStringLength value.)

it's expecting, [0].IsSelected=false&[0].Id=6&[1].IsSelected=false...

But I would like url like this

www.domain.com/Action/Comma-separated-selected-idx

for example:

www.domain.com/Search/1,6,7

How can I fix,edit form get action? Thanks


问:
Coin Change problem with Greedy Approach in Python
I am trying to implement greedy approach in coin change problem, but need to reduce the time complexity because the compiler won't accept my code, and since I am unable to verify I don't even know if my code is actually correct or not. The function should return the total number of notes needed to make the change. If change cannot be obtained for the given amount, then return -1. Return 1 if the amount is equal to one of the currencies available in the denomination list.</p>

```<code>def make_change(denomination_list, amount):

    denomination_list.sort()
    n = len(denomination_list)
    i = n - 1
    ans = 0
    x = 0
    while i>= 0 :
        while denomination_list[i]<= amount:
            ans = +1
            amount -= denomination_list[i]
            i -= 1
        if amount == 0:
            x = 1
        elif amount<0:
            x = -1
    return x

    amount= 20
    denomination_list = [1,15,10]
    print(make_change(denomination_list, amount))
</code>```

答:
You want to minimize the use of list indexes if possible, and iterate over the list itself. Here is a code that works:

```<code># Pre-process denomination list before function, sorting in decreasing order
denomination_list = [1,15,10]
denomination_list.sort(reverse = True)
# Ensure ones are available for change (or infinite loop may result)
if denomination_list[-1] != 1:
    denomination_list.append(1)

def make_change(denomination_list, amount):
    change = []
    # Iterate through coins
    for coin in denomination_list:
        # Add current coin as long as not exceeding ampoiunt
        while amount:
            if coin <= amount:
                change.append(coin)
                amount -= coin
            else:
                break
    return change

amount= 43
print(make_change(denomination_list, amount))
</code>```

This will work for non-integer values of amount and will list the change for a rounded down amount.

Body:
I am trying to implement greedy approach in coin change problem, but need to reduce the time complexity because the compiler won't accept my code, and since I am unable to verify I don't even know if my code is actually correct or not. The function should return the total number of notes needed to make the change. If change cannot be obtained for the given amount, then return -1. Return 1 if the amount is equal to one of the currencies available in the denomination list.

def make_change(denomination_list, amount):

    denomination_list.sort()
    n = len(denomination_list)
    i = n - 1
    ans = 0
    x = 0
    while i>= 0 :
        while denomination_list[i]<= amount:
            ans = +1
            amount -= denomination_list[i]
            i -= 1
        if amount == 0:
            x = 1
        elif amount<0:
            x = -1
    return x

    amount= 20
    denomination_list = [1,15,10]
    print(make_change(denomination_list, amount))

Body:
You want to minimize the use of list indexes if possible, and iterate over the list itself. Here is a code that works:

# Pre-process denomination list before function, sorting in decreasing order
denomination_list = [1,15,10]
denomination_list.sort(reverse = True)
# Ensure ones are available for change (or infinite loop may result)
if denomination_list[-1] != 1:
    denomination_list.append(1)

def make_change(denomination_list, amount):
    change = []
    # Iterate through coins
    for coin in denomination_list:
        # Add current coin as long as not exceeding ampoiunt
        while amount:
            if coin <= amount:
                change.append(coin)
                amount -= coin
            else:
                break
    return change

amount= 43
print(make_change(denomination_list, amount))

This will work for non-integer values of amount and will list the change for a rounded down amount.


问:
Activex control goes to upper left corner when reopen excel sheet
I have a datetime picker control on the excel sheet that keeps on moving to the upper left corner when I reopen the excel sheet. How do I fix it to the cell? </p>

答:
I had the same issue and noticed that when I scroll down and back up, for some reason it corrects the issue. So I added a macros to scroll down and then back up as a workbook open event. Here's what I added to the "Thisworkbook" object:

```<code>Private Sub Workbook_Open()
Worksheets("Sheet1").Activate
ActiveWindow.LargeScroll Down:=1
ActiveWindow.LargeScroll Up:=1
End Sub
</code>```

*Note: Be sure to add to the "Thisworkbook" object (instead of modules or other objects).

Body:
I had the same issue and noticed that when I scroll down and back up, for some reason it corrects the issue. So I added a macros to scroll down and then back up as a workbook open event. Here's what I added to the "Thisworkbook" object:

Private Sub Workbook_Open()
Worksheets("Sheet1").Activate
ActiveWindow.LargeScroll Down:=1
ActiveWindow.LargeScroll Up:=1
End Sub

*Note: Be sure to add to the "Thisworkbook" object (instead of modules or other objects).


问:
PushNotification VolleyError at first time and 2nd time its working
When I call the PrepareNotificationToAdmin function first time onErrorResponse(VolleyError error) is coming. When again I call this function then only it's getting success. It means 2nd time its working.

Can anyone find out the error.

```<code>
private void PrepareNotificationToAdmin() {

        database.collection("xxxx").document("xxxx").get()
                .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                    @Override
                    public void onSuccess(DocumentSnapshot documentSnapshot) {
                        AdminDeviceToken = documentSnapshot.getString("deviceToken");
                    }
                });

        NOTIFICATION_TITLE = "New Kiranam Registration";
        NOTIFICATION_MESSAGE =  loggedUserId + " - Has registered new kiranam as " + KiranamName;

        JSONObject notification = new JSONObject();
        JSONObject notifcationBody = new JSONObject();
        try {
            notifcationBody.put("title", NOTIFICATION_TITLE);
            notifcationBody.put("message", NOTIFICATION_MESSAGE);

            notification.put("to", AdminDeviceToken);
            notification.put("data", notifcationBody);
        } catch (JSONException e) {
            Log.e(TAG, "onCreate: " + e.getMessage());
        }
        sendNotification(notification);
    }

    private void sendNotification(JSONObject notification) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i(TAG, "onResponse: " + response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        new OneToast(Register.this, "Request error");
                        //Todo: request error on first time only//
                        Log.i(TAG, "onErrorResponse: Didn't work");
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Authorization", serverKey);
                params.put("Content-Type", contentType);
                return params;
            }
        };
        MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
    }
</code>```

答:
Finally, I got a solution for this. The main problem is due to the delay in getting device token from server of Admin. Before this, Notification function is getting processed and result is fail.

Now this issue is resolved.

Body:
When I call the PrepareNotificationToAdmin function first time onErrorResponse(VolleyError error) is coming. When again I call this function then only it's getting success. It means 2nd time its working.

Can anyone find out the error.

private void PrepareNotificationToAdmin() {

        database.collection("xxxx").document("xxxx").get()
                .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                    @Override
                    public void onSuccess(DocumentSnapshot documentSnapshot) {
                        AdminDeviceToken = documentSnapshot.getString("deviceToken");
                    }
                });

        NOTIFICATION_TITLE = "New Kiranam Registration";
        NOTIFICATION_MESSAGE =  loggedUserId + " - Has registered new kiranam as " + KiranamName;

        JSONObject notification = new JSONObject();
        JSONObject notifcationBody = new JSONObject();
        try {
            notifcationBody.put("title", NOTIFICATION_TITLE);
            notifcationBody.put("message", NOTIFICATION_MESSAGE);

            notification.put("to", AdminDeviceToken);
            notification.put("data", notifcationBody);
        } catch (JSONException e) {
            Log.e(TAG, "onCreate: " + e.getMessage());
        }
        sendNotification(notification);
    }

    private void sendNotification(JSONObject notification) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i(TAG, "onResponse: " + response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        new OneToast(Register.this, "Request error");
                        //Todo: request error on first time only//
                        Log.i(TAG, "onErrorResponse: Didn't work");
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Authorization", serverKey);
                params.put("Content-Type", contentType);
                return params;
            }
        };
        MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
    }


问:
Docker Quickstart Terminal: exit status 255
Docker version 1.12.2, build bb80604

When I try to launch docker quickstart terminal, I am getting below error. Can anyone please provide inputs to solve this problem?

```<code>Error checking TLS connection: Something went wrong running an SSH command!
command : ip addr show
err     : exit status 255
output  :

                    ##         .
              ## ## ##        ==
           ## ## ## ## ##    ===
       /"""""""""""""""""\___/ ===
  ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
       \______ o           __/
         \    \         __/
          \____\_______/

Error getting IP address: Something went wrong running an SSH command!
command : ip addr show
err     : exit status 255
output  :
docker is configured to use the default machine with IP
For help getting started, check out the docs at https://docs.docker.com

Start interactive shell
</code>```

答:
This worked for me:

```<code>$ docker-machine rm -y default; docker-machine create -d virtualbox default
</code>```

BUT,
I had to do it twice, because I had the VM running.

Body:
Docker version 1.12.2, build bb80604

When I try to launch docker quickstart terminal, I am getting below error. Can anyone please provide inputs to solve this problem?

Error checking TLS connection: Something went wrong running an SSH command!
command : ip addr show
err     : exit status 255
output  :

                    ##         .
              ## ## ##        ==
           ## ## ## ## ##    ===
       /"""""""""""""""""\___/ ===
  ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
       \______ o           __/
         \    \         __/
          \____\_______/

Error getting IP address: Something went wrong running an SSH command!
command : ip addr show
err     : exit status 255
output  :
docker is configured to use the default machine with IP
For help getting started, check out the docs at https://docs.docker.com

Start interactive shell

Body:
This worked for me:

$ docker-machine rm -y default; docker-machine create -d virtualbox default

BUT,
I had to do it twice, because I had the VM running.


问:
Subtract and Sum Operations On Columns
I have an output like this:

```<code>Volume               c1                     c2
--------------------------------------------------
0                   1000                     0
1-20                 100                    10
20+                   50                    40
</code>```

I get this output by this:

```<code>SELECT
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' as Volume,
sum(ab) as c1,
sum(xy) as c2
FROM
table t
GROUP BY
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+'
</code>```

However, I need to get the output just like below. I am trying to subtract sum of c1 column from sum of c2 column and result must be placed at first row under c2 column just like this:

```<code>Volume                c1                  c2
--------------------------------------------------
0                   1000                **1100**
1-20                 100                  10
20+                   50                  40
</code>```

How can I do this?

Thanks in advance.

答:
You can used below query to get output you required
with CTE table expression you can achieved.

with Cte as(
SELECT
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' as Volume,
sum(ab) as c1,
sum(xy) as c2,
sum(ab)-sum(xy) as c
FROM
table t
GROUP BY
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' end
)

select volume,c1, case when Volume ='0' then (select sum(c3) from cte) else c2 end c2 from cte

Title: Subtract and Sum Operations On Columns

Body:
I have an output like this:

Volume               c1                     c2
--------------------------------------------------
0                   1000                     0
1-20                 100                    10
20+                   50                    40

I get this output by this:

SELECT
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' as Volume,
sum(ab) as c1,
sum(xy) as c2
FROM
table t
GROUP BY
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+'

However, I need to get the output just like below. I am trying to subtract sum of c1 column from sum of c2 column and result must be placed at first row under c2 column just like this:

Volume                c1                  c2
--------------------------------------------------
0                   1000                **1100**
1-20                 100                  10
20+                   50                  40

How can I do this?

Thanks in advance.


问:
How to reshape a table having multiple records for the same id into a table with one record per id without losing information?
Basically, I want to transform this(Initial) into this(Final). In other words, I want to

"squash" the initial table so that it will have only one record per id

"dilate" the initial table so that I won't lose any information: create a different column for every possible combination of source and column from the initial table (create c1_A, c1_B, ...).

I can work with the initial table as a csv in Python (maybe Pandas) and manually hardcode the mapping between the Initial and the Final table. However, I don't find this solution elegant at all and I'm much more interested in a sql / sas solution. Is there any way of doing that?

Edit: I what to change

```<code>+----+--------+------+-----+------+
| ID | source |  c1  | c2  |  c3  |
+----+--------+------+-----+------+
|  1 | A      |  432 |  56 |    1 |
|  1 | B      |   53 |   3 |   73 |
|  1 | C      |    7 | 342 |   83 |
|  1 | D      |  543 |  43 |   73 |
|  2 | A      |    8 | 882 |   39 |
|  2 | B      |    5 |  54 |   46 |
|  2 | C      |    8 |   3 | 2226 |
|  2 | D      |   87 |   2 |   45 |
|  3 | A      |   93 | 143 |   45 |
|  3 | B      | 1023 |  72 |    8 |
|  3 | C      |    3 |   3 |  704 |
|  4 | A      |    2 |   5 |    0 |
|  4 | B      |   78 | 888 |    2 |
|  4 | C      |   87 |  23 |   34 |
|  4 | D      |  112 |   7 |  712 |
+----+--------+------+-----+------+
</code>```

into

```<code>+----+------+------+------+------+------+------+------+------+------+------+------+------+
| ID | c1_A | c1_B | c1_C | c1_D | c2_A | c2_B | c2_C | c2_D | c3_A | c3_B | c3_C | c3_D |
+----+------+------+------+------+------+------+------+------+------+------+------+------+
|  1 |  432 |   53 |    7 |  543 |   56 |    3 |  342 |   43 |    1 |   73 |   83 |   73 |
|  2 |    8 |    5 |    8 |   87 |  882 |   54 |    3 |    2 |   39 |   46 | 2226 |   45 |
|  3 |   93 | 1023 |    3 |      |  143 |   72 |    3 |      |   45 |    8 |  704 |      |
|  4 |    2 |   78 |   87 |  112 |    5 |  888 |   23 |    7 |    0 |    2 |   34 |  712 |
+----+------+------+------+------+------+------+------+------+------+------+------+------+
</code>```

答:
Abandon hope ... ?

```<code>data want;
input
  ID   source $  c1    c2     c3;datalines;
   1   A         432    56      1
   1   B          53     3     73
   1   C           7   342     83
   1   D         543    43     73
   2   A           8   882     39
   2   B           5    54     46
   2   C           8     3   2226
   2   D          87     2     45
   3   A          93   143     45
   3   B        1023    72      8
   3   C           3     3    704
   4   A           2     5      0
   4   B          78   888      2
   4   C          87    23     34
   4   D         112     7    712
;

* one to grow you oh data;
proc transpose data=want out=stage1;
  by id source;
  var c1-c3;
run;

* and one to shrink;
proc transpose data=stage1 out=want(drop=_name_) delim=_;
  by id;
  id _name_ source;
run;
</code>```

Body:
Basically, I want to transform this(Initial) into this(Final). In other words, I want to

"squash" the initial table so that it will have only one record per id

"dilate" the initial table so that I won't lose any information: create a different column for every possible combination of source and column from the initial table (create c1_A, c1_B, ...).

I can work with the initial table as a csv in Python (maybe Pandas) and manually hardcode the mapping between the Initial and the Final table. However, I don't find this solution elegant at all and I'm much more interested in a sql / sas solution. Is there any way of doing that?

Edit: I what to change

+----+--------+------+-----+------+
| ID | source |  c1  | c2  |  c3  |
+----+--------+------+-----+------+
|  1 | A      |  432 |  56 |    1 |
|  1 | B      |   53 |   3 |   73 |
|  1 | C      |    7 | 342 |   83 |
|  1 | D      |  543 |  43 |   73 |
|  2 | A      |    8 | 882 |   39 |
|  2 | B      |    5 |  54 |   46 |
|  2 | C      |    8 |   3 | 2226 |
|  2 | D      |   87 |   2 |   45 |
|  3 | A      |   93 | 143 |   45 |
|  3 | B      | 1023 |  72 |    8 |
|  3 | C      |    3 |   3 |  704 |
|  4 | A      |    2 |   5 |    0 |
|  4 | B      |   78 | 888 |    2 |
|  4 | C      |   87 |  23 |   34 |
|  4 | D      |  112 |   7 |  712 |
+----+--------+------+-----+------+

into

+----+------+------+------+------+------+------+------+------+------+------+------+------+
| ID | c1_A | c1_B | c1_C | c1_D | c2_A | c2_B | c2_C | c2_D | c3_A | c3_B | c3_C | c3_D |
+----+------+------+------+------+------+------+------+------+------+------+------+------+
|  1 |  432 |   53 |    7 |  543 |   56 |    3 |  342 |   43 |    1 |   73 |   83 |   73 |
|  2 |    8 |    5 |    8 |   87 |  882 |   54 |    3 |    2 |   39 |   46 | 2226 |   45 |
|  3 |   93 | 1023 |    3 |      |  143 |   72 |    3 |      |   45 |    8 |  704 |      |
|  4 |    2 |   78 |   87 |  112 |    5 |  888 |   23 |    7 |    0 |    2 |   34 |  712 |
+----+------+------+------+------+------+------+------+------+------+------+------+------+

Body:
Abandon hope ... ?

data want;
input
  ID   source $  c1    c2     c3;datalines;
   1   A         432    56      1
   1   B          53     3     73
   1   C           7   342     83
   1   D         543    43     73
   2   A           8   882     39
   2   B           5    54     46
   2   C           8     3   2226
   2   D          87     2     45
   3   A          93   143     45
   3   B        1023    72      8
   3   C           3     3    704
   4   A           2     5      0
   4   B          78   888      2
   4   C          87    23     34
   4   D         112     7    712
;

* one to grow you oh data;
proc transpose data=want out=stage1;
  by id source;
  var c1-c3;
run;

* and one to shrink;
proc transpose data=stage1 out=want(drop=_name_) delim=_;
  by id;
  id _name_ source;
run;


问:
SQL - Removing Row Groups
I have a table with the following information:

Is there a way to remove all groups which have multiple IDs? For example group 3 would be removed because it consists of ID 1 and 2.

Thank you!

答:
You can use below query to remove all groups having multiple IDs

```<code>Delete from <your_table_name> where Group in (select Group from <your_table_name> group by Group,ID having count(*) > 1)
</code>```

inner query will return Group having multiple IDs.

Title: SQL - Removing Row Groups

Body:
You can use below query to remove all groups having multiple IDs

Delete from <your_table_name> where Group in (select Group from <your_table_name> group by Group,ID having count(*) > 1)

inner query will return Group having multiple IDs.


问:
How do have both count and percent on barcharts in ggplot2? R
this is my data

```<code>data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c("5","7", "3"),
                   "Percent" = c("33%", "47%", "20%"))
</code>```

This is my plot

```<code>ggplot(data, aes(x=Name, y=Freq)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=data$Freq, vjust=-1)

</code>```

How can I have both my percent label next to my freq label preferably in parenthesis or separated by a comma?

答:
Compose the text label with paste/paste0.

```<code>ggplot(data, aes(x = Name, y = as.numeric(Freq))) +
  geom_bar(stat = "identity", color = "black", fill = "dodgerblue1")+
  geom_text(label = with(data, paste(Freq, paste0('(', Percent, ')'))), vjust=-1) +
  ylim(0, 8)
</code>```

Body:
this is my data

data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c("5","7", "3"),
                   "Percent" = c("33%", "47%", "20%"))

This is my plot

ggplot(data, aes(x=Name, y=Freq)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=data$Freq, vjust=-1)

How can I have both my percent label next to my freq label preferably in parenthesis or separated by a comma?

Body:
Compose the text label with paste/paste0.

ggplot(data, aes(x = Name, y = as.numeric(Freq))) +
  geom_bar(stat = "identity", color = "black", fill = "dodgerblue1")+
  geom_text(label = with(data, paste(Freq, paste0('(', Percent, ')'))), vjust=-1) +
  ylim(0, 8)


问:
height and align-content: center is not working in css flexbox
"height:100%" and "align-content: center" are not working in css flexbox.

For below code, can someone please suggest how to align child element vertically?

body {
    background-color: #eee;
}

.container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    width: 100%;
    text-align: center;
    background-color: rgb(8, 8, 119);
}

.child {
    background-color: green;
    height: 100%;
    color: #fff;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Flexbox</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="container">
      <div class="child">
        SkillsEnabled
      </div>
    </div>
  </body>
</html></code>```

答:
When searching for alignments on the vertical scale, I suggest to work with flexbox column logic like so:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  width: 100%;
  text-align: center;
  background-color: cadetblue;
}

.child {
  background-color: chartreuse;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Flexbox</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="container">
      <div class="child">
        SkillsEnabled
      </div>
    </div>
  </body>
</html></code>```

Body:
"height:100%" and "align-content: center" are not working in css flexbox.

For below code, can someone please suggest how to align child element vertically?

body {
    background-color: #eee;
}

.container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    width: 100%;
    text-align: center;
    background-color: rgb(8, 8, 119);
}

.child {
    background-color: green;
    height: 100%;
    color: #fff;
  }

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Flexbox</title>
    <link rel="stylesheet" href="style.css">

        SkillsEnabled

Body:
When searching for alignments on the vertical scale, I suggest to work with flexbox column logic like so:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  width: 100%;
  text-align: center;
  background-color: cadetblue;
}

.child {
  background-color: chartreuse;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Flexbox</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="container">
      <div class="child">
        <a href="#">SkillsEnabled</a>
      </div>
    </div>
  </body>
</html>


问:
AWS IOT End Point and Route53
Once we create a thing in AWS IOT Core, we get an endpoint which has to be used by java program in the device to connect to AWS IOT.

The endpoint *.iot.us-west-2.amazonaws.com has region in it. This end point has to be configured in device which we want to avoid. The reason is to have low latency when device communicates with AWS IOT. For this, we were planning to have a registered domain and create a hosted zone in Route53. Then map this domain to the actual end point. In Route53 we can select the "Geolocation" as a routing policy and create records for each region and map the corresponding endpoint.Do you think this a good solution?

The purpose is -

The device should not be aware of the IOT endpoint,

Route 53 should be able to identify the region of incoming traffic and directs it to the corresponding endpoint as specified by various records in the hosted zone.

Another question is - The program on the device which is connecting to AWS IOT is MQTT client. Will it be able to connect to Route53? (Route 53 is not an MQTT server.)

答:
Recently, AWS has added a support of configurable domain name for IoT endpoint, though in beta version yet.

Outline to achieve it

Register certificate to AWS Certificate Manager (ACM)

Create Domain Configuration for IoT (of type DATA)

Using Route 53, create DNS record for domain and IoT mapping.

Step by Step illustration, is available here

Title: AWS IOT End Point and Route53


问:
Pytorch could not find module
I have installed pytorch with command:

```<code>conda install pytorch torchvision cudatoolkit=10.2 -c pytorch -y
</code>```

Python complains regarding line import torch with message:

```<code>Could not find module 'C:\ProgramData\Anaconda3\envs\edx\lib\site-packages\torch\lib\caffe2_nvrtc.dll' (or one of its dependencies). Try using the full path with constructor syntax
</code>```

This directory contains library caffe2_nvrtc.dll. What might be wrong and how to fix this error?

答: I faced the same problem. If your OS is Windows then I would recommend using Anaconda and installing pytorch in separate conda environment. Quick solution is to search for nvcuda.dll file on google and download this file. If you are running the code on Jupyter notebook the output will give you the complete path of the 'lib' folder of conda environment. By default it is 'C:\Users\YourUserName\anaconda3\envs\mera_beta\Lib\site-packages\torch\lib'. Go this directory and paste the file in this folder. Rerun your code. Hopefully it will run.</p>

Title: Pytorch could not find module

Body:
I have installed pytorch with command:

conda install pytorch torchvision cudatoolkit=10.2 -c pytorch -y

Python complains regarding line import torch with message:

Could not find module 'C:\ProgramData\Anaconda3\envs\edx\lib\site-packages\torch\lib\caffe2_nvrtc.dll' (or one of its dependencies). Try using the full path with constructor syntax

This directory contains library caffe2_nvrtc.dll. What might be wrong and how to fix this error?


问:
Parse JSON using GSON in Kotlin
I have JSON data like this and I want to parse using GSON in Kotlin

```<code>{"items":["Green Tea","19,90"]}

</code>```

First item is name of product, second is price of product.

I am not really sure how to do it. Json format is correct. Do I have to create data class? How it should look like?

答:
You'll have to make two data classes like

data class MainItem(val items: List<ItemsDataClass>)

data class ItemsDataClass(val name: String, val price: String)
```

And after that parse MainItem from your JSON.

Title: Parse JSON using GSON in Kotlin

Body:
I have JSON data like this and I want to parse using GSON in Kotlin

{"items":["Green Tea","19,90"]}

First item is name of product, second is price of product.

I am not really sure how to do it. Json format is correct. Do I have to create data class? How it should look like?

Body:
You'll have to make two data classes like

data class MainItem(val items: List<ItemsDataClass>)

data class ItemsDataClass(val name: String, val price: String)

And after that parse MainItem from your JSON.


问:
Find closest item in array that matches criteria in Swift?
When I have a reference to an item in an array, I'd like to find another item closest to it that matches a certain criteria (forward or backwards).

For example, I have this array:

```<code>let items = [
    (a: "Item 1", b: "F", c: 3),
    (a: "Item 2", b: "S", c: 5),
    (a: "Item 3", b: "D", c: 7),
    (a: "Item 4", b: "A", c: 9),
    (a: "Item 5", b: "M", c: 11),
    (a: "Item 6", b: "I", c: 13),
    (a: "Item 7", b: "F", c: 15),
    (a: "Item 8", b: "S", c: 17),
    (a: "Item 9", b: "D", c: 19),
    (a: "Item 10", b: "A", c: 21),
    (a: "Item 11", b: "M", c: 23),
    (a: "Item 12", b: "I", c: 13),
    (a: "Item 13", b: "F", c: 15),
    (a: "Item 14", b: "S", c: 17),
    (a: "Item 15", b: "D", c: 19),
    (a: "Item 16", b: "A", c: 21),
    (a: "Item 17", b: "M", c: 23),
    (a: "Item 18", b: "I", c: 13),
    (a: "Item 19", b: "F", c: 15),
    (a: "Item 20", b: "S", c: 17),
    (a: "Item 21", b: "D", c: 19),
    (a: "Item 22", b: "A", c: 21),
    (a: "Item 23", b: "M", c: 23),
    (a: "Item 24", b: "I", c: 13)
]
</code>```

Now say I have item[7], how can I find the closest item that has b = "I"? I can only think of a few nested for loops but sounds messy and not good on performance. Also keeping in mind I don't want an out of range issue when searching. Any Swift-like ideas on how to handle this?

答:
Optimised solution using higher order functions: </p>

```<code> func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
    return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
}
</code>```

<p>Swift is advancing with every version to optimise the performance and efficiency. With higher order functions finding the closest match in an array of values is much easier with this implementation. Change the type of value as per your need. </p>

Body:
When I have a reference to an item in an array, I'd like to find another item closest to it that matches a certain criteria (forward or backwards).

For example, I have this array:

let items = [
    (a: "Item 1", b: "F", c: 3),
    (a: "Item 2", b: "S", c: 5),
    (a: "Item 3", b: "D", c: 7),
    (a: "Item 4", b: "A", c: 9),
    (a: "Item 5", b: "M", c: 11),
    (a: "Item 6", b: "I", c: 13),
    (a: "Item 7", b: "F", c: 15),
    (a: "Item 8", b: "S", c: 17),
    (a: "Item 9", b: "D", c: 19),
    (a: "Item 10", b: "A", c: 21),
    (a: "Item 11", b: "M", c: 23),
    (a: "Item 12", b: "I", c: 13),
    (a: "Item 13", b: "F", c: 15),
    (a: "Item 14", b: "S", c: 17),
    (a: "Item 15", b: "D", c: 19),
    (a: "Item 16", b: "A", c: 21),
    (a: "Item 17", b: "M", c: 23),
    (a: "Item 18", b: "I", c: 13),
    (a: "Item 19", b: "F", c: 15),
    (a: "Item 20", b: "S", c: 17),
    (a: "Item 21", b: "D", c: 19),
    (a: "Item 22", b: "A", c: 21),
    (a: "Item 23", b: "M", c: 23),
    (a: "Item 24", b: "I", c: 13)
]

Now say I have item[7], how can I find the closest item that has b = "I"? I can only think of a few nested for loops but sounds messy and not good on performance. Also keeping in mind I don't want an out of range issue when searching. Any Swift-like ideas on how to handle this?

Body:
Optimised solution using higher order functions:

 func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
    return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
}

Swift is advancing with every version to optimise the performance and efficiency. With higher order functions finding the closest match in an array of values is much easier with this implementation. Change the type of value as per your need.


问:
Ask Google Home Assistant to run CURL commands
I cannot find a way to ask my Google Home Assistant to run cURL commands for me. Ideally this process is achieved through services linked together only but a script would do also; my language of preference is C#. I'd then convert the C# code to python and put on rpi.

I have tried using IFTTT webhooks, zapier and was looking into google assistant sdk but it seems that the process/setup is way too complex to achieve such a simple task.

Any easier ways to do this please?

答: How about using a command_line switch or a shell command? You should be able to execute both as part of an automation.</p>


问:
AS2: string in array is undefined
I have the following code on the timeline, but when I try and output date_string from the Slider_Tracker array it says it is undefined.

```<code>var Days:Array = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday');
var Months:Array = new Array('January', 'February', 'March', 'April', 'May', 'June','July','August','September','October','November','December');
var current_date = new Date();
var day_num = current_date.getDay();
var year = current_date.getFullYear();
var month = current_date.getMonth();
var date_num:String = new String(current_date.getDate());
date_char = date_num.charAt(date_num.length-1);
if (date_char == 1) {
    date_suffix = "st";
}
else if (date_char == 2) {
    date_suffix = "nd";
}
else if (date_char == 3) {
    date_suffix = "rd";
}
var date_string:String = new String(Days[day_num]+" "+date_num+date_suffix+" of "+Months[month]+" "+year);
trace(date_string);
date_int = current_date.getTime();
trace(current_date);
trace(date_int);
var Sliders:Array = Array (slider1.slider, slider2.slider, slider3.slider, slider4.slider, slider5.slider, slider6.slider, slider7.slider, slider8.slider, slider9.slider);
var Slide_Tracker:Array = new Array();
var local_data = SharedObject.getLocal("user_data");

if (local_data.data.user_data == undefined) {
    local_data.data.user_data = Slide_Tracker;
    trace("fail");
} else {
    Slide_Tracker = local_data.data.user_data;
    for (i=0;i<Slide_Tracker.length;i++) {
            trace(Slide_Tracker[i][1]);

        if(Slide_Tracker[i][1] == date_string) {
            index = i;
        }
    }
    trace("success");
}
var current_time = new Date();

this._parent.fullClear.onRelease = function() {
    local_data.clear();
}

this._parent.saver.onRelease = function() {
trace(date_string);
Slide_Tracker.push(new Array(date_int, date_string));
for (i=0;i<Sliders.length;i++) {
    Slide_Tracker[0].push(100-Sliders[i]._y);
}
    Slide_tracker.push(today_Stats);
    local_data.data.user_data = Slide_Tracker;
    local_data.flush();

    nextFrame();

};
</code>```

Can anyone see my downfall? thanks.

答:
You mean the trace in this._parent.saver.onRelease?

That's a different scope unfortunately, it'll be relative to your this._parent.saver MovieClip, so it won't have access to date_string and Slide_Tracker you defined here.

Title: AS2: string in array is undefined

Body:
I have the following code on the timeline, but when I try and output date_string from the Slider_Tracker array it says it is undefined.

var Days:Array = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday');
var Months:Array = new Array('January', 'February', 'March', 'April', 'May', 'June','July','August','September','October','November','December');
var current_date = new Date();
var day_num = current_date.getDay();
var year = current_date.getFullYear();
var month = current_date.getMonth();
var date_num:String = new String(current_date.getDate());
date_char = date_num.charAt(date_num.length-1);
if (date_char == 1) {
    date_suffix = "st";
}
else if (date_char == 2) {
    date_suffix = "nd";
}
else if (date_char == 3) {
    date_suffix = "rd";
}
var date_string:String = new String(Days[day_num]+" "+date_num+date_suffix+" of "+Months[month]+" "+year);
trace(date_string);
date_int = current_date.getTime();
trace(current_date);
trace(date_int);
var Sliders:Array = Array (slider1.slider, slider2.slider, slider3.slider, slider4.slider, slider5.slider, slider6.slider, slider7.slider, slider8.slider, slider9.slider);
var Slide_Tracker:Array = new Array();
var local_data = SharedObject.getLocal("user_data");

if (local_data.data.user_data == undefined) {
    local_data.data.user_data = Slide_Tracker;
    trace("fail");
} else {
    Slide_Tracker = local_data.data.user_data;
    for (i=0;i<Slide_Tracker.length;i++) {
            trace(Slide_Tracker[i][1]);

        if(Slide_Tracker[i][1] == date_string) {
            index = i;
        }
    }
    trace("success");
}
var current_time = new Date();

this._parent.fullClear.onRelease = function() {
    local_data.clear();
}

this._parent.saver.onRelease = function() {
trace(date_string);
Slide_Tracker.push(new Array(date_int, date_string));
for (i=0;i<Sliders.length;i++) {
    Slide_Tracker[0].push(100-Sliders[i]._y);
}
    Slide_tracker.push(today_Stats);
    local_data.data.user_data = Slide_Tracker;
    local_data.flush();

    nextFrame();

};

Can anyone see my downfall? thanks.


问:
Make a section Visible on the action of Button from other section
I'm showing the data on tableview with multiple section,

when I open tableView height of section 1 should be 0. If I click a button in section 0 the height of the section 1 will be 150. For example if I click Agent button height of (want to) section cell show 150,I click builder button section hight will 0

I want to make the Section 1 visible on the button click from section 0

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.section == 0
        {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! postaddTableViewCell1

            cell.ownerButton.addTarget(self, action: #selector(FisrtButtonClick), for: .touchUpInside)
            cell.agentButton.addTarget(self, action: #selector(FisrtButtonClick), for: .touchUpInside)
            cell.builderButton.addTarget(self, action: #selector(FisrtButtonClick), for: .touchUpInside)
            return cell

        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! postaddTableViewCell2
            cell.checkbutton.tag = indexPath.row
            cell.checkbutton.addTarget(self, action: #selector(checkbuttonClick) , for: .touchUpInside)
            return cell
        }
    }

  @objc func FisrtButtonClick(_ sender :UIButton)
    {
        let indexPath = IndexPath(row: 0, section: 0)
        let cell = TableView.cellForRow(at: indexPath) as? postaddTableViewCell1

        print(cell?.agentButton.titleLabel as Any)

        if sender.tag == 10
        {
            cell?.ownerButton.backgroundColor = #colorLiteral(red: 0, green: 0.7254901961, blue: 0.4588235294, alpha: 1)
            cell?.agentButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
            cell?.builderButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
        }else if sender.tag == 11
        {
            cell?.ownerButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
            cell?.agentButton.backgroundColor = #colorLiteral(red: 0, green: 0.7254901961, blue: 0.4588235294, alpha: 1)
            cell?.builderButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)

        } else if sender.tag == 12
        {
            cell?.ownerButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
            cell?.agentButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
            cell?.builderButton.backgroundColor = #colorLiteral(red: 0, green: 0.7254901961, blue: 0.4588235294, alpha: 1)
        }

    }
 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        if indexPath.section == 0
        {
            return 80
        }
        if indexPath.section == 1
        {
            return 0
        }
        return 80
     }
</code>```

答:
Check if the required button is clicked in the FisrtButtonClick method and set a boolean that is accessible to heightForRowAt. After toggling the boolean you can just reload the section you require (also cleaned up your code lil bit).

var selectedAgent = false

@objc func firstButtonClick(_ sender: UIButton) {
    if sender.currentTitle == "Agent" {
        selectedAgent = true
        tableView.reloadSections([1], with: .automatic)
    }
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.section == 1 && !selectedAgent {
        return 0
    }
    return 80
}
```

Body:
I'm showing the data on tableview with multiple section,

when I open tableView height of section 1 should be 0. If I click a button in section 0 the height of the section 1 will be 150. For example if I click Agent button height of (want to) section cell show 150,I click builder button section hight will 0

I want to make the Section 1 visible on the button click from section 0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.section == 0
        {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! postaddTableViewCell1

            cell.ownerButton.addTarget(self, action: #selector(FisrtButtonClick), for: .touchUpInside)
            cell.agentButton.addTarget(self, action: #selector(FisrtButtonClick), for: .touchUpInside)
            cell.builderButton.addTarget(self, action: #selector(FisrtButtonClick), for: .touchUpInside)
            return cell

        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! postaddTableViewCell2
            cell.checkbutton.tag = indexPath.row
            cell.checkbutton.addTarget(self, action: #selector(checkbuttonClick) , for: .touchUpInside)
            return cell
        }
    }

  @objc func FisrtButtonClick(_ sender :UIButton)
    {
        let indexPath = IndexPath(row: 0, section: 0)
        let cell = TableView.cellForRow(at: indexPath) as? postaddTableViewCell1

        print(cell?.agentButton.titleLabel as Any)

        if sender.tag == 10
        {
            cell?.ownerButton.backgroundColor = #colorLiteral(red: 0, green: 0.7254901961, blue: 0.4588235294, alpha: 1)
            cell?.agentButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
            cell?.builderButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
        }else if sender.tag == 11
        {
            cell?.ownerButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
            cell?.agentButton.backgroundColor = #colorLiteral(red: 0, green: 0.7254901961, blue: 0.4588235294, alpha: 1)
            cell?.builderButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)

        } else if sender.tag == 12
        {
            cell?.ownerButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
            cell?.agentButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
            cell?.builderButton.backgroundColor = #colorLiteral(red: 0, green: 0.7254901961, blue: 0.4588235294, alpha: 1)
        }

    }
 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        if indexPath.section == 0
        {
            return 80
        }
        if indexPath.section == 1
        {
            return 0
        }
        return 80
     }


问:
React DatePicker change default start date
I'm using https://reactdatepicker.com/ .

Right now the default start date is the current date. I want the start date to be +45 days in advance. The calendar does not need to disable any dates from current to 44 days, I just want the calendar to select that day initially.

This is my current code:

```<code>this.state = {
    startDate: new Date(),
}

handleChangeDate = date => {
    this.setState({
      startDate: date
    });
};

<DatePicker
    selected={this.state.startDate}
    onChange={this.handleChangeDate}
/>
</code>```

I tried something like this to no success, I couldn't find any props in their documentation to do this.

```<code>handleChangeDate = date => {
    const Newdate = new Date();
    date.setDate(date.getDate() + 45);
    this.setState({
      startDate: Newdate,
    });
};
</code>```

答:
You should set the Date +45 as the initial Date itself. Selected property is used for initial initalization only</p>

```<code>class MyComponent extends React.Component {
    constructor () {
      const newdate = new Date();
      newdate.setDate(newdate.getDate() + 45);
      this.state = {
        startDate: newdate,
      }
    }

    handleChangeDate = date => {
        this.setState({
          startDate: date
        });
    };
    render () {
      return (
        <DatePicker
          selected={this.state.startDate}
          onChange={this.handleChangeDate}
        />
      )
    }
  }
</code>```

Body:
I'm using https://reactdatepicker.com/ .

Right now the default start date is the current date. I want the start date to be +45 days in advance. The calendar does not need to disable any dates from current to 44 days, I just want the calendar to select that day initially.

This is my current code:

this.state = {
    startDate: new Date(),
}

handleChangeDate = date => {
    this.setState({
      startDate: date
    });
};

<DatePicker
    selected={this.state.startDate}
    onChange={this.handleChangeDate}
/>

I tried something like this to no success, I couldn't find any props in their documentation to do this.

handleChangeDate = date => {
    const Newdate = new Date();
    date.setDate(date.getDate() + 45);
    this.setState({
      startDate: Newdate,
    });
};

Body:
You should set the Date +45 as the initial Date itself. Selected property is used for initial initalization only

class MyComponent extends React.Component {
    constructor () {
      const newdate = new Date();
      newdate.setDate(newdate.getDate() + 45);
      this.state = {
        startDate: newdate,
      }
    }

    handleChangeDate = date => {
        this.setState({
          startDate: date
        });
    };
    render () {
      return (
        <DatePicker
          selected={this.state.startDate}
          onChange={this.handleChangeDate}
        />
      )
    }
  }


问:
how can I get the right index in react&antD
AppUI.js

```<code>class AppUI extends Component {
render() {
    return (
        <div>
            <List
                itemLayout="horizontal"
                dataSource={this.props.list}
                renderItem={(item, index) => (
                    <List.Item onClick={(index) => {
                        this.props.handleDelete(index)
                    }}>
                        {item.title}
                    </List.Item>
                )}
            />
        </div>
    )
}
</code>```

}

App.js

```<code>class App extends Component {
constructor(props) {
    super(props);
    this.state = store.getState();
    this.handleStore = this.handleStore.bind(this);
    this.handleDelete = this.handleDelete.bind(this);
    store.subscribe(this.handleStore);
}

render() {
    return (
        <AppUI
            handleDelete={this.handleDelete}
            list={this.state.list}
        />
    )
}

handleDelete(index) {
    const action = getDeleteListAction(index);
    store.dispatch(action);
}

handleStore() {
    this.setState(store.getState())

}
</code>```

}

my question is that how can I get the right index when I click each list

  my question is that how can I get the right index when I click each list

  my question is that how can I get the right index when I click each list

```<code>  renderItem={(item, index) => (
                        <List.Item onClick={(index) => {
                            this.props.handleDelete(index)
                        }}>
                            {item.title}
                        </List.Item>
                    )}
</code>```

答:
Your onClick handler needs a bit of tweaking, that param is actually the event, which is what you ended up passing into handleDelete. You want something like

```<code>renderItem={(item, index) => (
  <List.Item onClick={() => {
    this.props.handleDelete(index)
  }}>
    {item.title}
  </List.Item>
)}
</code>```

As a side note, its probably better in the long run to pass the item itself and find by a ID or some sort of identifier

Body:
AppUI.js

class AppUI extends Component {
render() {
    return (

            <List
                itemLayout="horizontal"
                dataSource={this.props.list}
                renderItem={(item, index) => (
                    <List.Item onClick={(index) => {
                        this.props.handleDelete(index)
                    }}>
                        {item.title}
                    </List.Item>
                )}
            />

    )
}

}

App.js

class App extends Component {
constructor(props) {
    super(props);
    this.state = store.getState();
    this.handleStore = this.handleStore.bind(this);
    this.handleDelete = this.handleDelete.bind(this);
    store.subscribe(this.handleStore);
}

render() {
    return (
        <AppUI
            handleDelete={this.handleDelete}
            list={this.state.list}
        />
    )
}

handleDelete(index) {
    const action = getDeleteListAction(index);
    store.dispatch(action);
}

handleStore() {
    this.setState(store.getState())

}

}

my question is that how can I get the right index when I click each list

  my question is that how can I get the right index when I click each list

  my question is that how can I get the right index when I click each list

  renderItem={(item, index) => (
                        <List.Item onClick={(index) => {
                            this.props.handleDelete(index)
                        }}>
                            {item.title}
                        </List.Item>
                    )}

Body:
Your onClick handler needs a bit of tweaking, that param is actually the event, which is what you ended up passing into handleDelete. You want something like

renderItem={(item, index) => (
  <List.Item onClick={() => {
    this.props.handleDelete(index)
  }}>
    {item.title}
  </List.Item>
)}

As a side note, its probably better in the long run to pass the item itself and find by a ID or some sort of identifier


问:
Express: Req.body is undefined after POST req
I am new to node JS.
I am getting undefined for post request. My express version is 4.10.
I think I am missing something.

```<code>var express = require('express');
var http = require('http');

var app = express();

app.use(express.static(__dirname + '/public'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.post('/test',function(req,res){
    var color1 = req.body.color;
    console.log(req.headers);
    console.log("Color : "+color1);
});
</code>```

In content-length I am getting 234.

Thanks!!

答:
The correct answer is to change the default Content-Type as described above:

```<code>app.use(bodyParser.json({
    type: 'application/vnd.api+json',
    strict: false
}));
</code>```

strict:false gets around some bugs in bodyParser rejecting valid JSON objects.

Body:
I am new to node JS.
I am getting undefined for post request. My express version is 4.10.
I think I am missing something.

var express = require('express');
var http = require('http');

var app = express();

app.use(express.static(__dirname + '/public'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.post('/test',function(req,res){
    var color1 = req.body.color;
    console.log(req.headers);
    console.log("Color : "+color1);
});

In content-length I am getting 234.

Thanks!!

Body:
The correct answer is to change the default Content-Type as described above:

app.use(bodyParser.json({
    type: 'application/vnd.api+json',
    strict: false
}));

strict:false gets around some bugs in bodyParser rejecting valid JSON objects.


问:
How to replace those entries in a column which have parenthesis or numbers included with them in a pandas dataframe?
```<code>I have a dataframe like this:
    Country                  Energy Supply      Energy Supply per Capita
16  Afghanistan              3.210000e+08       10.0
17  Albania                  1.020000e+08       35.0
18  Algeria                  1.959000e+09       51.0
19  American Samoa           NaN
40  Bolivia
   (Plurinational State of)  3.360000e+08       32.0
... ... ... ...
213 Switzerland17            1.113000e+09       136.0
214 Syrian Arab Republic     5.420000e+08       28.0
215 Tajikistan               1.060000e+08       13.0
216 Thailand                 5.336000e+09       79.0
228 Ukraine18                4.844000e+09       107.0
232 United States of
    America20                9.083800e+10       286.0
</code>```

I needed to replace name of all those countries which are having parenthesis or numbers in their name. For example: 'Bolivia (Plurinational State of)' should be 'Bolivia','Switzerland17' should be 'Switzerland' and 'United States of America20' should be 'United States of America'.
I tried this using replace() and split() but nothing worked out for me.

Can somebody please help me with this.

答:
You can use this regex pattern with str.extract:

```<code>df['Country'] = df.Country.str.extract('^([^\d\(]*)')[0]
</code>```

Output:

```<code>                      Country  Energy Supply  Energy Supply per Capita
16                Afghanistan   3.210000e+08                      10.0
17                    Albania   1.020000e+08                      35.0
18                    Algeria   1.959000e+09                      51.0
19             American Samoa            NaN                       NaN
40                   Bolivia    3.360000e+08                      32.0
213               Switzerland   1.113000e+09                     136.0
214      Syrian Arab Republic   5.420000e+08                      28.0
215                Tajikistan   1.060000e+08                      13.0
216                  Thailand   5.336000e+09                      79.0
228                   Ukraine   4.844000e+09                     107.0
232  United States of America   9.083800e+10                     286.0
</code>```

Body:
I have a dataframe like this:
    Country                  Energy Supply      Energy Supply per Capita
16  Afghanistan              3.210000e+08       10.0
17  Albania                  1.020000e+08       35.0
18  Algeria                  1.959000e+09       51.0
19  American Samoa           NaN
40  Bolivia
   (Plurinational State of)  3.360000e+08       32.0
... ... ... ...
213 Switzerland17            1.113000e+09       136.0
214 Syrian Arab Republic     5.420000e+08       28.0
215 Tajikistan               1.060000e+08       13.0
216 Thailand                 5.336000e+09       79.0
228 Ukraine18                4.844000e+09       107.0
232 United States of
    America20                9.083800e+10       286.0

I needed to replace name of all those countries which are having parenthesis or numbers in their name. For example: 'Bolivia (Plurinational State of)' should be 'Bolivia','Switzerland17' should be 'Switzerland' and 'United States of America20' should be 'United States of America'.
I tried this using replace() and split() but nothing worked out for me.

Can somebody please help me with this.

Body:
You can use this regex pattern with str.extract:

df['Country'] = df.Country.str.extract('^([^\d\(]*)')[0]

Output:

                      Country  Energy Supply  Energy Supply per Capita
16                Afghanistan   3.210000e+08                      10.0
17                    Albania   1.020000e+08                      35.0
18                    Algeria   1.959000e+09                      51.0
19             American Samoa            NaN                       NaN
40                   Bolivia    3.360000e+08                      32.0
213               Switzerland   1.113000e+09                     136.0
214      Syrian Arab Republic   5.420000e+08                      28.0
215                Tajikistan   1.060000e+08                      13.0
216                  Thailand   5.336000e+09                      79.0
228                   Ukraine   4.844000e+09                     107.0
232  United States of America   9.083800e+10                     286.0


问:
How to connect two users in one room in React Native JSX
i am a newbie. Making my first app in react-native. I am stuck on one step.

In the app a user can create a room on regestration. The room is shared ONLY between 2 users. So the second user can connect to it using the name of  the room and the password. Both users won't share one screen. The connection between the users in the room will be used only at the end. When the "game" is finished, the second user will be notified and will get a list of tasks that the first user has completed.

How could i achieve it?

THanks for any help.

答: You can use firebase or if you want to maintain, you can write a socket server using socket.io. If you're building using socket.io, then you can create a room when users join and send messages between users when you want to.


答:
You can use multiple regex with str.replace like this:

Consider below dataframe:

```<code>In [1431]: df
Out[1431]:
                            Country
0                       Afghanistan
1  Bolivia (Plurinational State of)
2                     Switzerland17

In [1433]: df['Country'] = df['Country'].str.replace(r"\(.*\)|\d+",'')
In [1434]: df
Out[1434]:
         Country
0    Afghanistan
1       Bolivia
2    Switzerland
</code>```

Title: How to replace those entries in a column which have parenthesis or numbers included with them in a pandas dataframe?

Body:
You can use multiple regex with str.replace like this:

Consider below dataframe:

In [1431]: df
Out[1431]:
                            Country
0                       Afghanistan
1  Bolivia (Plurinational State of)
2                     Switzerland17

In [1433]: df['Country'] = df['Country'].str.replace(r"\(.*\)|\d+",'')
In [1434]: df
Out[1434]:
         Country
0    Afghanistan
1       Bolivia
2    Switzerland