问:
Hi, I am new to php and I cant find a way to make alternate table color in my code. It always show the wrong output that is required for me to follow
I did the nth child rule in css but it the colors are not alternate. Colors are all the same each rows and columns. My code is a multiplication table with a supposed alternate color. Im having a hard time knowing what I should do to modify or add in my php code to create the desired output (alternate colors in rows and columns in the multiplication table).

Below is my php code:

```<code><?php
    for($row=0; $row<=10; $row++){
        echo "<tr>";

        for($column=0; $column<=10; $column++){

            if($row==0 && $column==0){
                echo "<td></td>";
            }

            else{
                echo "<td>". $row * $column. "</td>";
            }

        }
    }
    echo "</tr>";
    ?>
</code>```

CSS code:

```<code>table, th, td {
    border: 1px solid black;
}

td {
    padding: 15px;
}

.bold{
    font-weight: bold;
    font-size: 1.3em;
}

table tr:nth-child(odd) {
    background-color: yellow;
}
table tr:nth-child(even) {
    background-color: red;
}
</code>```

答:
you forget to use the
 tag and your CSS address it from the table.

```<code><?php
   echo "<table>";
    for($row=0; $row<=10; $row++){
        echo "<tr>";

        for($column=0; $column<=10; $column++){

            if($row==0 && $column==0){
                echo "<td></td>";
            }

            else{
                echo "<td>". $row * $column. "</td>";
            }

        }
        echo "</tr>";
    }

    echo "</table>";
    ?>
</code>```

Body:
I did the nth child rule in css but it the colors are not alternate. Colors are all the same each rows and columns. My code is a multiplication table with a supposed alternate color. Im having a hard time knowing what I should do to modify or add in my php code to create the desired output (alternate colors in rows and columns in the multiplication table).

Below is my php code:

<?php
    for($row=0; $row<=10; $row++){
        echo "
";

        for($column=0; $column<=10; $column++){

            if($row==0 && $column==0){
                echo "	";
            }

            else{
                echo "". $row * $column. "	";
            }

        }
    }
    echo "
";
    ?>

CSS code:

table, th, td {
    border: 1px solid black;
}

td {
    padding: 15px;
}

.bold{
    font-weight: bold;
    font-size: 1.3em;
}

table tr:nth-child(odd) {
    background-color: yellow;
}
table tr:nth-child(even) {
    background-color: red;
}

Body:
you forget to use the <table> tag and your CSS address it from the table.

<?php
   echo "<table>";
    for($row=0; $row<=10; $row++){
        echo "<tr>";

        for($column=0; $column<=10; $column++){

            if($row==0 && $column==0){
                echo "<td></td>";
            }

            else{
                echo "<td>". $row * $column. "</td>";
            }

        }
        echo "</tr>";
    }

    echo "</table>";
    ?>


来源: stackexchange

问:
Removing the integers in the output when inputted with a String
I am struggling on my code. My prof told us to make a line of code in Eclipse which, when a string like a "q1w2e3r4t5y" is input, will output only "qwerty". The numbers are removed. This can be easily achieved using a regular expression. My problem is, it is my first year in coding and I'm not yet familiar with the code using Java.

The code using regex is

```<code>String inputString = "q1w2e3r4t5y";

System.out.println(inputString.replaceAll("\\d",""));
</code>```

And the console/output is

```<code>qwerty
</code>```

Please tell me what code is the best way to execute this output without using the regex.

答:
```<code>  public static void main(String[] args) {
        String inputString = "q1w2e3r4t5y";
        String newS ="";
        for (int i = 0; i < inputString.length(); i++) {
            String s = inputString.charAt(i)+"";
            try {
                Integer.parseInt(s);

            } catch (Exception e) {
                //TODO: build the string here
                newS+=s;
            }

        }

        System.out.println(newS);//qwerty

      }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am struggling on my code. My prof told us to make a line of code in Eclipse which, when a string like a "q1w2e3r4t5y" is input, will output only "qwerty". The numbers are removed. This can be easily achieved using a regular expression. My problem is, it is my first year in coding and I'm not yet familiar with the code using Java.

The code using regex is

String inputString = "q1w2e3r4t5y";

System.out.println(inputString.replaceAll("\\d",""));

And the console/output is

qwerty

Please tell me what code is the best way to execute this output without using the regex.


问:
Code doesn't run when I had one more elsif statement
Can anyone please explain to me why my code doesn't run when I have my second elsif statement in. I'm sure it's something simple but I've been over it a few times, wrote out the code again and still can't work out the bug. It only bugs when line 25 to 30 are in and says

undefined method`[]' on line 35

but this error will change to something else if I run it again.

So this is affecting line_three as a test I am trying "Southern Cross" for the starting location and "Windsor" for the destination.

This is an error message I receive:

```<code>Traceback (most recent call last):
pt_planner.rb:35:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
</code>```

another is:

```<code>Traceback (most recent call last):
pt_planner.rb:33:in `<main>': undefined method `-' for nil:NilClass (NoMethodError)
</code>```

Hope this edit helps

```<code>require 'pry'

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]
line_two = ['Flagstaff', 'Melbourne Central', 'Parliament', 'Richmond', 'Kooyong', 'Tooronga']
line_three = ['Southern Cross', 'Richmond', 'South Yarra' ,'Prahran' 'Windsor']

#1 where would you like to go capture input
puts "what is your starting location?"
user_input_1 = gets.chomp
puts "what is your end location"
user_input_2 = gets.chomp

if line_one.include?(user_input_1) == true and
    line_one.include?(user_input_2) == true
    origin_index = line_one.index(user_input_1)
    destination_index = line_one.index(user_input_2)
    route = line_one
elsif
    line_two.include?(user_input_1) == true and
    line_two.include?(user_input_2) == true
    origin_index = line_two.index(user_input_1)
    destination_index = line_two.index(user_input_2)
    route = line_two
elsif
    line_three.include?(user_input_1) == true and
    line_three.include?(user_input_2) == true
    origin_index = line_three.index(user_input_1)
    destination_index = line_two.index(user_input_2)
    route = line_three
end

stops = destination_index - origin_index

puts "origin: #{route[origin_index]}\ndestination: #{route[destination_index]}\n#{route.slice(origin_index +1, stops)}\n stops total: #{destination_index - origin_index}"

binding.pry
</code>```

答:
In your line_three Array, you have forgotten the comma between 'Prahran' and 'Windsor'. As such, Ruby parses this as a string continuation and adds a single element as 'PrahranWindsor' here.

With that, none of your if or elsif conditions match. Consequently, note of the variables you set on any of the branches will be set and instead will be implicitly initialized as nil. As you assume these variables to be set later in your program, things break.

To fix this, you should at first fix the definition of your line_three array.

You should also add code to handle the case that none of your queries matched. Here, you could add a final else branch which e.g. shows an error message and asks the user to try again.

Body:
Can anyone please explain to me why my code doesn't run when I have my second elsif statement in. I'm sure it's something simple but I've been over it a few times, wrote out the code again and still can't work out the bug. It only bugs when line 25 to 30 are in and says

undefined method`[]' on line 35

but this error will change to something else if I run it again.

So this is affecting line_three as a test I am trying "Southern Cross" for the starting location and "Windsor" for the destination.

This is an error message I receive:

Traceback (most recent call last):
pt_planner.rb:35:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)

another is:

Traceback (most recent call last):
pt_planner.rb:33:in `<main>': undefined method `-' for nil:NilClass (NoMethodError)

Hope this edit helps

require 'pry'

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]
line_two = ['Flagstaff', 'Melbourne Central', 'Parliament', 'Richmond', 'Kooyong', 'Tooronga']
line_three = ['Southern Cross', 'Richmond', 'South Yarra' ,'Prahran' 'Windsor']

#1 where would you like to go capture input
puts "what is your starting location?"
user_input_1 = gets.chomp
puts "what is your end location"
user_input_2 = gets.chomp

if line_one.include?(user_input_1) == true and
    line_one.include?(user_input_2) == true
    origin_index = line_one.index(user_input_1)
    destination_index = line_one.index(user_input_2)
    route = line_one
elsif
    line_two.include?(user_input_1) == true and
    line_two.include?(user_input_2) == true
    origin_index = line_two.index(user_input_1)
    destination_index = line_two.index(user_input_2)
    route = line_two
elsif
    line_three.include?(user_input_1) == true and
    line_three.include?(user_input_2) == true
    origin_index = line_three.index(user_input_1)
    destination_index = line_two.index(user_input_2)
    route = line_three
end

stops = destination_index - origin_index

puts "origin: #{route[origin_index]}\ndestination: #{route[destination_index]}\n#{route.slice(origin_index +1, stops)}\n stops total: #{destination_index - origin_index}"

binding.pry


问:
PHP object loaded as reference in foreach loop
I am looping through an object and i try to duplicate one of the items while changing one of it's variables.

But when i copy the original and then change the title in the new one, the old one changes along with it. Which it shouldn't, since i did not initialised it as a reference.

