问:
AutoRole Discord.py
so I make a simple auto role, is good and work as well

this is my code

```<code>
@bot.event
async def on_member_join(member):
    role = discord.utils.get(member.guild.roles, name="Member")
    await member.add_roles(role)

    if discord.utils.get(member.guild.roles, name="Fruits"):
        role = discord.utils.get(member.guild.roles, name="Fruits")
        await member.remove_roles(role)
</code>```

and I want if the user gets role name "Fruits" the role name "Member" will automatically remove from the user, but this doesn't work for me, so after the user gets role name "Fruits" the role name "Member" doesn't remove from the user

I hope u guys can help me solve this problem
Thank You!

答:
From your code:

    Member = discord.utils.get(member.guild.roles, name="Member")
    await member.add_roles(Member)

    if discord.utils.get(member.guild.roles, name="Fruits"):
        Fruits = discord.utils.get(member.guild.roles, name="Fruits")
        await member.remove_roles(Fruits)
```

You first define role as the "Member" role, and then reassign the variable for "Fruits" role, so in the last line (await member.remove_roles(role)) the role which is removed is "Fruits", not "Members". Simply use different variables for both role.
Hope I was clear with my answer

Title: AutoRole Discord.py

Body:
so I make a simple auto role, is good and work as well

this is my code

@bot.event
async def on_member_join(member):
    role = discord.utils.get(member.guild.roles, name="Member")
    await member.add_roles(role)

    if discord.utils.get(member.guild.roles, name="Fruits"):
        role = discord.utils.get(member.guild.roles, name="Fruits")
        await member.remove_roles(role)

and I want if the user gets role name "Fruits" the role name "Member" will automatically remove from the user, but this doesn't work for me, so after the user gets role name "Fruits" the role name "Member" doesn't remove from the user

I hope u guys can help me solve this problem
Thank You!

Body:
From your code:

    Member = discord.utils.get(member.guild.roles, name="Member")
    await member.add_roles(Member)

    if discord.utils.get(member.guild.roles, name="Fruits"):
        Fruits = discord.utils.get(member.guild.roles, name="Fruits")
        await member.remove_roles(Fruits)

You first define role as the "Member" role, and then reassign the variable for "Fruits" role, so in the last line (await member.remove_roles(role)) the role which is removed is "Fruits", not "Members". Simply use different variables for both role.
Hope I was clear with my answer


来源: stackexchange

问:
awk remove before match but after empty line
I didn't find the exact similar question, so i need to ask:

I have a file gist :

```<code>...
must_be_intact

bad_line
bad_line
bad_line
match_line
...
</code>```

I use awk to remove everything before the match but after a space:

'NR==FNR{if (/match_line/) {
    i=0;
    while(1) {
        if (NR-i==/^\s*$/) break;
        del[NR-i];
        i=i-1;
        next
        }
    }
} !(FNR in del)'
```

But this does not work correctly. Help improve this code, or you can advise another way.

答:
$ sed '/^$/,/match_line/{/match_line/!d}' txt
...
must_be_intact
match_line
...
```
<p>Or</p>
<pre class="lang-sh prettyprint-override"><code>awk -v m="match_line" '{ if($0 ~ /^$/) { while($0 != m) getline } print }' txt
</code>```

Which yields the same output. I can edit/elaborate later if you want, now I have to go! :)

ContentLicense: CC BY-SA 4.0

Body:
I didn't find the exact similar question, so i need to ask:

I have a file gist :

...
must_be_intact

bad_line
bad_line
bad_line
match_line
...

I use awk to remove everything before the match but after a space:

'NR==FNR{if (/match_line/) {
    i=0;
    while(1) {
        if (NR-i==/^\s*$/) break;
        del[NR-i];
        i=i-1;
        next
        }
    }
} !(FNR in del)'

But this does not work correctly. Help improve this code, or you can advise another way.

Body:
$ sed '/^$/,/match_line/{/match_line/!d}' txt
...
must_be_intact
match_line
...

Or

awk -v m="match_line" '{ if($0 ~ /^$/) { while($0 != m) getline } print }' txt

Which yields the same output. I can edit/elaborate later if you want, now I have to go! :)


问:
Find Duplicate Objects in JSON Array
I am relatively new to c# and need some guidance. I need to search through a large json array to find duplicate objects and list how many occurrences.

Sample Array

```<code>{
    "data":
        [
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          }

        ]
}
</code>```

I have been able to search through and find duplicate elements but not the complete object. The output should be:

```<code>{
    "result":
        [
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND",
            "objCount": 2
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV",
            "objCount": 3
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND",
            "objCount": 3
          }

        ]
}
</code>```

Any help to point me in the right direction would be great. Thanks in advance

答:
You can try to create models to let your JSON data be objects

```<code>public class Datum
{
    public string date { get; set; }
    public string someID { get; set; }
    public string someType1 { get; set; }
    public string someType2 { get; set; }
}

public class Root
{
    public List<Datum> data { get; set; }
}
</code>```

then you can use JsonConvert.DeserializeObject method to deserialize the JSON value to be objects, then use lambda to get duplicate values from the list.

```<code>var root = JsonConvert.DeserializeObject<Root>(data);
var res = JsonConvert.SerializeObject(root.data.GroupBy(x=> new {
    x.someID,
    x.someType1,
    x.someType2,
    x.date
}).Where(x=>x.Count()>1).Select(x=>x.Key));
</code>```

c# online

Title: Find Duplicate Objects in JSON Array

Body:
I am relatively new to c# and need some guidance. I need to search through a large json array to find duplicate objects and list how many occurrences.

Sample Array

{
    "data":
        [
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          }

        ]
}

I have been able to search through and find duplicate elements but not the complete object. The output should be:

{
    "result":
        [
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND",
            "objCount": 2
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV",
            "objCount": 3
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND",
            "objCount": 3
          }

        ]
}

Any help to point me in the right direction would be great. Thanks in advance

Body:
You can try to create models to let your JSON data be objects

public class Datum
{
    public string date { get; set; }
    public string someID { get; set; }
    public string someType1 { get; set; }
    public string someType2 { get; set; }
}

public class Root
{
    public List<Datum> data { get; set; }
}

then you can use JsonConvert.DeserializeObject method to deserialize the JSON value to be objects, then use lambda to get duplicate values from the list.

var root = JsonConvert.DeserializeObject<Root>(data);
var res = JsonConvert.SerializeObject(root.data.GroupBy(x=> new {
    x.someID,
    x.someType1,
    x.someType2,
    x.date
}).Where(x=>x.Count()>1).Select(x=>x.Key));

c# online


问:
styled components extension is not Working in new update of Vs-code
I've updated vscode to 1.64, the styled-components extension is not suggesting anything. It was working correctly before this new update. is there any solution for that?

I am using react with typescript.

答: here same problem, looks like this update broken the extension</p>


问:
A dictionary inside of a dictionary in PowerShell
So, I'm rather new to PowerShell and just can't figure out how to use the arrays/lists/hashtables. I basically want to do the following portrayed by Python:

```<code>entries = {
    'one' : {
        'id': '1',
        'text': 'ok'
    },
    'two' : {
        'id': '2',
        'text': 'no'
    }
}

for entry in entries:
    print(entries[entry]['id'])
</code>```

Output:

1

2

But how does this work in PowerShell? I've tried the following:

```<code>$entries = @{
    one = @{
        id = "1";
        text = "ok"
    };
    two = @{
        id = "2";
        text = "no"
    }
}
</code>```

And now I can't figure out how to access the information.

```<code>foreach ($entry in $entries) {
   Write-Host $entries[$entry]['id']
}
</code>```

=> Error

答:
To complement Mathias R. Jessen's helpful answer with a more concise alternative that takes advantage of member-access enumeration:

# Implicitly loops over all entry values and from each
# gets the 'Id' entry value from the nested hashtable.
$entries.Values.Id  # -> 2, 1
```

Note: As with .Keys vs. .get_Keys(), you may choose to routinely use .get_Values() instead of .Values to avoid problems with keys literally named Values.

Body:
So, I'm rather new to PowerShell and just can't figure out how to use the arrays/lists/hashtables. I basically want to do the following portrayed by Python:

entries = {
    'one' : {
        'id': '1',
        'text': 'ok'
    },
    'two' : {
        'id': '2',
        'text': 'no'
    }
}

for entry in entries:
    print(entries[entry]['id'])

Output:

1

2

But how does this work in PowerShell? I've tried the following:

$entries = @{
    one = @{
        id = "1";
        text = "ok"
    };
    two = @{
        id = "2";
        text = "no"
    }
}

And now I can't figure out how to access the information.

foreach ($entry in $entries) {
   Write-Host $entries[$entry]['id']
}

=> Error

Body:
To complement Mathias R. Jessen's helpful answer with a more concise alternative that takes advantage of member-access enumeration:

# Implicitly loops over all entry values and from each
# gets the 'Id' entry value from the nested hashtable.
$entries.Values.Id  # -> 2, 1

Note: As with .Keys vs. .get_Keys(), you may choose to routinely use .get_Values() instead of .Values to avoid problems with keys literally named Values.


问:
Is there any way to get the pull request description using a command?
I have a PR and I have to get the description of the PR.

I know that there will be a way to get this using API., but is there any git command where I can use it to get the PR details of the branch?

答:
you could use github cli

then:

gh pr status


问:
Translate default message No data available in v-autocomplete
I would like to translate the default message No data found in v-autocomplete when the search returns nothing. I understand it is due to default behaviour, but my app supports multiple languages through i18n localization library, so I would like to make it fully localized.

Sample code is for the autocomplete component:

```<code><v-autocomplete
                class="form-select__region"
                :class="fieldName"
                dense
                :disabled="disabled"
                item-text="text"
                item-value="value"
                :items="getData"
                outlined
                single-line
                solo
                :value="value"
                @change="input(fieldName, $event)"
            >
            </v-autocomplete>