```<code>$calendar = array(
    (object)[
        'id' => 1,
        'title' => 'original 1',
    ],
    (object)[
        'id' => 2,
        'title' => 'original 2',
    ],
    (object)[
        'id' => 3,
        'title' => 'original 3',
    ],
);

foreach ($calendar AS $key => $item){
    if($item->id == 2){
        $item->title = 'new 2';
        array_splice($calendar, $key, 0, [1]);
        $calendar[$key] = $item;
    }
}

echo "```";
print_r($calendar);
die();
```
<p>I would expect the output of this to keep <code>original 2</code> intact. But it changes it along with it.</p>
```(
    [0] => stdClass Object
        (
            [id] => 1
            [title] => original 1
        )

    [1] => stdClass Object
        (
            [id] => 2
            [title] => new 2
        )

    [2] => stdClass Object
        (
            [id] => 2
            [title] => new 2
        )

    [3] => stdClass Object
        (
            [id] => 3
            [title] => original 3
        )

)
```
<p>Even if i make a new object and use that one to make the changes, it still changes the orignial.</p>
```foreach ($calendar AS $key => $item){
    if($item->id == 2){
        $new_item = $item;
        $new_item->title = 'new 2';
        array_splice($calendar, $key, 0, [1]);
        $calendar[$key] = $new_item;
    }
}
```

Now i could probably fix this by just making a new object from scratch and copy the values one by one in it. But where's the fun in that?

So my question is...Why does this happen? Even though i didn't cast $item as &$item

答:
Assignment or clone ?

Because, you're using objects, the problem is that $new_item = $item; doesn't create a new object, it creates a new reference of $item, named $new_item.

In the following example, $a and $b are the same object:

```<code>$a = new stdclass;
$b = $a;
var_dump($a, $b);
</code>```

Output is:

```<code>object(stdClass)#1 (0) {...} // same object #1
object(stdClass)#1 (0) {...} // same object #1
</code>```

Clone

You could use the keyword clone to create a new instance:

```<code>$a = new stdclass;
$b = clone $a; // Clone the object
var_dump($a, $b);
</code>```

Output:

```<code>object(stdClass)#1 (0) {...} // object #1
object(stdClass)#2 (0) {...} // new object #2
</code>```

So, in your case, you could use:

```<code>if ($item->id == 2) {
    $clone          = clone $item; // << Create a COPY of $item
    $clone->title   = 'new 2'; // Update the copy, not the reference
    $calendar[$key] = $clone; // Add this copy to final array
    // ...
}
</code>```

A note about parameters

When you're using objects as parameters for some functions, objects are reference, so, the given object can be updated in that function. Here is a simple example (demo):

function updateObject(object $object): void {
    $object->newProperty = true;
}

$obj = new stdClass;
var_dump($obj);
updateObject($obj);
var_dump($obj);
```
<p>The code above gives the following (condensed) output:</p>
```object(stdClass)#1 (0) { }
object(stdClass)#1 (1) { ["newProperty"]=> bool(true) }
```

Further reading : Objects and references

Body:
I am looping through an object and i try to duplicate one of the items while changing one of it's variables.

But when i copy the original and then change the title in the new one, the old one changes along with it. Which it shouldn't, since i did not initialised it as a reference.

$calendar = array(
    (object)[
        'id' => 1,
        'title' => 'original 1',
    ],
    (object)[
        'id' => 2,
        'title' => 'original 2',
    ],
    (object)[
        'id' => 3,
        'title' => 'original 3',
    ],
);

foreach ($calendar AS $key => $item){
    if($item->id == 2){
        $item->title = 'new 2';
        array_splice($calendar, $key, 0, [1]);
        $calendar[$key] = $item;
    }
}

echo "
";
print_r($calendar);
die();

I would expect the output of this to keep original 2 intact. But it changes it along with it.

(
    [0] => stdClass Object
        (
            [id] => 1
            [title] => original 1
        )

    [1] => stdClass Object
        (
            [id] => 2
            [title] => new 2
        )

    [2] => stdClass Object
        (
            [id] => 2
            [title] => new 2
        )

    [3] => stdClass Object
        (
            [id] => 3
            [title] => original 3
        )

)

Even if i make a new object and use that one to make the changes, it still changes the orignial.

foreach ($calendar AS $key => $item){
    if($item->id == 2){
        $new_item = $item;
        $new_item->title = 'new 2';
        array_splice($calendar, $key, 0, [1]);
        $calendar[$key] = $new_item;
    }
}

Now i could probably fix this by just making a new object from scratch and copy the values one by one in it. But where's the fun in that?

So my question is...Why does this happen? Even though i didn't cast $item as &$item

Body:
Assignment or clone ?

Because, you're using objects, the problem is that $new_item = $item; doesn't create a new object, it creates a new reference of $item, named $new_item.

In the following example, $a and $b are the same object:

$a = new stdclass;
$b = $a;
var_dump($a, $b);

Output is:

object(stdClass)#1 (0) {...} // same object #1
object(stdClass)#1 (0) {...} // same object #1

Clone

You could use the keyword clone to create a new instance:

$a = new stdclass;
$b = clone $a; // Clone the object
var_dump($a, $b);

Output:

object(stdClass)#1 (0) {...} // object #1
object(stdClass)#2 (0) {...} // new object #2

So, in your case, you could use:

if ($item->id == 2) {
    $clone          = clone $item; // << Create a COPY of $item
    $clone->title   = 'new 2'; // Update the copy, not the reference
    $calendar[$key] = $clone; // Add this copy to final array
    // ...
}

A note about parameters

When you're using objects as parameters for some functions, objects are reference, so, the given object can be updated in that function. Here is a simple example (demo):

function updateObject(object $object): void {
    $object->newProperty = true;
}

$obj = new stdClass;
var_dump($obj);
updateObject($obj);
var_dump($obj);

The code above gives the following (condensed) output:

object(stdClass)#1 (0) { }
object(stdClass)#1 (1) { ["newProperty"]=> bool(true) }

Further reading : Objects and references


问:
Should I put my UserDefaults saving process into ViewModel? (good architecture)
I'm creating a simple NewsApp. I want to create the best app architecture I can made. So my question is that if I want save really simple data like username and maybe 5-6 tags as strings, should I put userDefaults logic into my viewModel or should I create a layer between ViewModel and UserDefaultsAPI which will take care about saving data?

I mean I will create StoreData protocol which UserDefaultsAPI will implement. And if I should do it how I can achieve that? I am using RxSwift and I don't now how to subscribe changing data in UserDefaults by UserDefaultsAPI.

答: It depends what your doing creating a seperate layer gives you, the opportunity to have different sources for data that implement the same protocol could be useful, and your data may be complex types than need to be encoded and decoded, so it makes sense to encapsulate that out, you may also want to provide some limit range to some of your values, but UserDefaults is just a service like NotificationCenter, you are not going to automatically wrap NotificationCenter in ever class, just do what is simplest, but doesn't run the risk of painting yourself in a corner later on. You are not going to get every issue decided at the get go right, the skill is to make sure you can quickly change if the need arises, and knowing about what possibility's you will need to take advantage of in the future and how can you avoid needing to make complex changes in the moment that don't add squat. There are lots of things you need to do, and being able to prioritise them is an important part of what you do, don't try make cleaver designs, be cleaver in making designs that can be easy for other to understand and modify.</p>


问:
How to fix Cloud Function error admin.database.ref is not a function at exports
I'm currently trying to modify my Cloud Functions and move in under https.onRequest so that i can call use it to schedule a cron job. How it i'm getting the following error in the logs.

TypeError: admin.database.ref is not a function
        at exports.scheduleSendNotificationMessageJob.functions.https.onRequest (/user_code/index.js:30:20)
        at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)

```<code>exports.scheduleSendNotificationMessageJob = functions.https.onRequest((req, res) => {
    admin.database.ref('/notifications/{studentId}/notifications/{notificationCode}')
        .onCreate((dataSnapshot, context) => {
            const dbPath = '/notifications/' + context.params.pHumanId + '/fcmCode';
            const promise = admin.database().ref(dbPath).once('value').then(function(tokenSnapshot) {
                const theToken = tokenSnapshot.val();
                res.status(200).send(theToken);
                const notificationCode = context.params.pNotificationCode;
                const messageData = {notificationCode: notificationCode};
                const theMessage = {    data: messageData,
                    notification: { title: 'You have a new job reminder' }
                };
                const options = {   contentAvailable: true,
                    collapseKey: notificationCode };
                const notificationPath = '/notifications/' + context.params.pHumanId + '/notifications/' + notificationCode;
                admin.database().ref(notificationPath).remove();
                return admin.messaging().sendToDevice(theToken, theMessage, options);
            });
            return null;
        });
});
</code>```

答: For me, this error happened when writing admin.database instead of admin.database().

Body:
I'm currently trying to modify my Cloud Functions and move in under https.onRequest so that i can call use it to schedule a cron job. How it i'm getting the following error in the logs.

TypeError: admin.database.ref is not a function
        at exports.scheduleSendNotificationMessageJob.functions.https.onRequest (/user_code/index.js:30:20)
        at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)

exports.scheduleSendNotificationMessageJob = functions.https.onRequest((req, res) => {
    admin.database.ref('/notifications/{studentId}/notifications/{notificationCode}')
        .onCreate((dataSnapshot, context) => {
            const dbPath = '/notifications/' + context.params.pHumanId + '/fcmCode';
            const promise = admin.database().ref(dbPath).once('value').then(function(tokenSnapshot) {
                const theToken = tokenSnapshot.val();
                res.status(200).send(theToken);
                const notificationCode = context.params.pNotificationCode;
                const messageData = {notificationCode: notificationCode};
                const theMessage = {    data: messageData,
                    notification: { title: 'You have a new job reminder' }
                };
                const options = {   contentAvailable: true,
                    collapseKey: notificationCode };
                const notificationPath = '/notifications/' + context.params.pHumanId + '/notifications/' + notificationCode;
                admin.database().ref(notificationPath).remove();
                return admin.messaging().sendToDevice(theToken, theMessage, options);
            });
            return null;
        });
});


问:
How can add extra Firebase Cloud Functions to an Angular Unviersal project
In an Angular Universal project this is the fixed firebase.json setting:

{
    "hosting": [{
        "target": "PROJECT-ID",
        "public": "dist/PROJECT-ID/dist/PROJECT-ID/browser",
        "ignore": [
            "**/.*"
        ],
        "headers": [{
            "source": "*.[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].+(css|js)",
            "headers": [{
                "key": "Cache-Control",
                "value": "public,max-age=31536000,immutable"
            }]
        }],
        "rewrites": [{
            "source": "**",
            "function": "ssr"
        }]
    }],
    "functions": {
        "source": "dist/PROJECT-ID"
    }
}
```

But now, I would like to add extra Firebase Cloud Functions (both HTTP and callable), so I would like to struct this server folder to code functions with typescript, src-folder, tsconfig.json and so on. This is easy if you start from scratch:

Can anybody help me? I am not sure if I have to add the functions in my index.js file and deploy SSR and the remaining functions together, or do I have to create another folder for functions, and deploy first SSR and later other functions?

答:
Cloud Functions for AngularFire is contained in the @angular/fire/functions module namespace. Import the AngularFireFunctionsModule in your NgModule. This sets up the AngularFireFunction service for dependency injection.

Im not sure if this can help you Deploy your application on Firebase Hosting & Functions

Body:
In an Angular Universal project this is the fixed firebase.json setting:

{
    "hosting": [{
        "target": "PROJECT-ID",
        "public": "dist/PROJECT-ID/dist/PROJECT-ID/browser",
        "ignore": [
            "**/.*"
        ],
        "headers": [{
            "source": "*.[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].+(css|js)",
            "headers": [{
                "key": "Cache-Control",
                "value": "public,max-age=31536000,immutable"
            }]
        }],
        "rewrites": [{
            "source": "**",
            "function": "ssr"
        }]
    }],
    "functions": {
        "source": "dist/PROJECT-ID"
    }
}

But now, I would like to add extra Firebase Cloud Functions (both HTTP and callable), so I would like to struct this server folder to code functions with typescript, src-folder, tsconfig.json and so on. This is easy if you start from scratch:

Can anybody help me? I am not sure if I have to add the functions in my index.js file and deploy SSR and the remaining functions together, or do I have to create another folder for functions, and deploy first SSR and later other functions?


问:
Use External Notifier in AWS with SNS
I am using AWS with Codedeploy and Codepipeline, with Git to push our PHP codes and I want to use Discord or any free service to Notify our Pipeline status</p>

答:
EventBridge service provide codepipeline notification. Trigger it to SNS for email notification or lambda function for custom action

Available EventBridge event for codepipeline:
https://docs.aws.amazon.com/codepipeline/latest/userguide/detect-state-changes-cloudwatch-events.html

Telegram notification python example (you can try other application API)
https://levelup.gitconnected.com/simple-telegram-bot-with-python-and-aws-lambda-5eab1066b466

Title: Use External Notifier in AWS with SNS


问:
blazor webassembly Why I am getting infinite looping between Page and subComponent?
My app is in VS2022 C# Blazor WASM-hosted with .Net 6.  I have a blazor page with a sub-Component that has functionality to allow the PAGE to see a select-box for Active/Inactive (two options) and a select-box for a list of Customer names (abbreviated).

The PAGE looks like this:

The TOP rectangle is the sub-component that "acts" like a "function" that returns (via CALLBACK) the selected "CustomerID" (shown is 'ARCTB').  The sub-component reacts to the "select-choice" (@onchange=) by CALLBACK-parameter to the parent form with the 'selected' CustomerID so the parent-page can fetch the vehicles for that selected customer.

On the initial sub-component OnParametersSetAsync(), where the list of customers and first CustomerID are determined, the CALLBACK to the PAGE is made using the List[0] element for CustomerID.  At this point at the PAGE, a re-render takes place for both the PAGE and the sub-component. That causes the sub-component's OnParametersSetAsync() to fire again and the CALLBACK, again for the infinite loop.

The SECOND rectangle is part of the PAGE-html and allows the user to select active or inactive vehicles, that filters the list of customer vehicles to that of _listOfAllVehicles( v => v.IS_ACTIVE == true-or-false).

The problem of infinite-loop occurs because the CALLBACK to the PAGE forces re-renders and then the sub-component performs another CALLBACK from the OnParametersSetAsync() method.  This is the infinite-loop problem I seek an answer.

Being new to the latest Blazor, I am not sure if ShouldRender() could be used on the PAGE or sub-component or both?  Maybe using a sub-component "flag" to denote "OkToCallback" to limit repeated CALLBACK calls.

Your comments, questions and answers are welcome.

As requested by @Marius, the sub-component code is shown below.  I have included a TEST for '_IsLoading' that STOPPED the infinite-loop.

Thank you @Marius for the ANSWER. :-)

```<code>protected override async Task OnParametersSetAsync() {
    // Retain the Parameters.
    _LoggedInCustomerName = pLoggedInCustomerName;
    _LoggedInUserRoleName = pLoggedInRole;

    _IsUserNotFCI = (_LoggedInUserRoleName != "FCI");
    _IsActiveCustomers = (_ddlActive_Value == 1);

    await Task.Delay(10);
    _ddlCustomer_Value = RefreshCustomerList(_ddlActive_Value);

    if (_ddlCustomer_Value > 0) {

        // Set to first-option (index) (refer to wwwroot\index.html -- see OnAfterRender()
        if (_IsLoading) {
            // Update the selected customer.
            ChangeEventArgs evntArgs = new ChangeEventArgs();
            evntArgs.Value = _ddlCustomer_Value.ToString();
            await SelectedCustomerChanged(evntArgs);
            _IsLoading = false;
        }
    }

    base.OnParametersSet();
}

private int RefreshCustomerList(int pCustomersActiveFlag) {
    // Refresh the customer-list based on the 'ddlActiveFilter' ACTIVE-STATUS and USER-ROLE.
    // Return the zero-th element's UID_CUSTOMER of the list of customers.
    bool isActiveFlag = (pCustomersActiveFlag==1);
    int retValue = 0;
    if (_ListAllCustomers != null) {
        // When LOGGEDIN-USER is NOT FCI, reduce the list to ONLY the loggedin-user customer.
        if (_IsUserNotFCI) {
            // This returns a list of a single <Customer> record.
            _ListFilteredCustomers = _ListAllCustomers.Where(c => (c.TXT_CUSTOMER_NAME == _LoggedInCustomerName)).ToList();
        } else {
            // This returns a list of all ACTIVE or INACTIVE customers based on 'pCustomersActiveFlag' => 'isActiveFlag'.
            _ListFilteredCustomers = _ListAllCustomers.Where(c => (c.BOOL_IS_CUST_ACTIVE == isActiveFlag)).OrderBy(r => r.TXT_CUSTOMER_ABBREV).ToList();
        }

        // Set the 'ddlCustomer_Value' to the UID of the first-customer in the list.
        retValue = _ListFilteredCustomers[0].UID_CUSTOMER;
    }
    return retValue;
}

private async Task SelectedCustomerChanged(ChangeEventArgs e) {  // This is the event after selection is made.
    int iArgValue = Convert.ToInt32(e.Value);
    _ddlCustomer_Value = Convert.ToInt32(e.Value);

    Customer customer = _ListFilteredCustomers!.Where(rec => rec.UID_CUSTOMER == _ddlCustomer_Value).FirstOrDefault();
    if (customer != null) {
        _SelectedCustUID = customer.UID_CUSTOMER;
        _SelectedCustName = customer.TXT_CUSTOMER_NAME;
    }

    // Callback to Parent.
    await OnCustomerSelection.InvokeAsync(_ddlCustomer_Value);

}
</code>```

答:
OnParametersSetAsync and OnParametersSet will fire whenever a parameter changes, even if the value is the same as before. You can write some code to avoid this.

Example: Is previous parameter value the same as current ? skip load : load

```<code>private string _cachedValue;

[Parameter]
public string parameterValue { get; set; }

protected override async Task OnParametersSetAsync()
{
    if (parameterValue != _cachedValue)
    {
        _cachedValue = parameterValue;
        LoadComponent();
    }
}