</code>```

答:
you need to use the slot 'no-data' like this :</p>
```<code><template v-slot:no-data>
   <div class="px-4">YOUR TEXT</div>
</template>
</code>```

Body:
I would like to translate the default message No data found in v-autocomplete when the search returns nothing. I understand it is due to default behaviour, but my app supports multiple languages through i18n localization library, so I would like to make it fully localized.

Sample code is for the autocomplete component:

<v-autocomplete
                class="form-select__region"
                :class="fieldName"
                dense
                :disabled="disabled"
                item-text="text"
                item-value="value"
                :items="getData"
                outlined
                single-line
                solo
                :value="value"
                @change="input(fieldName, $event)"
            >
            </v-autocomplete>

Body:
you need to use the slot 'no-data' like this :

<template v-slot:no-data>
   <div class="px-4">YOUR TEXT</div>
</template>


问:
async wait for element to load in so i can find it with jquery
i don't really understand async. i have a function like this:

function getTeam() {
    let sir = setInterval(() => {
        const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir)
          return firstTeam.trim()
        }
    }, 100)
}
```

im not js master.  i just want to get that element when it loads in,  this code is running in a userscript and // @run-at document-idle doesnt help either. i knew i would have to get into async js promises callbacks and whatever someday but i really dont understand how it works after pages of docs and other stackoverflow.
when i console.log this function it will print undefined once then if i have a console.log inside the if it will print the actual team name.
how do i wait for that result

答:
Answer regarding the javascript language part if the question

You could modify your code to the following (but don't - see further below - I'm just providing this as your StackOverflow tags included async/await):

async function getTeam() {
    return new Promise(resolve => {
      const sir = setInterval(() => {
        const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir);
          resolve(firstTeam.trim());
        }
      }, 100);
    });
}

// ... and then anywhere else in your code:
doSomethingSynchronous();
const team = await getTeam();
soSomethingSynchronousWithTeam(team);
```

Note that this will only work with modern browsers supporting >= ECMAScript 2017:
https://caniuse.com/async-functions (but luckily that's most by now!)

Answer regarding the implicit "howto wait for an element part"

... you really shouldn't actively wait for an element because this is unnecessarily heavy on the CPU. Usually you'll have some kind of event that informs you as soon as the element you're waiting for has been created. Just listen for that and then run your code.

What to do, if there's currently no such event:

If you're in control of the code creating the element, then trigger one yourself (see https://api.jquery.com/trigger/ for example).

If the element is created by a third party lib or by something else you cannot easily modify, you could use a MutationObserver (see this StackBlitz answer to a related question) and run your getTeam code only whenever something has changed instead of every 100ms (smaller impact on performance!)

Body:
i don't really understand async. i have a function like this:

function getTeam() {
    let sir = setInterval(() => {
        const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir)
          return firstTeam.trim()
        }
    }, 100)
}

im not js master.  i just want to get that element when it loads in,  this code is running in a userscript and // @run-at document-idle doesnt help either. i knew i would have to get into async js promises callbacks and whatever someday but i really dont understand how it works after pages of docs and other stackoverflow.
when i console.log this function it will print undefined once then if i have a console.log inside the if it will print the actual team name.
how do i wait for that result

Body:
Answer regarding the javascript language part if the question

You could modify your code to the following (but don't - see further below - I'm just providing this as your StackOverflow tags included async/await):

async function getTeam() {
    return new Promise(resolve => {
      const sir = setInterval(() => {
        const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir);
          resolve(firstTeam.trim());
        }
      }, 100);
    });
}

// ... and then anywhere else in your code:
doSomethingSynchronous();
const team = await getTeam();
soSomethingSynchronousWithTeam(team);

Note that this will only work with modern browsers supporting >= ECMAScript 2017:
https://caniuse.com/async-functions (but luckily that's most by now!)

Answer regarding the implicit "howto wait for an element part"

... you really shouldn't actively wait for an element because this is unnecessarily heavy on the CPU. Usually you'll have some kind of event that informs you as soon as the element you're waiting for has been created. Just listen for that and then run your code.

What to do, if there's currently no such event:

If you're in control of the code creating the element, then trigger one yourself (see https://api.jquery.com/trigger/ for example).

If the element is created by a third party lib or by something else you cannot easily modify, you could use a MutationObserver (see this StackBlitz answer to a related question) and run your getTeam code only whenever something has changed instead of every 100ms (smaller impact on performance!)


问:
QT -- QTLowEnergyService->discoverDetails() does not discover non standard characteristics
I am writing a QT application for BLE on windows 10. The windows application is a BLE central, while the peripheral is running on an iOS device (tablet or phone). I pretty much followed the low energy scanner example and I can find the iOS device with the UUID of interest. The problem is that when the service is discovered and after issuing the discoverDetails() to get a list of the characteristics, the QT state machine goes from DiscoveryRequired, DiscoveringServices, Invalid Service, and then it disconnects.

I know this is a QT problem because

I can connect and interact with the peripheral using other applications
https://apps.apple.com/us/app/lightblue/id557428110
https://www.microsoft.com/en-us/p/ble-scanner/9nblggh0j7m0#activetab=pivot:overviewtab

The BLE scanner app (written in C#) from Microsoft, when compiled and run on the same machine as QT, also is able to connect and interact with the iOS peripheral.

I have noticed that other people are had/have the same problem, but I don't see where/if a resolution/workaround was eventually found.
Qt - Cannot read descriptor of the characteristic - BLE

Here is my handler for the QLowEnergyService::ServiceState signal

```<code>void BleClient::serviceStateChanged(QLowEnergyService::ServiceState newState)
{
    switch (newState)
    {
        case QLowEnergyService::DiscoveringServices) :
        {
            // Nothing to do here, just note that we got into this state
            qDebug() << "Discovering services";
            break;
        }
        case QLowEnergyService::ServiceDiscovered:
        {
            qDebug() << "Service discovered";

            const QList<QLowEnergyCharacteristic> chars = m_currentService->characteristics();
            for (const QLowEnergyCharacteristic& ch : chars) {
                auto cInfo = new CharacteristicInfo(ch);
                m_characteristics.append(cInfo);
            }

            if (!chars.isValid()) {
                setMessage("Value for characteristic not found.");
                break;
            }

            m_notificationDesc = chars.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
            if (m_notificationDesc.isValid()) {
                m_service->writeDescriptor(m_notificationDesc, QByteArray::fromHex("0100"));
                setMessage("Characteristic enabled");
                m_start = QDateTime::currentDateTime();
            }

            break;
        }
        default:
            qDebug() << "Unhandled state received : (" << newState << ")";
    }
}
</code>```

答:
Ok, figured it out. Added more debug code and saw that a very descriptive error was being logged:

```<code>QLowEnergyService error: UnknownError
</code>```

Looking further, seems like , the QLowEnergyController needs a queued connection callback for the serviceDiscovered event to work as expected. So I changed

```<code>connect(controller, &QLowEnergyController::discoveryFinished, this, &BleClient::serviceScanDone);
</code>```

to

```<code>connect(controller, &QLowEnergyController::discoveryFinished, this, &BleClient::serviceScanDone, Qt::QueuedConnection);
</code>```

..and lo and behold, now I see all services with all the characteristics.

Body:
I am writing a QT application for BLE on windows 10. The windows application is a BLE central, while the peripheral is running on an iOS device (tablet or phone). I pretty much followed the low energy scanner example and I can find the iOS device with the UUID of interest. The problem is that when the service is discovered and after issuing the discoverDetails() to get a list of the characteristics, the QT state machine goes from DiscoveryRequired, DiscoveringServices, Invalid Service, and then it disconnects.

I know this is a QT problem because

I can connect and interact with the peripheral using other applications
https://apps.apple.com/us/app/lightblue/id557428110
https://www.microsoft.com/en-us/p/ble-scanner/9nblggh0j7m0#activetab=pivot:overviewtab

The BLE scanner app (written in C#) from Microsoft, when compiled and run on the same machine as QT, also is able to connect and interact with the iOS peripheral.

I have noticed that other people are had/have the same problem, but I don't see where/if a resolution/workaround was eventually found.
Qt - Cannot read descriptor of the characteristic - BLE

Here is my handler for the QLowEnergyService::ServiceState signal

void BleClient::serviceStateChanged(QLowEnergyService::ServiceState newState)
{
    switch (newState)
    {
        case QLowEnergyService::DiscoveringServices) :
        {
            // Nothing to do here, just note that we got into this state
            qDebug() << "Discovering services";
            break;
        }
        case QLowEnergyService::ServiceDiscovered:
        {
            qDebug() << "Service discovered";

            const QList<QLowEnergyCharacteristic> chars = m_currentService->characteristics();
            for (const QLowEnergyCharacteristic& ch : chars) {
                auto cInfo = new CharacteristicInfo(ch);
                m_characteristics.append(cInfo);
            }

            if (!chars.isValid()) {
                setMessage("Value for characteristic not found.");
                break;
            }

            m_notificationDesc = chars.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
            if (m_notificationDesc.isValid()) {
                m_service->writeDescriptor(m_notificationDesc, QByteArray::fromHex("0100"));
                setMessage("Characteristic enabled");
                m_start = QDateTime::currentDateTime();
            }

            break;
        }
        default:
            qDebug() << "Unhandled state received : (" << newState << ")";
    }
}

Body:
Ok, figured it out. Added more debug code and saw that a very descriptive error was being logged:

QLowEnergyService error: UnknownError

Looking further, seems like , the QLowEnergyController needs a queued connection callback for the serviceDiscovered event to work as expected. So I changed

connect(controller, &QLowEnergyController::discoveryFinished, this, &BleClient::serviceScanDone);

to

connect(controller, &QLowEnergyController::discoveryFinished, this, &BleClient::serviceScanDone, Qt::QueuedConnection);

..and lo and behold, now I see all services with all the characteristics.


问:
can't get odbc working in apache
I installed unixODBC by using apt-get install, and now when I try to use odbc_connect() is still get this error.

```<code>PHP Fatal error:  Call to undefined function odbc_connect()
</code>```

what do i need to do to configure it to work with php?  I have been looking online but I can't really figure it out.

答: I think you need to install php5-odbc also. unixODBC provides the driver manager, but you need the PHP code that calls it.</p>

ContentLicense: CC BY-SA 3.0

Title: can't get odbc working in apache

Body:
I installed unixODBC by using apt-get install, and now when I try to use odbc_connect() is still get this error.

PHP Fatal error:  Call to undefined function odbc_connect()

what do i need to do to configure it to work with php?  I have been looking online but I can't really figure it out.


答:
You can make it async if you want, but the main part us going to be using events instead. There is a special object called mutation observer. It will call a function you give it any time there's a change in the element you're observing.

Check the mutation observer docs to understand the code below: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Without knowing much about your HTML, I can say as much as this should work:

```<code>function getTeam() {
  const teamsGrid = $('[class*="teamsgrid"]').find("p");
  const firstTeam = $(teamsGrid[0]).text();
  if (firstTeam != '') {
    return firstTeam.trim()
  }
}

function getTeamWhenAvailable() {
  // returning a promise allows you to do "await" and get result when it is available
  return new Promise((resolve, reject) => {
    // furst try if element is available right now
    const teamText = getTeam();
    if(teamText) {
      // resolve() "returns" the value to whoever is doing "await"
      resolve(teamText);
      // resolve does not terminate this function, we need to do that using return
      return;
    }

    // Mutation observer gives you list of stuff that changed, but we don't care, we just do our own thing
    const observer = new MutationObserver(()=>{
          const teamText = getTeam();
          if(teamText) {
            // stop observing
            observer.disconnect();
            // resolve the value
            resolve(teamText);
          }
    });
    observer.observe(document.body, { childList: true, subtree: true };
  })
}

// usage, the extra brackets around the lambda cause it to invoke immediatelly

(async () => {
  console.log("Waitinf for team...");
  const teamName = await getTeamWhenAvailable();
  console.log("Result team name: ", teamName)
})();
</code>```

Now you might wanna narrow the scope of the mutation observer, in the example above it watches the entire document. Try to instead observe the deepest element that you can rely on not being removed.

If you need to receive team name multiple times, I think you should just go with the obsever alone without the async stuff.

Title: async wait for element to load in so i can find it with jquery

Body:
You can make it async if you want, but the main part us going to be using events instead. There is a special object called mutation observer. It will call a function you give it any time there's a change in the element you're observing.

Check the mutation observer docs to understand the code below: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Without knowing much about your HTML, I can say as much as this should work:

function getTeam() {
  const teamsGrid = $('[class*="teamsgrid"]').find("p");
  const firstTeam = $(teamsGrid[0]).text();
  if (firstTeam != '') {
    return firstTeam.trim()
  }
}

function getTeamWhenAvailable() {
  // returning a promise allows you to do "await" and get result when it is available
  return new Promise((resolve, reject) => {
    // furst try if element is available right now
    const teamText = getTeam();
    if(teamText) {
      // resolve() "returns" the value to whoever is doing "await"
      resolve(teamText);
      // resolve does not terminate this function, we need to do that using return
      return;
    }

    // Mutation observer gives you list of stuff that changed, but we don't care, we just do our own thing
    const observer = new MutationObserver(()=>{
          const teamText = getTeam();
          if(teamText) {
            // stop observing
            observer.disconnect();
            // resolve the value
            resolve(teamText);
          }
    });
    observer.observe(document.body, { childList: true, subtree: true };
  })
}

// usage, the extra brackets around the lambda cause it to invoke immediatelly

(async () => {
  console.log("Waitinf for team...");
  const teamName = await getTeamWhenAvailable();
  console.log("Result team name: ", teamName)
})();

Now you might wanna narrow the scope of the mutation observer, in the example above it watches the entire document. Try to instead observe the deepest element that you can rely on not being removed.

If you need to receive team name multiple times, I think you should just go with the obsever alone without the async stuff.


问:
Can't load tidyverse library
Just upgraded R and RStudio to

```<code>> version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          4.0
year           2017
month          04
day            21
svn rev        72570
language       R
version.string R version 3.4.0 (2017-04-21)
nickname       You Stupid Darkness
</code>```

The rstudio version is

```<code>Version 1.0.143 – © 2009-2016 RStudio, Inc.
</code>```

Then I install the tidyverse package

```<code>install.packages("tidyverse")
</code>```

results in

```<code>trying URL 'https://dirichlet.mat.puc.cl/bin/windows/contrib/3.4/tidyverse_1.1.1.zip'
Content type 'application/zip' length 42211 bytes (41 KB)
downloaded 41 KB

package ‘tidyverse’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\...\AppData\Local\Temp\Rtmp6vaNT1\downloaded_packages
</code>```

Everything OK.

Now, when trying to load the tidyverse library:

```<code>> library("tidyverse")
Error: package or namespace load failed for ‘tidyverse’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
 there is no package called ‘cellranger’
</code>```

Fail.

I can load all the packages individually, but for some reason not the tidyverse package.

答:
This will resolve your problem</p>
```<code>install.packages('cellranger')
install.packages('tidyverse', type = 'binary')
</code>```

Title: Can't load tidyverse library

Body:
Just upgraded R and RStudio to

> version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          4.0
year           2017
month          04
day            21
svn rev        72570
language       R
version.string R version 3.4.0 (2017-04-21)
nickname       You Stupid Darkness

The rstudio version is

Version 1.0.143 – © 2009-2016 RStudio, Inc.

Then I install the tidyverse package

install.packages("tidyverse")

results in

trying URL 'https://dirichlet.mat.puc.cl/bin/windows/contrib/3.4/tidyverse_1.1.1.zip'
Content type 'application/zip' length 42211 bytes (41 KB)
downloaded 41 KB

package ‘tidyverse’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\...\AppData\Local\Temp\Rtmp6vaNT1\downloaded_packages

Everything OK.

Now, when trying to load the tidyverse library:

> library("tidyverse")
Error: package or namespace load failed for ‘tidyverse’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
 there is no package called ‘cellranger’

Fail.

I can load all the packages individually, but for some reason not the tidyverse package.

Body:
This will resolve your problem

install.packages('cellranger')
install.packages('tidyverse', type = 'binary')


问:
Unable to use vagrant ssh on a custom box
I have successfully created a custom Vagrant box, based on the official ubuntu/xenial64 Vagrant box, but I get this message when I attempt to use vagrant ssh:

```<code>==> default: The machine you're attempting to SSH into is configured to use
==> default: password-based authentication. Vagrant can't script entering the
==> default: password for you. If you're prompted for a password, please enter
==> default: the same password you have configured in the Vagrantfile.
</code>```

The only change to the box is to provision it with NginX. I then use...

```<code>vagrant package --vagrantfile <path_to_vagrantfile> --output nginx.box
</code>```

... where <path_to_vagrantfile> is, in my case, /home/blackslate/.vagrant.d/boxes/ubuntu-VAGRANTSLASH-xenial64/20170822.0.0/virtualbox/Vagrantfile. I follow this with:

```<code>vagrant box add nginx nginx.box
</code>```

I then create a new directory and use vagrant init nginx to create a new instance of the box. The whole process is described in this question.

When I use vagrant up, all appears to be running as expected:

```<code>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'nginx'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: Custom_default_1503826905856_10643
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: ubuntu
    default: SSH auth method: password
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => /home/blackslate/repos/Vagrant/Custom
</code>```

However, vagrant ssh provokes the message at the beginning of this question. When I try to ssh in manually, using "ubuntu" as the ssh user and "vagrant" as the password, I get this:

```<code>ssh ubuntu@127.0.0.1
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:PSnauymZfKi1HIRIKfez5wAnpPFJW9h3eC+TzxiiIWA.
Are you sure you want to continue connecting (yes/no)? y
Please type 'yes' or 'no': yes
Warning: Permanently added '127.0.0.1' (ECDSA) to the list of known hosts.
ubuntu@127.0.0.1's password:
Permission denied, please try again.
ubuntu@127.0.0.1's password:
</code>```

I get a similar result if I try ssh vagrant@127.0.0.1:

```<code>ssh vagrant@127.0.0.1
vagrant@127.0.0.1's password:
Permission denied, please try again.
vagrant@127.0.0.1's password:
</code>```

The same is true if I open the VirtualBox GUI and talk to the VM directly.

I have tried following the instructions here, but I'm guessing that this refers to an older version of Vagrant.

I am hoping that I will be able to make changes at the package stage, so that when I distribute the custom Vagrant box to other developers, vagrant ssh just works, with no need to massage any files beforehand.

答: Try using the Oracle Virtual Box Manager to log in directly console instead of with ssh.  Thereupon may edit the sshd config file and allow the passoword authentication.  Restart SSHD service.</p>

Body:
I have successfully created a custom Vagrant box, based on the official ubuntu/xenial64 Vagrant box, but I get this message when I attempt to use vagrant ssh:

==> default: The machine you're attempting to SSH into is configured to use
==> default: password-based authentication. Vagrant can't script entering the
==> default: password for you. If you're prompted for a password, please enter
==> default: the same password you have configured in the Vagrantfile.

The only change to the box is to provision it with NginX. I then use...

vagrant package --vagrantfile <path_to_vagrantfile> --output nginx.box

... where <path_to_vagrantfile> is, in my case, /home/blackslate/.vagrant.d/boxes/ubuntu-VAGRANTSLASH-xenial64/20170822.0.0/virtualbox/Vagrantfile. I follow this with:

vagrant box add nginx nginx.box

I then create a new directory and use vagrant init nginx to create a new instance of the box. The whole process is described in this question.

When I use vagrant up, all appears to be running as expected:

vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'nginx'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: Custom_default_1503826905856_10643
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: ubuntu
    default: SSH auth method: password
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => /home/blackslate/repos/Vagrant/Custom

However, vagrant ssh provokes the message at the beginning of this question. When I try to ssh in manually, using "ubuntu" as the ssh user and "vagrant" as the password, I get this:

ssh ubuntu@127.0.0.1
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:PSnauymZfKi1HIRIKfez5wAnpPFJW9h3eC+TzxiiIWA.
Are you sure you want to continue connecting (yes/no)? y
Please type 'yes' or 'no': yes
Warning: Permanently added '127.0.0.1' (ECDSA) to the list of known hosts.
ubuntu@127.0.0.1's password:
Permission denied, please try again.
ubuntu@127.0.0.1's password:

I get a similar result if I try ssh vagrant@127.0.0.1:

ssh vagrant@127.0.0.1
vagrant@127.0.0.1's password:
Permission denied, please try again.
vagrant@127.0.0.1's password:

The same is true if I open the VirtualBox GUI and talk to the VM directly.

I have tried following the instructions here, but I'm guessing that this refers to an older version of Vagrant.

I am hoping that I will be able to make changes at the package stage, so that when I distribute the custom Vagrant box to other developers, vagrant ssh just works, with no need to massage any files beforehand.


问:
Google Cloud APIs - Python - Request contains an invalid argument
Using Google Cloud APIs and Oauth2, I am trying to list down projects and display IAM Policies for each project using my Python Desktop app. Sample code is below:

```<code>appflow = flow.InstalledAppFlow.from_client_secrets_file("client_secrets.json",
scopes=["https://www.googleapis.com/auth/cloud-platform"])

appflow.run_console()

credentials = appflow.credentials

service = googleapiclient.discovery.build(
    'cloudresourcemanager', 'v1',  credentials=credentials)

operation1 = service.projects().list().execute()

jason=json.dumps(
    operation1,
    sort_keys=True,
    indent=3)
data = json.loads(jason)

#Gets the list of projects in a Python List object [Proj]

proj=[]
for mem in data['projects']:
    print(mem['projectId'])
    proj.append(mem['projectId'])

for prj in proj:
    resource = 'projects/' + prj

    response1 = service.projects().testIamPermissions(resource=resource, body=None, x__xgafv=None).execute()

    response2 = service.projects().listOrgPolicies(resource=resource, body=None, x__xgafv=None).execute()

    response3 = service.projects().getIamPolicy(resource=resource, body=None, x__xgafv=None).execute()
</code>```

I get the similar error for all the 3 calls:
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://cloudresourcemanager.googleapis.com/v1/projects/projects%2Fproject-name:testIamPermissions?alt=json returned "Request contains an invalid argument.". Details: "Request contains an invalid argument.">

Arguments appear to be correct. Does the service(cloudresourcemanager) version v1/v3 make a difference? Am I missing something? Thanks in Advance.

答:
I think you should not need to parse the resource with projects/ like the HTTPS example because you are using the library that should be abstract this for you, so if you remove resource = 'projects/' + prj and try the call directly with the project id instead

```<code>response1 = service.projects().testIamPermissions(resource=prj, body=None, x__xgafv=None).execute()

response2 = service.projects().listOrgPolicies(resource=prj, body=None, x__xgafv=None).execute()

response3 = service.projects().getIamPolicy(resource=prj, body=None, x__xgafv=None).execute()
</code>```

If it worked, you should no longer get error 400, but rather 403 "permission denied" because you are missing some of the scopes for those API calls(based on your code example).

The example google provided

testIamPermissions

listOrgPolicies

getIamPolicy

Body:
Using Google Cloud APIs and Oauth2, I am trying to list down projects and display IAM Policies for each project using my Python Desktop app. Sample code is below:

appflow = flow.InstalledAppFlow.from_client_secrets_file("client_secrets.json",
scopes=["https://www.googleapis.com/auth/cloud-platform"])

appflow.run_console()

credentials = appflow.credentials

service = googleapiclient.discovery.build(
    'cloudresourcemanager', 'v1',  credentials=credentials)

operation1 = service.projects().list().execute()

jason=json.dumps(
    operation1,
    sort_keys=True,
    indent=3)
data = json.loads(jason)

#Gets the list of projects in a Python List object [Proj]

proj=[]
for mem in data['projects']:
    print(mem['projectId'])
    proj.append(mem['projectId'])

for prj in proj:
    resource = 'projects/' + prj

    response1 = service.projects().testIamPermissions(resource=resource, body=None, x__xgafv=None).execute()

    response2 = service.projects().listOrgPolicies(resource=resource, body=None, x__xgafv=None).execute()

    response3 = service.projects().getIamPolicy(resource=resource, body=None, x__xgafv=None).execute()

I get the similar error for all the 3 calls:
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://cloudresourcemanager.googleapis.com/v1/projects/projects%2Fproject-name:testIamPermissions?alt=json returned "Request contains an invalid argument.". Details: "Request contains an invalid argument.">

Arguments appear to be correct. Does the service(cloudresourcemanager) version v1/v3 make a difference? Am I missing something? Thanks in Advance.

Body:
I think you should not need to parse the resource with projects/ like the HTTPS example because you are using the library that should be abstract this for you, so if you remove resource = 'projects/' + prj and try the call directly with the project id instead

response1 = service.projects().testIamPermissions(resource=prj, body=None, x__xgafv=None).execute()

response2 = service.projects().listOrgPolicies(resource=prj, body=None, x__xgafv=None).execute()

response3 = service.projects().getIamPolicy(resource=prj, body=None, x__xgafv=None).execute()

If it worked, you should no longer get error 400, but rather 403 "permission denied" because you are missing some of the scopes for those API calls(based on your code example).

The example google provided

testIamPermissions

listOrgPolicies

getIamPolicy


问:
Slow SQL Query / Displaying (PHP / jQuery)
I have a request to get data in my mySQL database (36,848 entries).
Then I format and append them with jQuery on my web page.

These two operations take 2 minutes and 30 seconds.
During this time, no other operation is possible on the page.

Is there a way to optimize this to speed up the process?
Like this, it's unusable.

My PHP function

```<code><?php
function get_my_customers() {
    $req = $bdd->prepare("SELECT * FROM clients ORDER BY raison_sociale");
    $req->execute();
    $customers = $req->fetchAll(PDO::FETCH_ASSOC);

    return $customers;
}

if(isset($_POST['ajax'])){
    $result = get_my_customers();
    echo json_encode($result);
}
?>
</code>```

Data retrieval in jQuery (Ajax)

```<code>function get_my_customers(){
    var customers;
    $.ajax({
        url: "model/application/*******/customers/get_my_customers.php",
        async: false,
        type: "POST",
        dataType: 'json',
        data: {ajax: 'true'},
        success: function(data)
        {
            customers = data;
        }
    });
    return customers;
}

var my_customers = get_my_customers();

$('#customers_list').append('<div class="list_card" card="customers_list"></div>');

$.each(my_customers, function(key, val){
    if(val.enseigne == null){
        var enseigne = '';
    }else{
        var enseigne = ',' + val.enseigne;
    }

    $('.list_card[card="customers_list"]').append(''+
        '<div class="list_card_element">'+
            '<div><b>'+ val.numero_client +'</b></div>'+
            '<div>'+
                '<b>'+ val.raison_sociale +'</b>' + enseigne +
                '<br>'+
                val.cp_livraison + ', ' + val.adresse_livraison +
            '</div>'+
        '</div>'
    );
});
</code>```

Do you know what I can do to speed up processing time?
I've tried limiting the SELECT query to only the fields I need but that doesn't improve processing time.

I wonder if it's not rather the jQuery layout that takes time rather than the SQL query.

Thank you !

答:
I just passed from 2 minutes and 30 secondes to 14 secondes with this optimization.

```<code>var construct_customers = "";

$.each(my_customers, function(key, val){
    if(val.enseigne == null){
        var enseigne = '';
    }else{
        var enseigne = ',' + val.enseigne;
    }

    construct_customers += '<div class="list_card_element">'+'<div><b>'+ val.numero_client +'</b></div>'+'<div>'+'<b>'+ val.raison_sociale +'</b>' + enseigne +'<br>'+val.cp_livraison + ', ' + val.adresse_livraison +'</div>'+'</div>';

    //OLD CODE
    // $('.list_card[card="customers_list"]').append(''+
    //     '<div class="list_card_element">'+
    //         '<div><b>'+ val.numero_client +'</b></div>'+
    //         '<div>'+
    //             '<b>'+ val.raison_sociale +'</b>' + enseigne +
    //             '<br>'+
    //             val.cp_livraison + ', ' + val.adresse_livraison +
    //         '</div>'+
    //     '</div>'
    // );
});

$('.list_card[card="customers_list"]').append(construct_customers);
</code>```

I'm impressed

Body:
I have a request to get data in my mySQL database (36,848 entries).
Then I format and append them with jQuery on my web page.

These two operations take 2 minutes and 30 seconds.
During this time, no other operation is possible on the page.

Is there a way to optimize this to speed up the process?
Like this, it's unusable.

My PHP function

<?php
function get_my_customers() {
    $req = $bdd->prepare("SELECT * FROM clients ORDER BY raison_sociale");
    $req->execute();
    $customers = $req->fetchAll(PDO::FETCH_ASSOC);

    return $customers;
}

if(isset($_POST['ajax'])){
    $result = get_my_customers();
    echo json_encode($result);
}
?>

Data retrieval in jQuery (Ajax)

function get_my_customers(){
    var customers;
    $.ajax({
        url: "model/application/*******/customers/get_my_customers.php",
        async: false,
        type: "POST",
        dataType: 'json',
        data: {ajax: 'true'},
        success: function(data)
        {
            customers = data;
        }
    });
    return customers;
}

var my_customers = get_my_customers();

$('#customers_list').append('

');

$.each(my_customers, function(key, val){
    if(val.enseigne == null){
        var enseigne = '';
    }else{
        var enseigne = ',' + val.enseigne;
    }

    $('.list_card[card="customers_list"]').append(''+
        '
'+
            '
'+ val.numero_client +'
'+
            '
'+
                ''+ val.raison_sociale +'' + enseigne +
                '
'+
                val.cp_livraison + ', ' + val.adresse_livraison +
            '
'+
        '
'
    );
});

Do you know what I can do to speed up processing time?
I've tried limiting the SELECT query to only the fields I need but that doesn't improve processing time.

I wonder if it's not rather the jQuery layout that takes time rather than the SQL query.

Thank you !

Body:
I just passed from 2 minutes and 30 secondes to 14 secondes with this optimization.

var construct_customers = "";

$.each(my_customers, function(key, val){
    if(val.enseigne == null){
        var enseigne = '';
    }else{
        var enseigne = ',' + val.enseigne;
    }

    construct_customers += '<div class="list_card_element">'+'<div><b>'+ val.numero_client +'</b></div>'+'<div>'+'<b>'+ val.raison_sociale +'</b>' + enseigne +'<br>'+val.cp_livraison + ', ' + val.adresse_livraison +'</div>'+'</div>';

    //OLD CODE
    // $('.list_card[card="customers_list"]').append(''+
    //     '<div class="list_card_element">'+
    //         '<div><b>'+ val.numero_client +'</b></div>'+
    //         '<div>'+
    //             '<b>'+ val.raison_sociale +'</b>' + enseigne +
    //             '<br>'+
    //             val.cp_livraison + ', ' + val.adresse_livraison +
    //         '</div>'+
    //     '</div>'
    // );
});

$('.list_card[card="customers_list"]').append(construct_customers);

I'm impressed


问:
There is a mode to run a nodejs backend on android?
I will try to explain better, I made a NodeJS backend with integrated react UI that call localhost for local API/function integrated in NodeJS. Is there a way to make a porting of this solution to an APK? For now the only way to make NodeJS works on android is manually or with obsolete library like Androidjs</p>

答: Yes we can use Node.js using Termux however it is not quite recommended to run  a backend server on Android.</p>


问:
How to retrieve a column that appear in multiple rows based on a condition with pandas?
I am using a large IMDB dataset to do some practicing.

df_movies[(df_movies['movie'] == 'Fight Club (1999)') | (df_movies['movie'] == 'Se7en (1995)')].value_counts('actor')
```
<p>The above query has given me this dataset.</p>
```
movie   actor   year    duration    adult_movie rating  votes
3506    Se7en (1995)    Brad Pitt (b.1963)  1995    127.0   0   8.6 1342867.0
3513    Fight Club (1999)   Brad Pitt (b.1963)  1999    139.0   0   8.8 1742920.0
5380    Se7en (1995)    Morgan Freeman (b.1937) 1995    127.0   0   8.6 1342867.0
8065    Se7en (1995)    Kevin Spacey (b.1959)   1995    127.0   0   8.6 1342867.0
40124   Fight Club (1999)   Meat Loaf (b.1947)  1999    139.0   0   8.8 1742920.0
40905   Fight Club (1999)   Edward Norton (b.1969)  1999    139.0   0   8.8 1742920.0
46730   Se7en (1995)    Andrew Kevin Walker (b.1964)    1995    127.0   0   8.6 1342867.0
390010  Fight Club (1999)   Zach Grenier (b.1954)   1999    139.0   0   8.8 1742920.0
```

Brad Pitt  is the only actor on this list to appear in both movies. How can I filter it such that Brad Pitt is returned?

答:
Using pd.value_counts(), you can obtain the number of occurrences of each actor in the list.  The result is sorted from highest to lowest.

```<code>df.drop_duplicates(['movie', 'actor'])['actor'].value_counts().index[0]
</code>```

Body:
I am using a large IMDB dataset to do some practicing.

df_movies[(df_movies['movie'] == 'Fight Club (1999)') | (df_movies['movie'] == 'Se7en (1995)')].value_counts('actor')

The above query has given me this dataset.

movie   actor   year    duration    adult_movie rating  votes
3506    Se7en (1995)    Brad Pitt (b.1963)  1995    127.0   0   8.6 1342867.0
3513    Fight Club (1999)   Brad Pitt (b.1963)  1999    139.0   0   8.8 1742920.0
5380    Se7en (1995)    Morgan Freeman (b.1937) 1995    127.0   0   8.6 1342867.0
8065    Se7en (1995)    Kevin Spacey (b.1959)   1995    127.0   0   8.6 1342867.0
40124   Fight Club (1999)   Meat Loaf (b.1947)  1999    139.0   0   8.8 1742920.0
40905   Fight Club (1999)   Edward Norton (b.1969)  1999    139.0   0   8.8 1742920.0
46730   Se7en (1995)    Andrew Kevin Walker (b.1964)    1995    127.0   0   8.6 1342867.0
390010  Fight Club (1999)   Zach Grenier (b.1954)   1999    139.0   0   8.8 1742920.0

Brad Pitt  is the only actor on this list to appear in both movies. How can I filter it such that Brad Pitt is returned?

Body:
Using pd.value_counts(), you can obtain the number of occurrences of each actor in the list.  The result is sorted from highest to lowest.

df.drop_duplicates(['movie', 'actor'])['actor'].value_counts().index[0]


问:
How to invoke a REST API when an object arrives on S3?
S3 can be configured to invoke lambda when an object arrives in it.

Is it possible to invoke a REST API (endpoint of a microservice running in EKS) when an object arrives in S3?

答: Have the Lambda hit the REST API for you.</p>


答:
Step 1 would be declaring a model

public class Data
{
    public DateTime date { get; set; }
    public int someID { get; set; }
    public string someType1 { get; set; }
    public string someType2 { get; set; }
}
```
<p>Step 2 - deserialize JSON, in this case, using Newtonsoft</p>
<pre class="lang-cs prettyprint-override"><code>var dataList = JsonConvert.DeserializeObject<Data>(json);
</code>```

Step 3 - produce result

var output = dataList.GroupBy(m => (m.date, m.someID, m.someType1, m.someType2))
    .Select(g => new
        {
            date = g.Key.date,
            someID = g.Key.someID,
            someType1 = g.Key.someType1,
            someType2 = g.Key.someType2,
            objCount = g.Count()
        });
```

2 things - potentially LINQ syntax is different for different versions of c#. And you might need to declare a special model for the output.

Title: Find Duplicate Objects in JSON Array

Body:
I am relatively new to c# and need some guidance. I need to search through a large json array to find duplicate objects and list how many occurrences.

Sample Array

{
    "data":
        [
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND"
          }

        ]
}

I have been able to search through and find duplicate elements but not the complete object. The output should be:

{
    "result":
        [
          {
            "date": "20220101",
            "someID": "ID1",
            "someType1": "SRVC",
            "someType2": "SEND",
            "objCount": 2
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "RECV",
            "objCount": 3
          },
          {
            "date": "20220101",
            "someID": "ID2",
            "someType1": "SRVC",
            "someType2": "SEND",
            "objCount": 3
          }

        ]
}

Any help to point me in the right direction would be great. Thanks in advance

Body:
Step 1 would be declaring a model

public class Data
{
    public DateTime date { get; set; }
    public int someID { get; set; }
    public string someType1 { get; set; }
    public string someType2 { get; set; }
}

Step 2 - deserialize JSON, in this case, using Newtonsoft

var dataList = JsonConvert.DeserializeObject<Data>(json);

Step 3 - produce result

var output = dataList.GroupBy(m => (m.date, m.someID, m.someType1, m.someType2))
    .Select(g => new
        {
            date = g.Key.date,
            someID = g.Key.someID,
            someType1 = g.Key.someType1,
            someType2 = g.Key.someType2,
            objCount = g.Count()
        });

2 things - potentially LINQ syntax is different for different versions of c#. And you might need to declare a special model for the output.


问:
How to handle push notifications when the user is not logged in?
I am confused about how to handle notifications in the react-native app if the user is not logged in. I send push notifications via OneSignal to the application but if a user is not logged in I should not send a notification, how can I check user is logged in or not?</p>

答: When logging out, you can try to call OneSignal.removeExternalUser() method. And logging in, OneSignal.setExternalUserId(userId).


问:
Mock open feign response body
I have a code as shown

MyDefinition databricksResponseBody = null;
ResponseBody = gson.fromJson(Response.body().asReader(), MyDefinition.class);
```

Now to mock this I am using Mockito. I already mocked the header of this response but unable to mock the body. Confused about how to achieve that? Tried but failed.

responseMock.headers().put("xxxxxx", headerValues);

答:
To mock a final class or method, you need to add a text file to the project's src/test/resources/mockito-extensions directory named org.mockito.plugins.MockMaker and add a single line of text:

```<code>mock-maker-inline
</code>```

Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.

Then, you should mock your Response as bellow. You can also mock the other fields of response.

```<code>Response response = mock(Response.class);
Response.Body body = mock(Response.Body.class);
when(response.body()).thenReturn(body);
</code>```

More details in this link:
https://www.baeldung.com/mockito-final#configure-mocktio

Title: Mock open feign response body

Body:
I have a code as shown

MyDefinition databricksResponseBody = null;
ResponseBody = gson.fromJson(Response.body().asReader(), MyDefinition.class);

Now to mock this I am using Mockito. I already mocked the header of this response but unable to mock the body. Confused about how to achieve that? Tried but failed.

responseMock.headers().put("xxxxxx", headerValues);

Body:
To mock a final class or method, you need to add a text file to the project's src/test/resources/mockito-extensions directory named org.mockito.plugins.MockMaker and add a single line of text:

mock-maker-inline

Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.

Then, you should mock your Response as bellow. You can also mock the other fields of response.

Response response = mock(Response.class);
Response.Body body = mock(Response.Body.class);
when(response.body()).thenReturn(body);

More details in this link:
https://www.baeldung.com/mockito-final#configure-mocktio


问:
How to call a stored procedure that has several types in C# on .NET Core
I wrote a stored procedure that takes two types I created as parameters, called Type1 and Type2 :

```<code>CREATE TYPE Type1 AS TABLE
(
    Id [int] NULL,
    Value [float] NULL
)

CREATE TYPE Type2 AS TABLE
(
    Id [int] NULL,
    Name [varchar](20) NULL,
    Value [float] NULL
)

CREATE PROCEDURE [SP-Name]
    (@Id INT = 1,
     @UserName VARCHAR(500) = 'test',
     @Item1 Type1 READONLY,
     @Item2 Type2 READONLY)
AS
BEGIN
    SELECT *
    FROM @Item1
END;
</code>```

When I call this stored procedure in SQL Server itself, it runs without error, but I write the same code in C#, I get an error. What is the problem?

This is how I call this stored procedure in C#:

```<code>ENTITIES.SqlQuery<Result>($"EXEC [SP-Name] @Item1",
      new[] {
               new SqlParameter
               {
                   SqlDbType = SqlDbType.Structured,
                   TypeName = "Type1",
                   Value = listItems.ToDataTable(),//Get list Item from database and Convert to DATA-TABLE
                   ParameterName = "Item1"
               }}).ToList();

public class Result
{
    public int Id { get; set; }
    public string Value { get; set; }
}

public static DataTable ToDataTable<T>(this List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        // Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo prop in Props)
        {
            // Defining type of data column gives proper data table
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);

            // Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }

        foreach (T item in items)
        {
            var values = new object[Props.Length];

            for (int i = 0; i < Props.Length; i++)
            {
                // inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
            }

            dataTable.Rows.Add(values);
        }

        // put a breakpoint here and check datatable
        return dataTable;
    }
</code>```

This is the error I get:

Operand type clash: Item1 is incompatible with int

答:
The problem here is you think that because you have a variable called @Item1 that it will be inferred, by SQL Server, to be for the parameter @Item1, as they share the same name; this assumption is wrong.

When you omit the parameter that the variable is being passed to, the variables (or literals) are passed to the parameters based on ordinal position. You pass one value for your parameters, @Item1, which will be passed to your first parameter, @Id. This is why you get an error. @Item1 is defined as a structured data type (SqlDbType.Structured), but @Id is an int; there are not the same data types, and you get an error.

If you want to omit parameters, be explicit on the parameters you are passing:

ENTITIES.SqlQuery<Result>($"EXEC dbo.[SP-Name] @Item1 = @Item1;",
```
<p>Or, probably better, just remove all the other parameters from the procedure, as you don't use them:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE PROCEDURE dbo.[SP-Name] @Item1 Type1 READONLY
AS
BEGIN
    SELECT *
    FROM @Item1;
END;
</code>```

Then you can use use EXEC dbo.[SP-Name] @Item1;.

Body:
I wrote a stored procedure that takes two types I created as parameters, called Type1 and Type2 :

CREATE TYPE Type1 AS TABLE
(
    Id [int] NULL,
    Value [float] NULL
)

CREATE TYPE Type2 AS TABLE
(
    Id [int] NULL,
    Name [varchar](20) NULL,
    Value [float] NULL
)

CREATE PROCEDURE [SP-Name]
    (@Id INT = 1,
     @UserName VARCHAR(500) = 'test',
     @Item1 Type1 READONLY,
     @Item2 Type2 READONLY)
AS
BEGIN
    SELECT *
    FROM @Item1
END;

When I call this stored procedure in SQL Server itself, it runs without error, but I write the same code in C#, I get an error. What is the problem?

This is how I call this stored procedure in C#:

ENTITIES.SqlQuery<Result>($"EXEC [SP-Name] @Item1",
      new[] {
               new SqlParameter
               {
                   SqlDbType = SqlDbType.Structured,
                   TypeName = "Type1",
                   Value = listItems.ToDataTable(),//Get list Item from database and Convert to DATA-TABLE
                   ParameterName = "Item1"
               }}).ToList();

public class Result
{
    public int Id { get; set; }
    public string Value { get; set; }
}

public static DataTable ToDataTable<T>(this List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        // Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo prop in Props)
        {
            // Defining type of data column gives proper data table
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);

            // Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }

        foreach (T item in items)
        {
            var values = new object[Props.Length];

            for (int i = 0; i < Props.Length; i++)
            {
                // inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
            }

            dataTable.Rows.Add(values);
        }

        // put a breakpoint here and check datatable
        return dataTable;
    }

This is the error I get:

Operand type clash: Item1 is incompatible with int

Body:
The problem here is you think that because you have a variable called @Item1 that it will be inferred, by SQL Server, to be for the parameter @Item1, as they share the same name; this assumption is wrong.

When you omit the parameter that the variable is being passed to, the variables (or literals) are passed to the parameters based on ordinal position. You pass one value for your parameters, @Item1, which will be passed to your first parameter, @Id. This is why you get an error. @Item1 is defined as a structured data type (SqlDbType.Structured), but @Id is an int; there are not the same data types, and you get an error.

If you want to omit parameters, be explicit on the parameters you are passing:

ENTITIES.SqlQuery<Result>($"EXEC dbo.[SP-Name] @Item1 = @Item1;",

Or, probably better, just remove all the other parameters from the procedure, as you don't use them:

CREATE PROCEDURE dbo.[SP-Name] @Item1 Type1 READONLY
AS
BEGIN
    SELECT *
    FROM @Item1;
END;

Then you can use use EXEC dbo.[SP-Name] @Item1;.


问:
Discord.py | Command That Randomly Gives Role
I am trying to make a command that rarely gives a role (with a cooldown). However, when I try to run my code, it does not work, can anyone help to improve my code?

```<code>import discord
from discord.ext import commands
from discord.utils import get
import random

bot = commands.Bot(command_prefix=">")

...

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error,commands.CommandOnCooldown):
        msg = 'wait for a while {:.2f}s'.format(error.retry_after)
        await ctx.send(msg)

@bot.command(pass_context=True)
@commands.cooldown(1, 86400, commands.BucketType.user)
@commands.has_role("Mod")
async def addrole(ctx):
    if random.randint(1, 10000) < 2:
        member = ctx.message.author
        role = get(member.server.roles, name="Mod")
        await bot.add_roles(member, role)

    else:
        await bot.channel.send("you did not get mod")

bot.run(TOKEN HERE)
</code>```

I am trying to make it a 0.01% chance of them getting the role. Thanks!

答: bot.add_roles is invalid syntax, commands.Bot object does not have a add_roles method. Instead, you gotta use member.add_roles(role) instead. Same with bot.channel, it's supposed to be ctx.send.

Body:
I am trying to make a command that rarely gives a role (with a cooldown). However, when I try to run my code, it does not work, can anyone help to improve my code?

import discord
from discord.ext import commands
from discord.utils import get
import random

bot = commands.Bot(command_prefix=">")

...

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error,commands.CommandOnCooldown):
        msg = 'wait for a while {:.2f}s'.format(error.retry_after)
        await ctx.send(msg)

@bot.command(pass_context=True)
@commands.cooldown(1, 86400, commands.BucketType.user)
@commands.has_role("Mod")
async def addrole(ctx):
    if random.randint(1, 10000) < 2:
        member = ctx.message.author
        role = get(member.server.roles, name="Mod")
        await bot.add_roles(member, role)

    else:
        await bot.channel.send("you did not get mod")

bot.run(TOKEN HERE)

I am trying to make it a 0.01% chance of them getting the role. Thanks!


问:
multidimensional array difference php
I have two multidimensional arrays and I want the difference. For eg. I have taken two-dimensional two arrays below

```<code>$array1 = Array (
       [a1] => Array  (
          [a_name] => aaaaa
          [a_value] => aaa
     )

       [b1] => Array (
          [b_name] => bbbbb
          [b_value] => bbb
   )
       [c1] => Array (
          [c_name] => ccccc
          [c_value] => ccc
   )

)

$array2 = Array (
 [b1] => Array (
       [b_name]=> zzzzz
     )
)
</code>```

Now I want the key difference of these two arrays. I have tried array_diff_key() but it doesnot work for multidimensional.

```<code>array_diff_key($array1, $array2)
</code>```

I want the output as following

```<code>//output
$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
 )

   [b1] => Array (
      [b_value] => bbb
)
   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
)

)
</code>```

If you think my question is genuine please accept it and answer. Thank you.

EDIT

Now if the second array is

```<code>$array2 = Array( [b1] => zzzzz)
</code>```

The result should be

```<code>$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
    )

   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
     )

)
</code>```

答:
It appears that you need, at most, one foreach loop to access the first level keys in your filter array, then depending on whether there is a second level to your filtering array, you either make another round of comparisons with array_diff_key() or directly unset() the qualifying data from the first level.

Code: (Demo)

```<code>$a1 = array(
    'a1' => array('a_name' => 'aaa', 'a_value' => 'aaaaa'),
    'b1' => array('b_name' => 'bbb', 'b_value' => 'bbbbbb'),
    'c1' => array('c_name' => 'ccc', 'c_value' => 'cccccc')
);

function twoLevelFilter($master, $filter) {
    foreach ($filter as $key => $value) {
        if (isset($master[$key])) {
            if (is_iterable($value)) {
                $master[$key] = array_diff_key($master[$key], $value);
            } else {
                unset($master[$key]);
            }
        }
    }
    return $master;
}

var_export(twoLevelFilter($a1, ['b1' => ['b_name' => 'zzzzz']]));
echo "\n---\n";
var_export(twoLevelFilter($a1, ['b1' => 'zzzzz']));
</code>```

Output:

```<code>array (
  'a1' =>
  array (
    'a_name' => 'aaa',
    'a_value' => 'aaaaa',
  ),
  'b1' =>
  array (
    'b_value' => 'bbbbbb',
  ),
  'c1' =>
  array (
    'c_name' => 'ccc',
    'c_value' => 'cccccc',
  ),
)
---
array (
  'a1' =>
  array (
    'a_name' => 'aaa',
    'a_value' => 'aaaaa',
  ),
  'c1' =>
  array (
    'c_name' => 'ccc',
    'c_value' => 'cccccc',
  ),
)
</code>```

Title: multidimensional array difference php

Body:
I have two multidimensional arrays and I want the difference. For eg. I have taken two-dimensional two arrays below

$array1 = Array (
       [a1] => Array  (
          [a_name] => aaaaa
          [a_value] => aaa
     )

       [b1] => Array (
          [b_name] => bbbbb
          [b_value] => bbb
   )
       [c1] => Array (
          [c_name] => ccccc
          [c_value] => ccc
   )

)

$array2 = Array (
 [b1] => Array (
       [b_name]=> zzzzz
     )
)

Now I want the key difference of these two arrays. I have tried array_diff_key() but it doesnot work for multidimensional.

array_diff_key($array1, $array2)

I want the output as following

//output
$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
 )

   [b1] => Array (
      [b_value] => bbb
)
   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
)

)