private void LoadComponent() {
    //...
}
</code>```

The above is just an example of one method of doing this. Use logic that suits your code.

Body:
My app is in VS2022 C# Blazor WASM-hosted with .Net 6.  I have a blazor page with a sub-Component that has functionality to allow the PAGE to see a select-box for Active/Inactive (two options) and a select-box for a list of Customer names (abbreviated).

The PAGE looks like this:

The TOP rectangle is the sub-component that "acts" like a "function" that returns (via CALLBACK) the selected "CustomerID" (shown is 'ARCTB').  The sub-component reacts to the "select-choice" (@onchange=) by CALLBACK-parameter to the parent form with the 'selected' CustomerID so the parent-page can fetch the vehicles for that selected customer.

On the initial sub-component OnParametersSetAsync(), where the list of customers and first CustomerID are determined, the CALLBACK to the PAGE is made using the List[0] element for CustomerID.  At this point at the PAGE, a re-render takes place for both the PAGE and the sub-component. That causes the sub-component's OnParametersSetAsync() to fire again and the CALLBACK, again for the infinite loop.

The SECOND rectangle is part of the PAGE-html and allows the user to select active or inactive vehicles, that filters the list of customer vehicles to that of _listOfAllVehicles( v => v.IS_ACTIVE == true-or-false).

The problem of infinite-loop occurs because the CALLBACK to the PAGE forces re-renders and then the sub-component performs another CALLBACK from the OnParametersSetAsync() method.  This is the infinite-loop problem I seek an answer.

Being new to the latest Blazor, I am not sure if ShouldRender() could be used on the PAGE or sub-component or both?  Maybe using a sub-component "flag" to denote "OkToCallback" to limit repeated CALLBACK calls.

Your comments, questions and answers are welcome.

As requested by @Marius, the sub-component code is shown below.  I have included a TEST for '_IsLoading' that STOPPED the infinite-loop.

Thank you @Marius for the ANSWER. :-)

protected override async Task OnParametersSetAsync() {
    // Retain the Parameters.
    _LoggedInCustomerName = pLoggedInCustomerName;
    _LoggedInUserRoleName = pLoggedInRole;

    _IsUserNotFCI = (_LoggedInUserRoleName != "FCI");
    _IsActiveCustomers = (_ddlActive_Value == 1);

    await Task.Delay(10);
    _ddlCustomer_Value = RefreshCustomerList(_ddlActive_Value);

    if (_ddlCustomer_Value > 0) {

        // Set to first-option (index) (refer to wwwroot\index.html -- see OnAfterRender()
        if (_IsLoading) {
            // Update the selected customer.
            ChangeEventArgs evntArgs = new ChangeEventArgs();
            evntArgs.Value = _ddlCustomer_Value.ToString();
            await SelectedCustomerChanged(evntArgs);
            _IsLoading = false;
        }
    }

    base.OnParametersSet();
}

private int RefreshCustomerList(int pCustomersActiveFlag) {
    // Refresh the customer-list based on the 'ddlActiveFilter' ACTIVE-STATUS and USER-ROLE.
    // Return the zero-th element's UID_CUSTOMER of the list of customers.
    bool isActiveFlag = (pCustomersActiveFlag==1);
    int retValue = 0;
    if (_ListAllCustomers != null) {
        // When LOGGEDIN-USER is NOT FCI, reduce the list to ONLY the loggedin-user customer.
        if (_IsUserNotFCI) {
            // This returns a list of a single <Customer> record.
            _ListFilteredCustomers = _ListAllCustomers.Where(c => (c.TXT_CUSTOMER_NAME == _LoggedInCustomerName)).ToList();
        } else {
            // This returns a list of all ACTIVE or INACTIVE customers based on 'pCustomersActiveFlag' => 'isActiveFlag'.
            _ListFilteredCustomers = _ListAllCustomers.Where(c => (c.BOOL_IS_CUST_ACTIVE == isActiveFlag)).OrderBy(r => r.TXT_CUSTOMER_ABBREV).ToList();
        }

        // Set the 'ddlCustomer_Value' to the UID of the first-customer in the list.
        retValue = _ListFilteredCustomers[0].UID_CUSTOMER;
    }
    return retValue;
}

private async Task SelectedCustomerChanged(ChangeEventArgs e) {  // This is the event after selection is made.
    int iArgValue = Convert.ToInt32(e.Value);
    _ddlCustomer_Value = Convert.ToInt32(e.Value);

    Customer customer = _ListFilteredCustomers!.Where(rec => rec.UID_CUSTOMER == _ddlCustomer_Value).FirstOrDefault();
    if (customer != null) {
        _SelectedCustUID = customer.UID_CUSTOMER;
        _SelectedCustName = customer.TXT_CUSTOMER_NAME;
    }

    // Callback to Parent.
    await OnCustomerSelection.InvokeAsync(_ddlCustomer_Value);

}

Body:
OnParametersSetAsync and OnParametersSet will fire whenever a parameter changes, even if the value is the same as before. You can write some code to avoid this.

Example: Is previous parameter value the same as current ? skip load : load

private string _cachedValue;

[Parameter]
public string parameterValue { get; set; }

protected override async Task OnParametersSetAsync()
{
    if (parameterValue != _cachedValue)
    {
        _cachedValue = parameterValue;
        LoadComponent();
    }
}

private void LoadComponent() {
    //...
}

The above is just an example of one method of doing this. Use logic that suits your code.


问:
Are C# events synchronous?
There are two parts to this question:

Does raising an event block the thread, or does it start execution of EventHandlers asynchronously and the thread goes continues on at the same time?

Are the individual EventHandlers (subscribed to the event) run synchronously one after another, or are they run asynchronously with no guarantee that others aren't running at the same time?

答: Events are just arrays of delegates. As long as delegate call is synchronous, events are also synchronous.</p>

Title: Are C# events synchronous?

ContentLicense: CC BY-SA 3.0


问:
SPARQL returning empty result when passing MIN(?date1) from subquery into outer query, with BIND((YEAR(?minDate) - YEAR(?date2)) AS ?diffDate)
<This question is now resolved, see comment by Valerio Cocchi>

I am trying to pass a variable from a subquery, that takes the minimum date of a set of dates ?date1 belonging to ?p and passes this to the outer query, which then takes another date ?date2 belonging to ?p (there can be at most 1 ?date2 for every ?p) and subtracts ?minDate from ?date2 to get an integer value for the number of years between. I am getting a blank value for this, i.e. ?diffDate returns no value.

I am using Fuseki version 4.3.2. Here is an example of the query:

```<code>SELECT ?p ?minDate ?date2 ?diffDate
  {
  ?p a abc:P;
    abc:hasAnotherDate ?date2.
    BIND((YEAR(?minDate) - YEAR(?date2)) AS ?diffDate)
  {
  SELECT ?p (MIN(?date1) as ?minDate)
  WHERE
  {
  ?p a abc:P;
    abc:hasDate ?date1.

  } group by ?p
    }
  }
</code>```

and an example of the kind of result I am getting:

|-?p----|-----------------?minDate-------------|-----------------?date2-------------         |?diffDate|

|<123>|20012-11-22T00:00:00"^^xsd:dateTime|2008-08-18T00:00:00"^^xsd:dateTime|   |

I would expect that ?diffDate would give me an integer value.  Am I missing something fundamental about how subqueries work in SPARQL?

答:
It seems you have encountered quite an obscure part of the SPARQL spec, namely how BIND works.

Normally SPARQL is evaluated without regard for the position of atoms, i.e.

```<code>SELECT *
WHERE {
?a :p1 ?b .
?b :p2 ?c .}
</code>```

is the same query as:

```<code>SELECT *
WHERE {
?b :p2 ?c .
?a :p1 ?b .}
</code>```

However, BIND is position dependent, so e.g.:

```<code>SELECT *
WHERE {
?a :p1 ?b .
BIND(:john AS ?a)}
</code>```

is not a valid query, whereas:

```<code>SELECT *
WHERE {
BIND(:john AS ?a)
?a :p1 ?b .
}
</code>```

is entirely valid. The same applies to variables used inside of the BIND, which must be declared before the BIND appears.
See here for more.

To go back to your problem, your BIND is using the ?minDate variable before it has been bound, which is why it fails to produce a value for ?diffDate.

This query should do the trick:

```<code>SELECT ?p ?minDate ?date2 ?diffDate
  {
  ?p a abc:P;
    abc:hasAnotherDate ?date2.

  {
  SELECT ?p (MIN(?date1) as ?minDate)
  WHERE
  {
  ?p a abc:P;
    abc:hasDate ?date1.

  } group by ?p
    }
BIND((YEAR(?minDate) - YEAR(?date2)) AS ?diffDate)   #Put the BIND after all the variables it uses are bound.

  }
</code>```

Alternatively, you could evaluate the difference in the SELECT, like so:

```<code>SELECT ?p ?minDate ?date2 (YEAR(?minDate) - YEAR(?date2) AS ?diffDate)
  {
  ?p a abc:P;
    abc:hasAnotherDate ?date2.

  {
  SELECT ?p (MIN(?date1) as ?minDate)
  WHERE
  {
  ?p a abc:P;
    abc:hasDate ?date1.

  } group by ?p
    }

  }
</code>```

Body:
<This question is now resolved, see comment by Valerio Cocchi>

I am trying to pass a variable from a subquery, that takes the minimum date of a set of dates ?date1 belonging to ?p and passes this to the outer query, which then takes another date ?date2 belonging to ?p (there can be at most 1 ?date2 for every ?p) and subtracts ?minDate from ?date2 to get an integer value for the number of years between. I am getting a blank value for this, i.e. ?diffDate returns no value.

I am using Fuseki version 4.3.2. Here is an example of the query:

SELECT ?p ?minDate ?date2 ?diffDate
  {
  ?p a abc:P;
    abc:hasAnotherDate ?date2.
    BIND((YEAR(?minDate) - YEAR(?date2)) AS ?diffDate)
  {
  SELECT ?p (MIN(?date1) as ?minDate)
  WHERE
  {
  ?p a abc:P;
    abc:hasDate ?date1.

  } group by ?p
    }
  }

and an example of the kind of result I am getting:

|-?p----|-----------------?minDate-------------|-----------------?date2-------------         |?diffDate|

|<123>|20012-11-22T00:00:00"^^xsd:dateTime|2008-08-18T00:00:00"^^xsd:dateTime|   |

I would expect that ?diffDate would give me an integer value.  Am I missing something fundamental about how subqueries work in SPARQL?

Body:
It seems you have encountered quite an obscure part of the SPARQL spec, namely how BIND works.

Normally SPARQL is evaluated without regard for the position of atoms, i.e.

SELECT *
WHERE {
?a :p1 ?b .
?b :p2 ?c .}

is the same query as:

SELECT *
WHERE {
?b :p2 ?c .
?a :p1 ?b .}

However, BIND is position dependent, so e.g.:

SELECT *
WHERE {
?a :p1 ?b .
BIND(:john AS ?a)}

is not a valid query, whereas:

SELECT *
WHERE {
BIND(:john AS ?a)
?a :p1 ?b .
}

is entirely valid. The same applies to variables used inside of the BIND, which must be declared before the BIND appears.
See here for more.

To go back to your problem, your BIND is using the ?minDate variable before it has been bound, which is why it fails to produce a value for ?diffDate.

This query should do the trick:

SELECT ?p ?minDate ?date2 ?diffDate
  {
  ?p a abc:P;
    abc:hasAnotherDate ?date2.

  {
  SELECT ?p (MIN(?date1) as ?minDate)
  WHERE
  {
  ?p a abc:P;
    abc:hasDate ?date1.

  } group by ?p
    }
BIND((YEAR(?minDate) - YEAR(?date2)) AS ?diffDate)   #Put the BIND after all the variables it uses are bound.

  }

Alternatively, you could evaluate the difference in the SELECT, like so:

SELECT ?p ?minDate ?date2 (YEAR(?minDate) - YEAR(?date2) AS ?diffDate)
  {
  ?p a abc:P;
    abc:hasAnotherDate ?date2.

  {
  SELECT ?p (MIN(?date1) as ?minDate)
  WHERE
  {
  ?p a abc:P;
    abc:hasDate ?date1.

  } group by ?p
    }

  }


问:
Macbook M1 chip fixing zsh: command not found: brew error
I'm trying to using brew install sourcery command but I getting zsh: command not found: brew error!

I'm installed homebrew with using bellow command:

```<code>/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
</code>```

is there any way to fix this problem on the Macbook with M1 chip?

答:
Run next commands one by one:</p>
```<code>/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

echo 'eval $(/opt/homebrew/bin/brew shellenv)' >> /Users/$USER/.zprofile

eval $(/opt/homebrew/bin/brew shellenv)