If you think my question is genuine please accept it and answer. Thank you.

EDIT

Now if the second array is

$array2 = Array( [b1] => zzzzz)

The result should be

$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
    )

   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
     )

)

Body:
It appears that you need, at most, one foreach loop to access the first level keys in your filter array, then depending on whether there is a second level to your filtering array, you either make another round of comparisons with array_diff_key() or directly unset() the qualifying data from the first level.

Code: (Demo)

$a1 = array(
    'a1' => array('a_name' => 'aaa', 'a_value' => 'aaaaa'),
    'b1' => array('b_name' => 'bbb', 'b_value' => 'bbbbbb'),
    'c1' => array('c_name' => 'ccc', 'c_value' => 'cccccc')
);

function twoLevelFilter($master, $filter) {
    foreach ($filter as $key => $value) {
        if (isset($master[$key])) {
            if (is_iterable($value)) {
                $master[$key] = array_diff_key($master[$key], $value);
            } else {
                unset($master[$key]);
            }
        }
    }
    return $master;
}

var_export(twoLevelFilter($a1, ['b1' => ['b_name' => 'zzzzz']]));
echo "\n---\n";
var_export(twoLevelFilter($a1, ['b1' => 'zzzzz']));

Output:

array (
  'a1' =>
  array (
    'a_name' => 'aaa',
    'a_value' => 'aaaaa',
  ),
  'b1' =>
  array (
    'b_value' => 'bbbbbb',
  ),
  'c1' =>
  array (
    'c_name' => 'ccc',
    'c_value' => 'cccccc',
  ),
)
---
array (
  'a1' =>
  array (
    'a_name' => 'aaa',
    'a_value' => 'aaaaa',
  ),
  'c1' =>
  array (
    'c_name' => 'ccc',
    'c_value' => 'cccccc',
  ),
)


问:
More efficient method to convert XYZ coords into Spherical Coords
I have a script in Blender for plotting data points either in plane or spherical projection. However, the current method I have for converting my X,Y,Z coordinate for each vertex to spherical format is quite slow. Maybe some of you know of a more efficient method.

Essentially I have a (#verts,3) array of XYZ coordinates. Then I apply the following function over it.

```<code>def deg2rads(deg):
    return deg*pi/180

def spherical(row):
    x,y,z = [deg2rads(i) for i in row]
    new_x = cos(y)*cos(x)
    new_y = cos(y)*sin(x)
    new_z = sin(y)
    return new_x,new_y,new_z

polar_verts = np.apply_along_axis(spherical,1,polar_verts)
</code>```

I believe apply_along_axis is not vectorized like other numpy operations. So maybe someone knows a better method? Now that I'm looking at it I think I can just vector multiply my verts to convert to rads. So that might shave a couple miliseconds off.

答:
Not sure if that makes your code faster. Basically you apply the function not to each coordinate-vector, but individually for x, y and z (hopefully vectorized) and afterwards stack them together.

import numpy as np

def spherical(spherical_coordinates):
    phi = spherical_coordinates[:, 0] * np.pi / 180
    theta = spherical_coordinates[:, 1] * np.pi / 180
    x = np.cos(phi) * np.cos(theta)
    y = np.sin(phi) * np.cos(theta)
    z = np.sin(theta)
    return np.column_stack([x, y, z])

spherical(polar_verts)
```

Assuming polar_verts has shape (#verts, 3).

But @DmitriChubarov is right: You're converting from spherical to cartesian coordinates, not the other way round. I would suggest to rename the function: spherical --> spherical_to_cartesian.

Body:
I have a script in Blender for plotting data points either in plane or spherical projection. However, the current method I have for converting my X,Y,Z coordinate for each vertex to spherical format is quite slow. Maybe some of you know of a more efficient method.

Essentially I have a (#verts,3) array of XYZ coordinates. Then I apply the following function over it.

def deg2rads(deg):
    return deg*pi/180

def spherical(row):
    x,y,z = [deg2rads(i) for i in row]
    new_x = cos(y)*cos(x)
    new_y = cos(y)*sin(x)
    new_z = sin(y)
    return new_x,new_y,new_z

polar_verts = np.apply_along_axis(spherical,1,polar_verts)

I believe apply_along_axis is not vectorized like other numpy operations. So maybe someone knows a better method? Now that I'm looking at it I think I can just vector multiply my verts to convert to rads. So that might shave a couple miliseconds off.

Body:
Not sure if that makes your code faster. Basically you apply the function not to each coordinate-vector, but individually for x, y and z (hopefully vectorized) and afterwards stack them together.

import numpy as np

def spherical(spherical_coordinates):
    phi = spherical_coordinates[:, 0] * np.pi / 180
    theta = spherical_coordinates[:, 1] * np.pi / 180
    x = np.cos(phi) * np.cos(theta)
    y = np.sin(phi) * np.cos(theta)
    z = np.sin(theta)
    return np.column_stack([x, y, z])

spherical(polar_verts)

Assuming polar_verts has shape (#verts, 3).

But @DmitriChubarov is right: You're converting from spherical to cartesian coordinates, not the other way round. I would suggest to rename the function: spherical --> spherical_to_cartesian.


问:
How to rename multiple variables at once?
I have multiple columns with variables I need to reverse-code. Let's say my column names are A,B,C,D and each column has a mix of values from 1-4. I am trying to recode all the 4's as 1's, 3's as 2's. etc.

I am able to do it like this:

```<code>`dataNew$A <- as.numeric(dataNew$A)
levels(dataNew$A)[levels(dataNew$A)=="1"] <- "4"
levels(dataNew$A)[levels(dataNew$A)=="2"] <- "3"
levels(dataNew$A)[levels(dataNew$A)=="3"] <- "2"
levels(dataNew$A)[levels(dataNew$A)=="2"] <- "1"`
</code>```

Then I could repeat for columns B,  C, D

However, I'm wondering if there is a cleaner way to do this where I can change multiple numbers or multiple columns and numbers at once, rather than individually writing the above code for each column/number combination.

答:
How about:</p>
```<code>library(tidyverse)

dataNew <- tibble(A = sample(1:4, 50, replace = TRUE),
                  B = sample(1:4, 50, replace = TRUE),
                  C = sample(1:4, 50, replace = TRUE),
                  D = sample(1:4, 50, replace = TRUE))
dataNew %>%
    mutate(across(A:D, ~ 5-.))
</code>```

Body:
I have multiple columns with variables I need to reverse-code. Let's say my column names are A,B,C,D and each column has a mix of values from 1-4. I am trying to recode all the 4's as 1's, 3's as 2's. etc.

I am able to do it like this:

`dataNew$A <- as.numeric(dataNew$A)
levels(dataNew$A)[levels(dataNew$A)=="1"] <- "4"
levels(dataNew$A)[levels(dataNew$A)=="2"] <- "3"
levels(dataNew$A)[levels(dataNew$A)=="3"] <- "2"
levels(dataNew$A)[levels(dataNew$A)=="2"] <- "1"`

Then I could repeat for columns B,  C, D

However, I'm wondering if there is a cleaner way to do this where I can change multiple numbers or multiple columns and numbers at once, rather than individually writing the above code for each column/number combination.

Body:
How about:

library(tidyverse)

dataNew <- tibble(A = sample(1:4, 50, replace = TRUE),
                  B = sample(1:4, 50, replace = TRUE),
                  C = sample(1:4, 50, replace = TRUE),
                  D = sample(1:4, 50, replace = TRUE))
dataNew %>%
    mutate(across(A:D, ~ 5-.))


问:
Python Add Try Exception in Loop
I have the following step in my python script that is pulling in every csv file from a directory to then be combined into a single dataframe. I keep on getting errors for a few files in the list (list is about 4000 long) and I'm looking for a way to skip those with errors.

I tried to add a try: except: into this line, but that did not work either. Any ideas?

```<code>combined_csv = pd.concat([pd.read_csv(os.path.join(export, l)) for l in os.listdir(export) ])
</code>```

Error:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
[Finished in 178.1s with exit code 1]
</code>```

答:
You'll have to build the list item by item, so that you can resume the loop after catching an exception. Something like

```<code>dataframes = []

for l in os.listdir(export):
    try:
        df = pd.read_csv(os.path.join(export, l))
    except UnicodeDecodeError:
        continue
    dataframes.append(df)

combined_csv = pd.concat(dataframes)
</code>```

There is, unfortunately, no expression that can catch an exception at this time in Python, only the statement. One was proposed, but rejected.

If you want, you can wrap the try statement in a function that return a value you can skip. For example:

```<code>def make_csv(path):
    try:
        return pd.read_csv(path)
    except UnicodeDecodeError:
        return None

combined_csv = pd.concat([x for x in [make_csv(os.path.join(export, f) for f in os.listdir(export)] if x is not None]
</code>```

or

```<code>combined_csv = pd.concat([make_csv(os.path.join(export, f)) for f in os.listdir(export)])
</code>```

if you can make make_csv return an empty CSV file instead of None.

Title: Python Add Try Exception in Loop

Body:
I have the following step in my python script that is pulling in every csv file from a directory to then be combined into a single dataframe. I keep on getting errors for a few files in the list (list is about 4000 long) and I'm looking for a way to skip those with errors.

I tried to add a try: except: into this line, but that did not work either. Any ideas?

combined_csv = pd.concat([pd.read_csv(os.path.join(export, l)) for l in os.listdir(export) ])

Error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
[Finished in 178.1s with exit code 1]

Body:
You'll have to build the list item by item, so that you can resume the loop after catching an exception. Something like

dataframes = []

for l in os.listdir(export):
    try:
        df = pd.read_csv(os.path.join(export, l))
    except UnicodeDecodeError:
        continue
    dataframes.append(df)

combined_csv = pd.concat(dataframes)

There is, unfortunately, no expression that can catch an exception at this time in Python, only the statement. One was proposed, but rejected.

If you want, you can wrap the try statement in a function that return a value you can skip. For example:

def make_csv(path):
    try:
        return pd.read_csv(path)
    except UnicodeDecodeError:
        return None

combined_csv = pd.concat([x for x in [make_csv(os.path.join(export, f) for f in os.listdir(export)] if x is not None]

or

combined_csv = pd.concat([make_csv(os.path.join(export, f)) for f in os.listdir(export)])

if you can make make_csv return an empty CSV file instead of None.


问:
Can I display D3 graphs on .epub?
I'm making a research project about .epub and I've been trying to hack my way into executing JS code into an EPUB and display some kind of data visualization.

Right now, I'm using calibre to create the epub from an HTML file. The HTML file has the code for very simple D3 scatterplots, and it works fine when opening the file from the browser. However, after creating the .epub in calibre, the page is just empty. Do you guys know if this is even possible? I know that EPUB 3 should be somewhat similar to a modern browser, so theoretically anything that can be rendered into a browser should also be possible on a .epub. Is it because I am loading d3.js? Calibre does not provide any kind of feedback.

<!DOCTYPE html>
<meta charset="utf-8">

```

答:
I think it's not possible for fetching external libraries, not only for security reasons, but how can I read book like this in forest without internet? It's definetly BAD practice - ebooks must working in offline.
https://github.com/kobolabs/epub-spec#javascript-support</p>

Title: Can I display D3 graphs on .epub?


问:
how can I fix "build failed" after I run react-native run-android in windows 10
I have created the project very well and I have also installed the android studio and all the required sdks. but still I am still facing a problem of the emulator not starting. below is error in the terminal.

'$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier"
flag.
(node:8368) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use node --trace-warnings ... to show where the warning was created)
Jetifier found 866 file(s) to forward-jetify. Using 6 workers...
info Starting JS server...
'adb' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of emulator -list-avds.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon, 3 stopped Daemons could not be reused, use --status for details

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.2/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

```<code>at makeError (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:174:9)
at C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:278:16
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async runOnAllDevices (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\react-native\node_modules\@react-native-community\cli\build\index.js:192:9)
</code>```

info Run CLI with --verbose flag for more details.`

答:
Have you tried this?

Go to your React-native Project -> Android

Create a file local.properties

Paste

C:\Users\USERNAME\AppData\Local\Android\sdk

Replace USERNAME with your user name

Body:
I have created the project very well and I have also installed the android studio and all the required sdks. but still I am still facing a problem of the emulator not starting. below is error in the terminal.

'$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier"
flag.
(node:8368) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use node --trace-warnings ... to show where the warning was created)
Jetifier found 866 file(s) to forward-jetify. Using 6 workers...
info Starting JS server...
'adb' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of emulator -list-avds.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon, 3 stopped Daemons could not be reused, use --status for details

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.2/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

at makeError (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:174:9)
at C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:278:16
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async runOnAllDevices (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\react-native\node_modules\@react-native-community\cli\build\index.js:192:9)

info Run CLI with --verbose flag for more details.`


问:
OnActionExecutedAsync Not available in ActionFilterAttribute in .Net core
I am porting over a action filter attribute from .net framework 4.6 to .net core 3.1 . One thing i noticed in .net core ActionFilterAttribute is that it , in .net core ther is no OnActionExecutedAsync Method.
Methods in ActionFilterAttribute  :-

```<code>public virtual void OnActionExecuted(ActionExecutedContext context);
public virtual void OnActionExecuting(ActionExecutingContext context);
public virtual Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next);
public virtual void OnResultExecuted(ResultExecutedContext context);
public virtual void OnResultExecuting(ResultExecutingContext context);
public virtual Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next);