brew help
</code>```

Body:
I'm trying to using brew install sourcery command but I getting zsh: command not found: brew error!

I'm installed homebrew with using bellow command:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

is there any way to fix this problem on the Macbook with M1 chip?

Body:
Run next commands one by one:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

echo 'eval $(/opt/homebrew/bin/brew shellenv)' >> /Users/$USER/.zprofile

eval $(/opt/homebrew/bin/brew shellenv)

brew help


问:
TypeError: [] is not a function
I am making a Discord bot command handler, and I keep getting this error:

```<code>(await PG(`${process.cwd()}/Commands/*/*js`)).map(async (file) => {
    ^

TypeError: [] is not a function
</code>```

Here is my code:

const { Perms } = require('../Validation/Permissions');
const { Client } = require('discord.js')
const { promisify } = require("util")
const { glob } = require('glob');
const PG = promisify(glob)
const Ascii = require('ascii-table')

/**
 * @param {Client} client
*/

module.exports = async (client) => {
    const Table = new Ascii('Command Loaded')

    CommandsArray = []

    (await PG(`${process.cwd()}/Commands/*/*js`)).map(async (file) => {
        const command = require(file);

        if (!command.name)
        return Table.addRow(file.split("/")[7], 'FAILED', 'Missing a name.')

        if (!command.description)
        return Table.addRow(command.name, 'FAILED', 'Missing the description.')

        if (command.permission) {
            if (Perms.includes(command.permission))
            command.defaultPermission = false;
            else
            return Table.addRow(command.name,'FAILED','Permission is invalid')
        }

        client.commands.set(command.name, command);
        CommandsArray.push(command);

        await Table.addRow(command.name, 'SUCCESSFUL');
    })

    console.log(Table.toString())

    // Permissions check //

    client.on('ready', async() => {
        const MainGuild = await client.guilds.cache.get('940180806696058910');

        MainGuild.commands.set(CommandsArray).then(async (command) => {
            const Roles = (commandName) => {
                const cmdPerms = CommandsArray.find((c) => c.name === commandName).permission
                if (!cmdPerms) return null;

                return MainGuild.roles.cache.filter((r) => r.permissions.has(cmdPerms))
            }

            const fullPermissions = command.reduce((accumulator, r) => {
                const roles = Roles(r.name);
                if (!roles) return accumulator;

                const permissions = roles.reduce((a, r) => {
                    return [...a,{id: r.id, type: 'ROLE', permission: true}]
                }, [])

                return [...accumulator, {id: r.id, permissions}]
            }, [])

            await MainGuild.commands.permissions.set({ fullPermissions });

        })

    })
}
```

I've done some googling, but I was unable to find anything related to just [], type error usually appears when there is a spelling mistake in your code. I have gone through my code numerous times and have been completely unable to find any mistakes, I just cannot figure this out.
I would really appreciate some help, thank you!

答:
Please use semi-colons!

Add ; onto the line above the PG where you define an empty array, JS sees the array and also brackets right after and this thinks you are executing a function because JS when compiled does not look at lines or spacing.

CommandsArray = [];

(await PG(`${process.cwd()}/Commands/*/*js`)).map(async (file) => {
```

Title: TypeError: [] is not a function

Body:
I am making a Discord bot command handler, and I keep getting this error:

(await PG(`${process.cwd()}/Commands/*/*js`)).map(async (file) => {
    ^

TypeError: [] is not a function

Here is my code:

const { Perms } = require('../Validation/Permissions');
const { Client } = require('discord.js')
const { promisify } = require("util")
const { glob } = require('glob');
const PG = promisify(glob)
const Ascii = require('ascii-table')

/**
 * @param {Client} client
*/

module.exports = async (client) => {
    const Table = new Ascii('Command Loaded')

    CommandsArray = []

    (await PG(`${process.cwd()}/Commands/*/*js`)).map(async (file) => {
        const command = require(file);

        if (!command.name)
        return Table.addRow(file.split("/")[7], 'FAILED', 'Missing a name.')

        if (!command.description)
        return Table.addRow(command.name, 'FAILED', 'Missing the description.')

        if (command.permission) {
            if (Perms.includes(command.permission))
            command.defaultPermission = false;
            else
            return Table.addRow(command.name,'FAILED','Permission is invalid')
        }

        client.commands.set(command.name, command);
        CommandsArray.push(command);

        await Table.addRow(command.name, 'SUCCESSFUL');
    })

    console.log(Table.toString())

    // Permissions check //

    client.on('ready', async() => {
        const MainGuild = await client.guilds.cache.get('940180806696058910');

        MainGuild.commands.set(CommandsArray).then(async (command) => {
            const Roles = (commandName) => {
                const cmdPerms = CommandsArray.find((c) => c.name === commandName).permission
                if (!cmdPerms) return null;

                return MainGuild.roles.cache.filter((r) => r.permissions.has(cmdPerms))
            }

            const fullPermissions = command.reduce((accumulator, r) => {
                const roles = Roles(r.name);
                if (!roles) return accumulator;

                const permissions = roles.reduce((a, r) => {
                    return [...a,{id: r.id, type: 'ROLE', permission: true}]
                }, [])

                return [...accumulator, {id: r.id, permissions}]
            }, [])

            await MainGuild.commands.permissions.set({ fullPermissions });

        })

    })
}

I've done some googling, but I was unable to find anything related to just [], type error usually appears when there is a spelling mistake in your code. I have gone through my code numerous times and have been completely unable to find any mistakes, I just cannot figure this out.
I would really appreciate some help, thank you!


问:
visibility of python output from bash
I've python code that includes tqdm code.
the bash build docker image and container however I can't see any output from the container(in CLI).

```<code>#!/bin/sh
docker build . -t traffic
docker run -d --name traffic_con traffic
docker wait traffic_con
docker cp -a traffic_con:/usr/TrafficMannager/out/data/. ./out/data/
docker rm /traffic_con
docker rmi /traffic
</code>```

I've tried to run the container on interactive mode (-it) however it's throwing an error

[EDIT:]
Docker file:

```<code>FROM cityflowproject/cityflow

# Create a folder we'll work in
WORKDIR /usr/TrafficMannager

# Upgrade installed packages
RUN apt-get update && apt-get upgrade -y && apt-get clean

# Install vim to open & edit code\text files
RUN apt-get install -y vim

# Install all python code depentences
RUN pip install gym && \
    pip install numpy && \
    pip install IPython && \
    pip install torch && \
    python -m pip install python-dotenv &&\
    pip install tqdm

COPY . .

CMD chmod u+x script/container_instructions.sh; ./script/container_instructions.sh
</code>```

container_instructions:

```<code>#!/bin/sh
pip install lib/extern/CityFlow/.
python main.py
</code>```

答:
You run the Docker container in the background, then immediately docker wait for it.  If you run the container in the foreground instead, you'll see its output on stdout, and the docker run command will complete when the container exits.

docker run --name traffic_con traffic  # without -d
```
<p>Given the wrapper script you show, you may find this setup much easier to run in a Python virtual environment.  Ignore all the Docker parts and run:</p>
<pre class="lang-sh prettyprint-override"><code>python3 -m venv venv
./venv/bin/pip install gym numpy IPython torch python-dotenv tqdm lib/extern/CityFlow
./venv/bin/python3 main.py
</code>```

The script will directly write to ./out/data on the host system, without the long-winded privileged script to copy data out.

If you really do need a container here, you can also mount the output directory into the container to avoid the manual copy step.

#!/bin/sh
docker build . -t traffic
docker run --rm -v "$PWD/out/data:/usr/TrafficMannager/out/data" traffic
docker rmi traffic
```

Title: visibility of python output from bash

Body:
I've python code that includes tqdm code.
the bash build docker image and container however I can't see any output from the container(in CLI).

#!/bin/sh
docker build . -t traffic
docker run -d --name traffic_con traffic
docker wait traffic_con
docker cp -a traffic_con:/usr/TrafficMannager/out/data/. ./out/data/
docker rm /traffic_con
docker rmi /traffic

I've tried to run the container on interactive mode (-it) however it's throwing an error

[EDIT:]
Docker file:

FROM cityflowproject/cityflow

# Create a folder we'll work in
WORKDIR /usr/TrafficMannager

# Upgrade installed packages
RUN apt-get update && apt-get upgrade -y && apt-get clean

# Install vim to open & edit code\text files
RUN apt-get install -y vim

# Install all python code depentences
RUN pip install gym && \
    pip install numpy && \
    pip install IPython && \
    pip install torch && \
    python -m pip install python-dotenv &&\
    pip install tqdm

COPY . .

CMD chmod u+x script/container_instructions.sh; ./script/container_instructions.sh

container_instructions:

#!/bin/sh
pip install lib/extern/CityFlow/.
python main.py

Body:
You run the Docker container in the background, then immediately docker wait for it.  If you run the container in the foreground instead, you'll see its output on stdout, and the docker run command will complete when the container exits.

docker run --name traffic_con traffic  # without -d

Given the wrapper script you show, you may find this setup much easier to run in a Python virtual environment.  Ignore all the Docker parts and run:

python3 -m venv venv
./venv/bin/pip install gym numpy IPython torch python-dotenv tqdm lib/extern/CityFlow
./venv/bin/python3 main.py

The script will directly write to ./out/data on the host system, without the long-winded privileged script to copy data out.

If you really do need a container here, you can also mount the output directory into the container to avoid the manual copy step.

#!/bin/sh
docker build . -t traffic
docker run --rm -v "$PWD/out/data:/usr/TrafficMannager/out/data" traffic
docker rmi traffic


问:
./node_modules/@prisma/client/runtime/index.js:35865:17-40 - Error: Module not found: Error: Can't resolve '_http_common'
I'm using angular universal with express-engine, the build for server fails with this error message:

./node_modules/@prisma/client/runtime/index.js:35865:17-40 - Error: Module not found: Error: Can't resolve '_http_common' in 'C:\Users\jude\Documents\Portfolio\evaluation-system\evaluation-system-app\node_modules@prisma\client\runtime'

答:
After some google research, i figured out how to fix this bug:

install custom-webpack ( npm install @angular-builders/custom-webpack --save-dev )

update angular.json file by doing the following:
replace this:

"server": {
"builder": "@angular-devkit/build-angular:server",
.
.
.
}

to this

"server": {
"builder": "@angular-builders/custom-webpack:server",
}

update the options section in the server

"server": {
"builder": "@angular-builders/custom-webpack:server",
"options": {
.
.
.
"customWebpackConfig": {
"path": "./webpack.config.js"
}
}

Now create a new file at the root of you app with name "webpack.config.js"

inside webpack.config.js add these

module.exports = {
externals: ["_http_common", "encoding"],
};

That's it. I hope this helps. happy coding!!!


问:
Run inner join query in Grafana where datasource is influx
I need to run inner join query in Grafana where datasource is InfluxDB.
In sql query will be:

```<code>SELECT t.status,count(t.taskName) FROM TasksStatus t
INNER JOIN TasksStatus  s
ON t.taskName = s.taskName
WHERE t.modified > s.modified
GROUP BY t.status;
</code>```

Getting Error while running in grafana
InfluxDB Error: error parsing query: found t, expected ; at line 1, char 71

答:
https://docs.influxdata.com/influxdb/v1.8/query_language/

InfluxQL, the InfluxDB SQL-like query language

It is only SQL-like, but it not a SQL language. InfluxQL doc doesn't mention any support for INNER JOIN, so it is not suported by InfluxQL.

Body:
I need to run inner join query in Grafana where datasource is InfluxDB.
In sql query will be:

SELECT t.status,count(t.taskName) FROM TasksStatus t
INNER JOIN TasksStatus  s
ON t.taskName = s.taskName
WHERE t.modified > s.modified
GROUP BY t.status;

Getting Error while running in grafana
InfluxDB Error: error parsing query: found t, expected ; at line 1, char 71


问:
When applying function to dataframe error that column is htest object and that all columns in tibble must be vectors
I am trying to run function

```<code>growth<- function(x){
  cor.test(df3$H1, x, method = "spearman", exact = FALSE)
}

v1<-map_dfr(df3, growth)
</code>```

where str(df3) shows all to be numerical. When I run this however it says

Error: All columns in a tibble must be vectors.

x Column H1 is a htest object.

x Column laz_12 is a htest object.

x Column waz_12 is a htest object.

x Column hcz_12 is a htest object.

x Column maz_12 is a htest object.

x ... and 4 more problems.

答:
For map_dfr to work the output from the function needs to be dataframe or tibble. Output from growth function is an htest object. Probably you can tidy the output to return a tibble.

Here's an example with mtcars dataset.

```<code>growth<- function(x){
    broom::tidy(cor.test(mtcars$mpg, x, method = "spearman", exact = FALSE))
}

v1 <- purrr::map_dfr(mtcars, growth, .id = "col")
v1

#   col   estimate statistic  p.value method                        alternative
#   <chr>    <dbl>     <dbl>    <dbl> <chr>                           <chr>
# 1 mpg      1            0  0        Spearman's rank correlation rho two.sided
# 2 cyl     -0.911    10425. 4.69e-13 Spearman's rank correlation rho two.sided
# 3 disp    -0.909    10415. 6.37e-13 Spearman's rank correlation rho two.sided
# 4 hp      -0.895    10337. 5.09e-12 Spearman's rank correlation rho two.sided
# 5 drat     0.651     1902. 5.38e- 5 Spearman's rank correlation rho two.sided
# 6 wt      -0.886    10292. 1.49e-11 Spearman's rank correlation rho two.sided
# 7 qsec     0.467     2908. 7.06e- 3 Spearman's rank correlation rho two.sided
# 8 vs       0.707     1601. 6.19e- 6 Spearman's rank correlation rho two.sided
# 9 am       0.562     2390. 8.16e- 4 Spearman's rank correlation rho two.sided
#10 gear     0.543     2495. 1.33e- 3 Spearman's rank correlation rho two.sided
#11 carb    -0.657     9043. 4.34e- 5 Spearman's rank correlation rho two.sided
</code>```

Body:
I am trying to run function

growth<- function(x){
  cor.test(df3$H1, x, method = "spearman", exact = FALSE)
}

v1<-map_dfr(df3, growth)

where str(df3) shows all to be numerical. When I run this however it says

Error: All columns in a tibble must be vectors.

x Column H1 is a htest object.

x Column laz_12 is a htest object.

x Column waz_12 is a htest object.

x Column hcz_12 is a htest object.

x Column maz_12 is a htest object.

x ... and 4 more problems.

Body:
For map_dfr to work the output from the function needs to be dataframe or tibble. Output from growth function is an htest object. Probably you can tidy the output to return a tibble.

Here's an example with mtcars dataset.

growth<- function(x){
    broom::tidy(cor.test(mtcars$mpg, x, method = "spearman", exact = FALSE))
}

v1 <- purrr::map_dfr(mtcars, growth, .id = "col")
v1

#   col   estimate statistic  p.value method                        alternative
#   <chr>    <dbl>     <dbl>    <dbl> <chr>                           <chr>
# 1 mpg      1            0  0        Spearman's rank correlation rho two.sided
# 2 cyl     -0.911    10425. 4.69e-13 Spearman's rank correlation rho two.sided
# 3 disp    -0.909    10415. 6.37e-13 Spearman's rank correlation rho two.sided
# 4 hp      -0.895    10337. 5.09e-12 Spearman's rank correlation rho two.sided
# 5 drat     0.651     1902. 5.38e- 5 Spearman's rank correlation rho two.sided
# 6 wt      -0.886    10292. 1.49e-11 Spearman's rank correlation rho two.sided
# 7 qsec     0.467     2908. 7.06e- 3 Spearman's rank correlation rho two.sided
# 8 vs       0.707     1601. 6.19e- 6 Spearman's rank correlation rho two.sided
# 9 am       0.562     2390. 8.16e- 4 Spearman's rank correlation rho two.sided
#10 gear     0.543     2495. 1.33e- 3 Spearman's rank correlation rho two.sided
#11 carb    -0.657     9043. 4.34e- 5 Spearman's rank correlation rho two.sided


问:
How do I do large non-blocking updates in PostgreSQL?
I want to do a large update on a table in PostgreSQL, but I don't need the transactional integrity to be maintained across the entire operation, because I know that the column I'm changing is not going to be written to or read during the update.  I want to know if there is an easy way in the psql console to make these types of operations faster.

For example, let's say I have a table called "orders" with 35 million rows, and I want to do this:

```<code>UPDATE orders SET status = null;
</code>```

To avoid being diverted to an offtopic discussion, let's assume that all the values of status for the 35 million columns are currently set to the same (non-null) value, thus rendering an index useless.

The problem with this statement is that it takes a very long time to go into effect (solely because of the locking), and all changed rows are locked until the entire update is complete.    This update might take 5 hours, whereas something like

```<code>UPDATE orders SET status = null WHERE (order_id > 0 and order_id < 1000000);
</code>```

might take 1 minute.   Over 35 million rows, doing the above and breaking it into chunks of 35 would only take 35 minutes and save me 4 hours and 25 minutes.

I could break it down even further with a script (using pseudocode here):

```<code>for (i = 0 to 3500) {
  db_operation ("UPDATE orders SET status = null
                 WHERE (order_id >" + (i*1000)"
             + " AND order_id <" + ((i+1)*1000) " +  ")");
}
</code>```

This operation might complete in only a few minutes, rather than 35.

So that comes down to what I'm really asking.  I don't want to write a freaking script to break down operations every single time I want to do a big one-time update like this.   Is there a way to accomplish what I want entirely within SQL?

答:
I would use CTAS:</p>

```<code>begin;
create table T as select col1, col2, ..., <new value>, colN from orders;
drop table orders;
alter table T rename to orders;
commit;
</code>```

OwnerDisplayName: S D

LastEditorDisplayName: S D

Body:
I want to do a large update on a table in PostgreSQL, but I don't need the transactional integrity to be maintained across the entire operation, because I know that the column I'm changing is not going to be written to or read during the update.  I want to know if there is an easy way in the psql console to make these types of operations faster.

For example, let's say I have a table called "orders" with 35 million rows, and I want to do this:

UPDATE orders SET status = null;

To avoid being diverted to an offtopic discussion, let's assume that all the values of status for the 35 million columns are currently set to the same (non-null) value, thus rendering an index useless.

The problem with this statement is that it takes a very long time to go into effect (solely because of the locking), and all changed rows are locked until the entire update is complete.    This update might take 5 hours, whereas something like

UPDATE orders SET status = null WHERE (order_id > 0 and order_id < 1000000);

might take 1 minute.   Over 35 million rows, doing the above and breaking it into chunks of 35 would only take 35 minutes and save me 4 hours and 25 minutes.

I could break it down even further with a script (using pseudocode here):

for (i = 0 to 3500) {
  db_operation ("UPDATE orders SET status = null
                 WHERE (order_id >" + (i*1000)"
             + " AND order_id <" + ((i+1)*1000) " +  ")");
}

This operation might complete in only a few minutes, rather than 35.

So that comes down to what I'm really asking.  I don't want to write a freaking script to break down operations every single time I want to do a big one-time update like this.   Is there a way to accomplish what I want entirely within SQL?

Body:
I would use CTAS:

begin;
create table T as select col1, col2, ..., <new value>, colN from orders;
drop table orders;
alter table T rename to orders;
commit;


问:
Firebird SQL join recommendation
I am using Firebird 3.0. I have 2 tables and I want to get the following result with one query, but I couldn't do this.

USERS Table

ID
USER_NAME

10
User1

20
User2

30
User3

40
User4

50
User5

CALL_HISTORY Table

ID
USER_ID
START_TIME
CALL_DIRECTION
STATUS
EXTEN
REMOTE_USER
DURATION

1
10
09.02.2022
I
3
1007
00000000000
63

2
10
09.02.2022
I
3
1007
00000000000
37

3
10
09.02.2022
I
4
1007
00000000000
0

4
20
09.02.2022
O
3
1008
00000000000
33

5
20
09.02.2022
O
3
1008
00000000000
47

6
20
09.02.2022
O
3
1008
00000000000
10

7
30
09.02.2022
O
3
1028
00000000000
121

8
30
09.02.2022
O
3
1028
00000000000
37

9
30
09.02.2022
O
3
1028
00000000000
73

10
30
09.02.2022
I
3
1028
00000000000
61

11
40
09.02.2022
I
4
1013
00000000000
0

Expected result

USER_NAME
NUM_INCOMING_CALL
DURATION_INCOMING_CALL
NUM_OUTGOING_CALL
DURATION_OUTGOING_CALL

User1
2
100
null
null

User2
null
null
3
90

User3
1
61
3
231

Attempt

Here is the query I tried (and there is also a dbfiddle):

```<code>SELECT
  outgoing_call.user_name,
  cast(incoming_call.num_incoming_call as bigint) as num_incoming_call,
  incoming_call.duration_incoming_call,
  cast(outgoing_call.num_outgoing_call as bigint) as num_outgoing_call,
  outgoing_call.duration_outgoing_call
from
  (select user_id, (select user_name from "USERS" where id=sch.user_id) user_name, count(id) num_outgoing_call, sum(duration) duration_outgoing_call
    from "CALL_HISTORY" sch
    where CALL_DIRECTION='O' AND (START_TIME BETWEEN '2022-01-01' AND '2022-03-01') AND (STATUS=3) group by user_id
  ) as outgoing_call
full join
  (select user_id, (select user_name from "USERS" where id=sch.user_id) user_name, count(id) num_incoming_call, sum(duration) duration_incoming_call
    from "CALL_HISTORY" sch
    where CALL_DIRECTION='I' AND (START_TIME BETWEEN '2022-01-01' AND '2022-03-01') AND (STATUS=3) group by user_id
  ) as incoming_call
on outgoing_call.user_name=incoming_call.user_name
</code>```

The result set is not what I want. I also tried the query as "Right Join", "Left Join" and "Full Join" but, it didn't get the result I expected. Can a single query sentence be written to see the expected result?

答:
Everything is much simpler than you think. All you need is a simple join and conditional aggregates like sum(case when call_direction='I' then duration end).

Look at this: https://dbfiddle.uk/?rdbms=firebird_3.0&fiddle=1d9cbe0e617f89d8bf698b1a22d4bd76

Title: Firebird SQL join recommendation

Body:
I am using Firebird 3.0. I have 2 tables and I want to get the following result with one query, but I couldn't do this.

USERS Table

ID
USER_NAME

10
User1

20
User2

30
User3

40
User4

50
User5

CALL_HISTORY Table

ID
USER_ID
START_TIME
CALL_DIRECTION
STATUS
EXTEN
REMOTE_USER
DURATION

1
10
09.02.2022
I
3
1007
00000000000
63

2
10
09.02.2022
I
3
1007
00000000000
37

3
10
09.02.2022
I
4
1007
00000000000
0

4
20
09.02.2022
O
3
1008
00000000000
33

5
20
09.02.2022
O
3
1008
00000000000
47

6
20
09.02.2022
O
3
1008
00000000000
10

7
30
09.02.2022
O
3
1028
00000000000
121

8
30
09.02.2022
O
3
1028
00000000000
37

9
30
09.02.2022
O
3
1028
00000000000
73

10
30
09.02.2022
I
3
1028
00000000000
61

11
40
09.02.2022
I
4
1013
00000000000
0

Expected result

USER_NAME
NUM_INCOMING_CALL
DURATION_INCOMING_CALL
NUM_OUTGOING_CALL
DURATION_OUTGOING_CALL

User1
2
100
null
null

User2
null
null
3
90

User3
1
61
3
231

Attempt

Here is the query I tried (and there is also a dbfiddle):

SELECT
  outgoing_call.user_name,
  cast(incoming_call.num_incoming_call as bigint) as num_incoming_call,
  incoming_call.duration_incoming_call,
  cast(outgoing_call.num_outgoing_call as bigint) as num_outgoing_call,
  outgoing_call.duration_outgoing_call
from
  (select user_id, (select user_name from "USERS" where id=sch.user_id) user_name, count(id) num_outgoing_call, sum(duration) duration_outgoing_call
    from "CALL_HISTORY" sch
    where CALL_DIRECTION='O' AND (START_TIME BETWEEN '2022-01-01' AND '2022-03-01') AND (STATUS=3) group by user_id
  ) as outgoing_call
full join
  (select user_id, (select user_name from "USERS" where id=sch.user_id) user_name, count(id) num_incoming_call, sum(duration) duration_incoming_call
    from "CALL_HISTORY" sch
    where CALL_DIRECTION='I' AND (START_TIME BETWEEN '2022-01-01' AND '2022-03-01') AND (STATUS=3) group by user_id
  ) as incoming_call
on outgoing_call.user_name=incoming_call.user_name

The result set is not what I want. I also tried the query as "Right Join", "Left Join" and "Full Join" but, it didn't get the result I expected. Can a single query sentence be written to see the expected result?


问:
How to use ArrayFormula with my Sum fuctions?
Google Sheet Here

I am new to Google sheet and can't figure a good way to do this.
I have tried doing the manual addition way, I got the idea, but am clueless on how to use in my own function :

```<code>= ArrayFormula(SUM
(Product (SUMIF(F2:L,"=4"),p_4),
 Product (SUMIF(F2:L,"=3"),p_3),
 Product (SUMIF(F2:L,"=2"),p_2),
 Product (SUMIF(F2:L,"=1"),p_1)))
</code>```

Also, I am doing this so that the data from Google Form can get auto calculated.

答:
use:

```<code>=ARRAYFORMULA(IF(A2:A="",,MMULT(IFNA(F2:L*
 VLOOKUP(F2:L, 'Price Sheet'!A:B, 2, ), 0),
 SEQUENCE(COLUMNS(F:L), 1, 1, ))))
</code>```

Body:
Google Sheet Here

I am new to Google sheet and can't figure a good way to do this.
I have tried doing the manual addition way, I got the idea, but am clueless on how to use in my own function :

= ArrayFormula(SUM
(Product (SUMIF(F2:L,"=4"),p_4),
 Product (SUMIF(F2:L,"=3"),p_3),
 Product (SUMIF(F2:L,"=2"),p_2),
 Product (SUMIF(F2:L,"=1"),p_1)))

Also, I am doing this so that the data from Google Form can get auto calculated.

Body:
use:

=ARRAYFORMULA(IF(A2:A="",,MMULT(IFNA(F2:L*
 VLOOKUP(F2:L, 'Price Sheet'!A:B, 2, ), 0),
 SEQUENCE(COLUMNS(F:L), 1, 1, ))))


问:
Node convert Decimal to Bytes - Avro Schema Kafka / Kafkajs
I am using http://kafka.js.org/ to produce messages to Kafka, one of the schemas I am working on is a decimal byte type:

```<code>{"type": "bytes", "logicalType": "decimal", "precision": 11, "scale": 2}
</code>```

I am looking for some guidance on how I can convert a decimal in Node to a byte value to match the above schema.

Thanks in advance.

答:
You can try https://www.npmjs.com/package/@ovotech/avro-decimal

This package helped us resolve the same problem

Body:
I am using http://kafka.js.org/ to produce messages to Kafka, one of the schemas I am working on is a decimal byte type:

{"type": "bytes", "logicalType": "decimal", "precision": 11, "scale": 2}

I am looking for some guidance on how I can convert a decimal in Node to a byte value to match the above schema.

Thanks in advance.


问:
Angular 4+ ngOnDestroy() in service - destroy observable
In an angular application we have ngOnDestroy() lifecycle hook for a component / directive and we use this hook to unsubscribe the observables.

I want to clear / destory observable that are created in an @injectable() service.
I saw some posts saying that ngOnDestroy() can be used in a service as well.

But, is it a good practice and only way to do so and When will it get called ?
someone please clarify.

答: I recommend using .pipe(take(1)).subscribe(). To avoid setting up an ongoing subscription.</p>


问:
Can't connect to localhost in React Native WebView
I started up a simple http server (from here):

```<code>from wsgiref.simple_server import make_server

def app(environ, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    yield b"<h1>Goodbye, World!</h1>"

server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
</code>```

Ran it using:

```<code>python3 simple_serve.py
</code>```

Redirecting to http://127.0.0.1:8080/ displays "Goodbye, World!".

I then created a new React Native Project and changed index.android.js to:

```<code>import React, { Component } from 'react';
import {
  AppRegistry,
  WebView,
} from 'react-native';

export default class WebTest extends Component {
  render() {
    return (
      <WebView
        source= {{ uri: "http://127.0.0.1:8080/" }}
      />
    );
  }
}

AppRegistry.registerComponent('WebTest', () => WebTest);
</code>```

"Goodbye, World!" doesn't show up, and I get a warning that says:

Encountered an error loading page
  {"canGoForward"false,"code":-6,"canGoBack":false,"description":"net::ERR_CONNECTION_REFUSED","loading":false,"title":"","url":"http://127.0.0.1:8080/","target":5}

For reference, changing http://127.0.0.1:8080/ to https://www.google.com works.

答: use it like that http://10.0.2.2://your port num this will work definetly</p>

Body:
I started up a simple http server (from here):

from wsgiref.simple_server import make_server

def app(environ, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    yield b"
Goodbye, World!
"

server = make_server('127.0.0.1', 8080, app)
server.serve_forever()

Ran it using:

python3 simple_serve.py

Redirecting to http://127.0.0.1:8080/ displays "Goodbye, World!".

I then created a new React Native Project and changed index.android.js to:

import React, { Component } from 'react';
import {
  AppRegistry,
  WebView,
} from 'react-native';

export default class WebTest extends Component {
  render() {
    return (
      <WebView
        source= {{ uri: "http://127.0.0.1:8080/" }}
      />
    );
  }
}

AppRegistry.registerComponent('WebTest', () => WebTest);

"Goodbye, World!" doesn't show up, and I get a warning that says:

Encountered an error loading page
  {"canGoForward"false,"code":-6,"canGoBack":false,"description":"net::ERR_CONNECTION_REFUSED","loading":false,"title":"","url":"http://127.0.0.1:8080/","target":5}

For reference, changing http://127.0.0.1:8080/ to https://www.google.com works.


问:
Convert decimal mark when reading numbers as input
I have a CSV file with data reading that I want to read into Python. I get lists that contain strings like "2,5". Now doing float("2,5") does not work, because it has the wrong decimal mark.

How do I read this into Python as 2.5?

答:
Try replacing all the decimal commas with decimal dots:

```<code>floatAsStr = "2,5"
floatAsStr = floatAsStr.replace(",", ".");
myFloat = float(floatAsStr)
</code>```

The function replace, of course, work on any substring as python does now differentiate between char and string.

Body:
Try replacing all the decimal commas with decimal dots:

floatAsStr = "2,5"
floatAsStr = floatAsStr.replace(",", ".");
myFloat = float(floatAsStr)

The function replace, of course, work on any substring as python does now differentiate between char and string.


问:
Apollo client not working on mobile browser
Using Apollo in react that's working on computer but it's not working on mobile browser, I have seen many solutions on here and github but they are all for version 2 or less, I'm using "@apollo/client": "^3.5.8" and here's where the occurs

```<code>        const getSignedUrl = async (file) => {

            try {
                const api = await mutationFunc({ variables: {
                    fileName: file[0].name,
                    email: currentUser.email
                }})

                .....

            } catch (error) {
                throw new Error('Unknown error')
            }
        }
</code>```

It does not even connect to the server, I just get Failed to fetch error.

According to the deprecated solutions, it has something to do with ApolloClient constructor, so here's my index file:

```<code>  import React from "react";
  import ReactDOM from "react-dom";
  import App from "./App";
  import {
    ApolloClient,
    InMemoryCache,
    ApolloProvider,
    HttpLink,
    createNetworkInterface
  } from "@apollo/client";

  // const client = new ApolloClient({
  //   link: new HttpLink({
  //   uri: Platform.select({
  //   ios: 'http://localhost:80/',
  //   android: 'http://10.0.2.2:80/',
  //   }),
  //   }),
  //   cache: new InMemoryCache(),
  //   });

  // const networkInterface = createNetworkInterface('/graphql')
  const client = new ApolloClient({
    // uri: 'http://localhost:8000/',
    link: new HttpLink({ uri: 'http://localhost:8000/' }),
    cache: new InMemoryCache()
  });

  ReactDOM.render(
    <ApolloProvider client={client}>
      <App />,
    </ApolloProvider>,
    document.getElementById("root")
  );
</code>```

EDIT

The API lives on my PC, so I tried changing the ApolloClient constructor uri to

```<code>const client = new ApolloClient({
    link: new HttpLink({ uri: http://192.168.1.101:8000' }),
    cache: new InMemoryCache()
  });
</code>```

I can also query the API directly on my phone using http://192.168.1.101:8000: Here is the query:

Here is the response from the API

and Here is the failed mutation on React side:

NOTE: I'm not uploading the image just send the name to get a pre-signed s3 url. But it's not even sending to the api.

答:
Where does your GraphQL server run? I assume it doesn't run on the mobile device. If so, you have to specify the URL of the server in Apollo client constructor.

http://localhost:8000/ --> http://myserver:8000/

And of course your mobile device should have access to port 8000 of myserver.

Body:
Using Apollo in react that's working on computer but it's not working on mobile browser, I have seen many solutions on here and github but they are all for version 2 or less, I'm using "@apollo/client": "^3.5.8" and here's where the occurs

        const getSignedUrl = async (file) => {

            try {
                const api = await mutationFunc({ variables: {
                    fileName: file[0].name,
                    email: currentUser.email
                }})

                .....

            } catch (error) {
                throw new Error('Unknown error')
            }
        }

It does not even connect to the server, I just get Failed to fetch error.

According to the deprecated solutions, it has something to do with ApolloClient constructor, so here's my index file:

  import React from "react";
  import ReactDOM from "react-dom";
  import App from "./App";
  import {
    ApolloClient,
    InMemoryCache,
    ApolloProvider,
    HttpLink,
    createNetworkInterface
  } from "@apollo/client";

  // const client = new ApolloClient({
  //   link: new HttpLink({
  //   uri: Platform.select({
  //   ios: 'http://localhost:80/',
  //   android: 'http://10.0.2.2:80/',
  //   }),
  //   }),
  //   cache: new InMemoryCache(),
  //   });

  // const networkInterface = createNetworkInterface('/graphql')
  const client = new ApolloClient({
    // uri: 'http://localhost:8000/',
    link: new HttpLink({ uri: 'http://localhost:8000/' }),
    cache: new InMemoryCache()
  });

  ReactDOM.render(
    <ApolloProvider client={client}>
      <App />,
    </ApolloProvider>,
    document.getElementById("root")
  );

EDIT

The API lives on my PC, so I tried changing the ApolloClient constructor uri to

const client = new ApolloClient({
    link: new HttpLink({ uri: http://192.168.1.101:8000' }),
    cache: new InMemoryCache()
  });

I can also query the API directly on my phone using http://192.168.1.101:8000: Here is the query:

Here is the response from the API

and Here is the failed mutation on React side:

NOTE: I'm not uploading the image just send the name to get a pre-signed s3 url. But it's not even sending to the api.


问:
How to do an inverse operation of a merge between two pandas dataframes by id column?
I am working on a project for university in which I received two dataframes:

```<code>      import pandas as pd

      df1 = pd.DataFrame({'id': ['0','1','2','3'],
                          'name': ['sensor', 'actuador', 'sensor', 'sensor'],
                          'type':['analog', 'analog', 'digital', 'analog']})

      print(df1)

      id    name        type
       0    sensor      analog
       1    actuador    analog
       2    sensor      digital
       3    sensor      analog

      df2 = pd.DataFrame({'inst': ['0','10','2','143'],
                          'number': [100, 200, 300, 400]})

     print(df2)

     inst   number
      0      100
     10      200
      2      300
    143      400
</code>```

I would like to check if the 'id' of df1 is different from the 'inst' of df2.
I would only need to return lines from df1 where the 'id' is not contained in the 'inst' of df2.

I thought of doing a merge between the dataframes using the 'id' and 'inst' columns as follows:

```<code>      merged_df = df1.merge(df2, left_on=['id'], right_on=['inst'])
</code>```

The output is:

```<code>     print(merged_df)

     id     name      type    inst    number
     0     sensor   analog     0      100
     2     sensor   digital    2      300
</code>```

However, the desired output is the opposite of this. I would like it to return the df1 with only the lines where the 'id' is not in 'inst'. Also, I would like it to return only the df1 columns.

The desired output is:

```<code>       print(df_result)

     id     name    type
      1   actuador  analog
      3   sensor    analog
</code>```

答:
If there is only one column use boolean indexing with inverted mask by Series.isin:

```<code>df_result = df1[~df1['id'].isin(df2['inst'])]
print (df_result)
  id      name    type
1  1  actuador  analog
3  3    sensor  analog
</code>```

If possible check per multiple columns is possible use alternative solution with indicator parameter and filtering left_only rows:

```<code>df_result = (df1.merge(df2, left_on=['id'], right_on=['inst'], how='left', indicator=True)
                .query("_merge == 'left_only'")
                .reindex(df1.columns, axis=1))

print (df_result)
  id      name    type
1  1  actuador  analog
3  3    sensor  analog
</code>```

Body:
I am working on a project for university in which I received two dataframes:

      import pandas as pd

      df1 = pd.DataFrame({'id': ['0','1','2','3'],
                          'name': ['sensor', 'actuador', 'sensor', 'sensor'],
                          'type':['analog', 'analog', 'digital', 'analog']})

      print(df1)

      id    name        type
       0    sensor      analog
       1    actuador    analog
       2    sensor      digital
       3    sensor      analog

      df2 = pd.DataFrame({'inst': ['0','10','2','143'],
                          'number': [100, 200, 300, 400]})

     print(df2)

     inst   number
      0      100
     10      200
      2      300
    143      400

I would like to check if the 'id' of df1 is different from the 'inst' of df2.
I would only need to return lines from df1 where the 'id' is not contained in the 'inst' of df2.

I thought of doing a merge between the dataframes using the 'id' and 'inst' columns as follows:

      merged_df = df1.merge(df2, left_on=['id'], right_on=['inst'])

The output is:

     print(merged_df)

     id     name      type    inst    number
     0     sensor   analog     0      100
     2     sensor   digital    2      300

However, the desired output is the opposite of this. I would like it to return the df1 with only the lines where the 'id' is not in 'inst'. Also, I would like it to return only the df1 columns.

The desired output is:

       print(df_result)

     id     name    type
      1   actuador  analog
      3   sensor    analog

Body:
If there is only one column use boolean indexing with inverted mask by Series.isin:

df_result = df1[~df1['id'].isin(df2['inst'])]
print (df_result)
  id      name    type
1  1  actuador  analog
3  3    sensor  analog

If possible check per multiple columns is possible use alternative solution with indicator parameter and filtering left_only rows:

df_result = (df1.merge(df2, left_on=['id'], right_on=['inst'], how='left', indicator=True)
                .query("_merge == 'left_only'")
                .reindex(df1.columns, axis=1))

print (df_result)
  id      name    type
1  1  actuador  analog
3  3    sensor  analog


问:
Returning a value from a response stream inside an upload function
I've created a function which uploads an imageFile to Node.js server & AWS Bucket

If I call response.stream.transform(utf8.decoder).listen((value) async {} the value is equal to the CloudFront URL where my picture is stored

I'm trying to extract this URL from my Upload function to use it in my app but I can't find how :

```<code>
  Future<String> upload(File imageFile) async {
    String url = '';

[...] // some code

    // add file to multipart
    request.files.add(multipartFile);

    // send
    var response = await request.send();

    // listen for response
    response.stream.transform(utf8.decoder).listen((value) async {
      print(value); // prints the URL

      url = value; // this value is the url where my picture is stored
// I'd like to use it outside this function
// I thought of returning it but I get an empty string
    });

    return url;
  }
</code>```

答:
response.stream is a ByteStream. Rather than calling listen, call bytesToString - details here.

So you replace the whole transform section with:

```<code>return await response.stream.bytesToString();
</code>```

Body:
I've created a function which uploads an imageFile to Node.js server & AWS Bucket

If I call response.stream.transform(utf8.decoder).listen((value) async {} the value is equal to the CloudFront URL where my picture is stored

I'm trying to extract this URL from my Upload function to use it in my app but I can't find how :

  Future<String> upload(File imageFile) async {
    String url = '';

[...] // some code

    // add file to multipart
    request.files.add(multipartFile);

    // send
    var response = await request.send();

    // listen for response
    response.stream.transform(utf8.decoder).listen((value) async {
      print(value); // prints the URL

      url = value; // this value is the url where my picture is stored
// I'd like to use it outside this function
// I thought of returning it but I get an empty string
    });

    return url;
  }

Body:
response.stream is a ByteStream. Rather than calling listen, call bytesToString - details here.

So you replace the whole transform section with:

return await response.stream.bytesToString();