</code>```

I have a couple of async methods that need to executed after the execution of the action . What would be the best practice to do this.

答:
Use OnActionExecutionAsync, where you can invoke the next delegate and then run your own async logic after:

public override async Task OnActionExecutionAsync(
    ActionExecutingContext context, ActionExecutionDelegate next)
{
    var actionExecutedContext = await next();

    // .. Your awaits here.
}
```

The next delegate returns the ActionExecutedContext.

Body:
I am porting over a action filter attribute from .net framework 4.6 to .net core 3.1 . One thing i noticed in .net core ActionFilterAttribute is that it , in .net core ther is no OnActionExecutedAsync Method.
Methods in ActionFilterAttribute  :-

public virtual void OnActionExecuted(ActionExecutedContext context);
public virtual void OnActionExecuting(ActionExecutingContext context);
public virtual Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next);
public virtual void OnResultExecuted(ResultExecutedContext context);
public virtual void OnResultExecuting(ResultExecutingContext context);
public virtual Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next);

I have a couple of async methods that need to executed after the execution of the action . What would be the best practice to do this.

Body:
Use OnActionExecutionAsync, where you can invoke the next delegate and then run your own async logic after:

public override async Task OnActionExecutionAsync(
    ActionExecutingContext context, ActionExecutionDelegate next)
{
    var actionExecutedContext = await next();

    // .. Your awaits here.
}

The next delegate returns the ActionExecutedContext.