问:
Laravel Websocket package issue with the latest Laravel, pusher, and Echo package
I am working on Laravel 9 where I install Laravel WebSocket, Laravel Echo, and Pusher PHP server.

By the way, I didn't use the official Pusher application, just using the package as per Laravel-WebSocket package documentation suggested.

User case - I want to update the site model value and send a notification (broadcast and mail) to the end user as soon as the user deletes a site.

Everything is installed and working fine but I found some glitches in the Laravel-WebSocket, Pusher package.

I have created the following event which will broadcast to the end user.

SiteDelete.php

```<code><?php

namespace App\Events;

use App\Models\Site;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class SiteDeleted implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * The site instance.
     *
     * @var \App\Models\Site
     */
    public $site;

    /**
     * The name of the queue connection to use when broadcasting the event.
     *
     * @var string
     */
    public $connection = 'database';

    /**
     * The name of the queue on which to place the broadcasting job.
     *
     * @var string
     */
    public $queue = 'default';

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Site $site)
    {
        $this->site = $site;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        // return new PrivateChannel('site.delete.'.$this->site->id); // this is not working.
        // return [new PrivateChannel('site.delete.'.$this->site->id)]; // this is not working.
        return [new PrivateChannel('site.delete.'.$this->site->id), new Channel('mock')]; // This will call but I need to pass two channels intentionally.
    }

    /**
     * Get the data to broadcast.
     *
     * @return array
     */
    public function broadcastWith()
    {
        return ['id' => $this->site->id];
    }
}
</code>```

app.js

```<code>Echo.private("site.delete.1")
.listen('SiteDeleted', (e) => {
    console.log("SiteDeleted");
    console.log(JSON.stringify(e));
})

Echo.private('App.Models.User.7')
.notification((notification) => {
    console.log("App.Models.User");
    console.log(notification);
});
</code>```

Problem

As you can see comments in my event class's broadcastOn method where I need to pass two channels. One is real and the second one is fake. So ultimately you need to pass at least two channels so the pusher request will have a channels parameter [which will work] but the channel parameter never works[i.e when you pass a single channel].

I can able to send custom events from the WebSocket GUI. i.e from http://localhost:8000/laravel-websockets URL. but those events are never caught by the front end unless I do it the dirty way.

The notifications are never caught by the front end due to this channel and channels parameter issue.

Dirty Way[Yes I know we should never touch the vendor folder but just curious to know why the things are not working]

I checked the vendor folder very deeply and I come to know, in the vendor/pusher/pusher-php-server/src/Pusher.php under the make_event function if I update the following line then it starts working without passing two channels.

vendor/pusher/pusher-php-server/src/Pusher.php

```<code>private function make_event(array $channels, string $event, $data, array $params = [], ?string $info = null, bool $already_encoded = false): array
{
    // if (count($channel_values) == 1) {
    //   $post_params['channel'] = $channel_values[0];
    // } else {
    //   $post_params['channels'] = $channel_values;
    // }

    $post_params['channels'] = $channel_values;
}
</code>```

My Research

As the WebSocket package suggests installing pusher-php-server version 3.0 but I install the latest one i.e 7. Version 3.0 is incompatible with Laravel 9. But I can't and don't want to install the older version.

I think the WebSocket package is not able to send the event and data on a single channel with a newer version of pusher-php-server.

I can't raise an issue (or blame it) for Pusher SDK because we are just replacing the package and I think the Pusher SDK package is working fine when you use their credentials(ie. you have to create an app on Pusher).

Even if you can check on the WebSocket dashboard i.e http://localhost:8000/laravel-websockets when you send the event it will never catch in the front end. But as soon as you update the Pusher.php file it starts catching an event on the front end.

due to the above reason, as you know the notification are sent to the user on their private channels, So I can't add a mock channel for notification as I did for my event, so notification will never catch by the frontend application.

composer.json

```<code>"beyondcode/laravel-websockets": "^1.13",
"pusher/pusher-php-server": "^7.2",
"laravel/framework": "^9.19",
</code>```

package.json

```<code>"pusher-js": "^7.5.0",
"laravel-echo": "^1.14.2",
</code>```

I tried the explicit way as well i.e using the pusher SDK's functions[which are giving 200 status code] but not working. As soon as I do it the dirty way it starts working, I mean everything starts working without any issue.

```<code>public function pusherTesting(Request $request)
{
    $path = "/apps/123456/events";
    $settings = [
        'scheme' => 'http',
        'port' => '6001',
        'path' => '',
        'timeout' => '30',
        'auth_key' => '1b5d6e5b1ab73b',
        'secret' => '3739db6a99c1ba',
        'app_id' => '123456',
        'base_path' => '/apps/123456',
        'host' => '127.0.0.1',
    ];
    $params = [];

    $body = '{"name":"Illuminate\\Notifications\\Events\\BroadcastNotificationCreated","data":"{\"site_id\":1,\"domain_url\":\"yucentipede-tuvo.blr3.instawp-testing.xyz\",\"save\":\"socket\",\"id\":\"2f53aac0-8d83-45f4-962d-516c1c8bc97c\",\"type\":\"App\\\\Notifications\\\\SiteDeletedNotification\"}","channels":["private-App.Models.User.7"]}';

    $params['body_md5'] = md5($body);

    $params_with_signature = \Pusher\Pusher::build_auth_query_params(
        $settings['auth_key'],
        $settings['secret'],
        'POST',
        $path,
        $params
    );

    $headers = [
        'Content-Type' => 'application/json',
        'X-Pusher-Library' => 'pusher-http-php 7.2.1'
    ];

    $client = new \GuzzleHttp\Client();

    try {
        $response = $client->post(ltrim($path, '/'), [
            'query' => $params_with_signature,
            'body' => $body,
            'http_errors' => false,
            'headers' => $headers,
            'base_uri' => 'http://127.0.0.1:6001'
        ]);
    } catch (Exception $e) {
        print_r($e->getMessage());
    }
    $response_body = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);

    echo $status = $response->getStatusCode();
    die;

}
</code>```

Body:
I am working on Laravel 9 where I install Laravel WebSocket, Laravel Echo, and Pusher PHP server.

By the way, I didn't use the official Pusher application, just using the package as per Laravel-WebSocket package documentation suggested.

User case - I want to update the site model value and send a notification (broadcast and mail) to the end user as soon as the user deletes a site.

Everything is installed and working fine but I found some glitches in the Laravel-WebSocket, Pusher package.

I have created the following event which will broadcast to the end user.

SiteDelete.php

<?php

namespace App\Events;

use App\Models\Site;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class SiteDeleted implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * The site instance.
     *
     * @var \App\Models\Site
     */
    public $site;

    /**
     * The name of the queue connection to use when broadcasting the event.
     *
     * @var string
     */
    public $connection = 'database';

    /**
     * The name of the queue on which to place the broadcasting job.
     *
     * @var string
     */
    public $queue = 'default';

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Site $site)
    {
        $this->site = $site;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        // return new PrivateChannel('site.delete.'.$this->site->id); // this is not working.
        // return [new PrivateChannel('site.delete.'.$this->site->id)]; // this is not working.
        return [new PrivateChannel('site.delete.'.$this->site->id), new Channel('mock')]; // This will call but I need to pass two channels intentionally.
    }

    /**
     * Get the data to broadcast.
     *
     * @return array
     */
    public function broadcastWith()
    {
        return ['id' => $this->site->id];
    }
}

app.js

Echo.private("site.delete.1")
.listen('SiteDeleted', (e) => {
    console.log("SiteDeleted");
    console.log(JSON.stringify(e));
})

Echo.private('App.Models.User.7')
.notification((notification) => {
    console.log("App.Models.User");
    console.log(notification);
});

Problem

As you can see comments in my event class's broadcastOn method where I need to pass two channels. One is real and the second one is fake. So ultimately you need to pass at least two channels so the pusher request will have a channels parameter [which will work] but the channel parameter never works[i.e when you pass a single channel].

I can able to send custom events from the WebSocket GUI. i.e from http://localhost:8000/laravel-websockets URL. but those events are never caught by the front end unless I do it the dirty way.

The notifications are never caught by the front end due to this channel and channels parameter issue.

Dirty Way[Yes I know we should never touch the vendor folder but just curious to know why the things are not working]

I checked the vendor folder very deeply and I come to know, in the vendor/pusher/pusher-php-server/src/Pusher.php under the make_event function if I update the following line then it starts working without passing two channels.

vendor/pusher/pusher-php-server/src/Pusher.php

private function make_event(array $channels, string $event, $data, array $params = [], ?string $info = null, bool $already_encoded = false): array
{
    // if (count($channel_values) == 1) {
    //   $post_params['channel'] = $channel_values[0];
    // } else {
    //   $post_params['channels'] = $channel_values;
    // }

    $post_params['channels'] = $channel_values;
}

My Research

As the WebSocket package suggests installing pusher-php-server version 3.0 but I install the latest one i.e 7. Version 3.0 is incompatible with Laravel 9. But I can't and don't want to install the older version.

I think the WebSocket package is not able to send the event and data on a single channel with a newer version of pusher-php-server.

I can't raise an issue (or blame it) for Pusher SDK because we are just replacing the package and I think the Pusher SDK package is working fine when you use their credentials(ie. you have to create an app on Pusher).

Even if you can check on the WebSocket dashboard i.e http://localhost:8000/laravel-websockets when you send the event it will never catch in the front end. But as soon as you update the Pusher.php file it starts catching an event on the front end.

due to the above reason, as you know the notification are sent to the user on their private channels, So I can't add a mock channel for notification as I did for my event, so notification will never catch by the frontend application.

composer.json

"beyondcode/laravel-websockets": "^1.13",
"pusher/pusher-php-server": "^7.2",
"laravel/framework": "^9.19",

package.json

"pusher-js": "^7.5.0",
"laravel-echo": "^1.14.2",

I tried the explicit way as well i.e using the pusher SDK's functions[which are giving 200 status code] but not working. As soon as I do it the dirty way it starts working, I mean everything starts working without any issue.

public function pusherTesting(Request $request)
{
    $path = "/apps/123456/events";
    $settings = [
        'scheme' => 'http',
        'port' => '6001',
        'path' => '',
        'timeout' => '30',
        'auth_key' => '1b5d6e5b1ab73b',
        'secret' => '3739db6a99c1ba',
        'app_id' => '123456',
        'base_path' => '/apps/123456',
        'host' => '127.0.0.1',
    ];
    $params = [];

    $body = '{"name":"Illuminate\\Notifications\\Events\\BroadcastNotificationCreated","data":"{\"site_id\":1,\"domain_url\":\"yucentipede-tuvo.blr3.instawp-testing.xyz\",\"save\":\"socket\",\"id\":\"2f53aac0-8d83-45f4-962d-516c1c8bc97c\",\"type\":\"App\\\\Notifications\\\\SiteDeletedNotification\"}","channels":["private-App.Models.User.7"]}';

    $params['body_md5'] = md5($body);

    $params_with_signature = \Pusher\Pusher::build_auth_query_params(
        $settings['auth_key'],
        $settings['secret'],
        'POST',
        $path,
        $params
    );

    $headers = [
        'Content-Type' => 'application/json',
        'X-Pusher-Library' => 'pusher-http-php 7.2.1'
    ];

    $client = new \GuzzleHttp\Client();

    try {
        $response = $client->post(ltrim($path, '/'), [
            'query' => $params_with_signature,
            'body' => $body,
            'http_errors' => false,
            'headers' => $headers,
            'base_uri' => 'http://127.0.0.1:6001'
        ]);
    } catch (Exception $e) {
        print_r($e->getMessage());
    }
    $response_body = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);

    echo $status = $response->getStatusCode();
    die;

}


来源: stackexchange

问:
Change dispatch for *all* generics

Problem

Given an object A wrapped in an object E (say an environment or list), is there a universal way to instruct R to dispatch on A whenever a generic is called on E?

Use case

Usually contents can be represented in multiple ways and sometimes it is necessary to toggle between these representations. For instance, the sequence 1, 2, ..., 10 can be stored in a data.frame as is, or as a sequence of increments 1, 1, ..., 1.

One can come up with an implementation that stores both, e.g.

E = function(view = c("cum", "incr")) {
  # Store preferred representation mode
  view <- match.arg(view)

  # Two equivalent representations
  cum  <- data.frame(X = 1L:10L)
  incr <- data.frame(X = rep.int(1L, 10L))

  # Get preferred representation
  A <- function() {
    get(view)
  }

  # Set preferred representation mode
  setview = function(view = c("cum", "incr")) {
    view <<- match.arg(view)
  }

  environment()
}

instance <- E()
instance$A()              # cumulative
instance$setview("incr")
instance$A()              # incremental
```

I would like instance to behave like a data.frame in any reasonable respect and not like an environment, e.g. print(), dim(), ... should apply to instance$A() instead of instance.

ContentLicense: CC BY-SA 4.0

Title: Change dispatch for *all* generics

Body:
Problem

Given an object A wrapped in an object E (say an environment or list), is there a universal way to instruct R to dispatch on A whenever a generic is called on E?

Use case

Usually contents can be represented in multiple ways and sometimes it is necessary to toggle between these representations. For instance, the sequence 1, 2, ..., 10 can be stored in a data.frame as is, or as a sequence of increments 1, 1, ..., 1.

One can come up with an implementation that stores both, e.g.

E = function(view = c("cum", "incr")) {
  # Store preferred representation mode
  view <- match.arg(view)

  # Two equivalent representations
  cum  <- data.frame(X = 1L:10L)
  incr <- data.frame(X = rep.int(1L, 10L))

  # Get preferred representation
  A <- function() {
    get(view)
  }

  # Set preferred representation mode
  setview = function(view = c("cum", "incr")) {
    view <<- match.arg(view)
  }

  environment()
}

instance <- E()
instance$A()              # cumulative
instance$setview("incr")
instance$A()              # incremental

I would like instance to behave like a data.frame in any reasonable respect and not like an environment, e.g. print(), dim(), ... should apply to instance$A() instead of instance.


问:
Bootstrap issue - overflow on the right
I am building a web app which is basically just one page containing a table.

The code looks more or less like this:

```<code><!DOCTYPE HTML>
<html lang="en">

<head>

<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="10">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>

<body style="width: 100%">

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.css" rel="stylesheet"/>
<div class="row">
<div class="col-xl-12">
  <nav class="navbar navbar-expand bg-dark navbar-dark fixed-top mb-3" style="height:10px" >
    <ul class="navbar-nav ml-auto">
      <li class="nav-item">
        <a class="nav-link" href="en">en</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="zh">中</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#"></a>
      </li>
    </ul>
  </nav>
</div>
</div>

<div class="container-fluid" style="margin-top:70px;">
<div class="row">
  <div class="col">

      <table class="table table-striped" style="width: 100%; font-size: 16px !important;">

          <thead>
              <tr>

                  <th class="text-center" scope="col">E.g.1</th>
                  <th class="text-center" scope="col">E.g.2</th>
                  <th class="text-center" scope="col">E.g.3</th>
                  <th class="text-center" scope="col">E.g.4</th>
                  <th class="text-center" scope="col">E.g.5</th>
                  <th class="text-center" scope="col">E.g.6</th>
              </tr>
          </thead>

          <tbody>
              <tr>
                    <td class="text-center">Text 1</td>
                    <td class="text-center">Text 2</td>
                    <td class="text-center">Text 3</td>
                    <td class="text-center">Text 4</td>
                    <td class="text-center">Text 5</td>
                    <td class="text-center">Text 6</td>
              </tr>
              <tr>
                    <td class="text-center">Text 1</td>
                    <td class="text-center">Text 2</td>
                    <td class="text-center">Text 3</td>
                    <td class="text-center">Text 4</td>
                    <td class="text-center">Text 5</td>
                    <td class="text-center">Text 6</td>
              </tr>

          </tbody>
      </table>

  </div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>

</body>

</html>

</code>```

So it should just displaying a navigation bar on top and then a table.

The problem is the following: while the page fits the screen good on laptop, it always overflows on the right (around 20% of the size) when opening the page from smartphone (then it is possible to "zoom out" and make the page occupy the full screen, but I want the table to fit the screen already when opening the page).

Also, note that if I replace:

```<code>      <table class="table table-striped"
</code>```

with

```<code>      <table
</code>```

The page fits the screen correctly from smartphone as well, but I want to be able to use the table-striped style.

EDIT:
The behaviour can be reproduced by copy-pasting the code here:
https://codebeautify.org/htmlviewer
Opening it from smartphone, you can see the last one and a half column overflows on the right, while this does not happen on laptop.

I'm quite sure I'm missing something basic here related to bootstrap, but I've been trying to change things for a few hours now with no results, so I hope someone can give me a hint on what could possibly go wrong here. Thank you!

Title: Bootstrap issue - overflow on the right

Body:
I am building a web app which is basically just one page containing a table.

The code looks more or less like this:

<!DOCTYPE HTML>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="10">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.css" rel="stylesheet"/>

        en

        中

                  E.g.1
                  E.g.2
                  E.g.3
                  E.g.4
                  E.g.5
                  E.g.6

                    Text 1
                    Text 2
                    Text 3
                    Text 4
                    Text 5
                    Text 6

                    Text 1
                    Text 2
                    Text 3
                    Text 4
                    Text 5
                    Text 6

So it should just displaying a navigation bar on top and then a table.

The problem is the following: while the page fits the screen good on laptop, it always overflows on the right (around 20% of the size) when opening the page from smartphone (then it is possible to "zoom out" and make the page occupy the full screen, but I want the table to fit the screen already when opening the page).

Also, note that if I replace:

      <table class="table table-striped"

with

      <table

The page fits the screen correctly from smartphone as well, but I want to be able to use the table-striped style.

EDIT:
The behaviour can be reproduced by copy-pasting the code here:
https://codebeautify.org/htmlviewer
Opening it from smartphone, you can see the last one and a half column overflows on the right, while this does not happen on laptop.

I'm quite sure I'm missing something basic here related to bootstrap, but I've been trying to change things for a few hours now with no results, so I hope someone can give me a hint on what could possibly go wrong here. Thank you!


问:
Which component is used if the content slot contains multiple components
Slot A contains components C and B. Slot A is associated with the page position "topBar". The code in JSP for placing the JSP component on the content page is given below:

```<code><cms:pageSlot position="topBar" var="feature" element="div">
  <cms:component component="${feature}"/>
</cms:pageSlot>
</code>```

Which JSP component will be placed on the page if both components are visible?

Body:
Slot A contains components C and B. Slot A is associated with the page position "topBar". The code in JSP for placing the JSP component on the content page is given below:

<cms:pageSlot position="topBar" var="feature" element="div">
  <cms:component component="${feature}"/>
</cms:pageSlot>

Which JSP component will be placed on the page if both components are visible?


问:
Azure Data Studio select correct encoding
I have a problem with encoding in ADS. I set in all settings encoding on "UTF-8 with boom". And when I open a new query then ok "UTF-8 with boom" encoding is set but when I open some files with my T-sql store procedures then always azure data studio open it with "UTF-8" encoding without boom.
How to fix that?</p>


问:
How can I help Intellisense find include paths based on CMake variables?
I'm trying to use Android NDK in my project, for which I'm using Visual Studio Code. This means I have a CMakeLists.txt file that uses a ANDROID_NDK variable in order to find both include and source files, and building works. However, Intellisense is not working, meaning that coding is a real pain since it can't recognize includes. I tried using CMAKE_EXPORT_COMPILE_COMMANDS but it just won't work as intended. Should I just manually edit vscode's includePath and expect everyone I share my code with to do the same? Whatever the solution may be, I'd rather have CMakeLists.txt modified so it can help any IDE/editor, but vscode-specific solutions are ok if there's no other way.

I tried set(CMAKE_EXPORT_COMPILE_COMMANDS ON) and editing the appropriate vscode variable for compile commands path but it just won't help.


问:
React Native switches local files in Android bundle
I am facing an issue with local images in a React Native app. I have a file where I require all of my app icons, something like this:

```<code>export const icons = {
  a: require("a.png"),
  b: require("b.png"),
  c: require("c.png")
};
</code>```

Then I use these files in the React Native Image component. For instance:

```<code>import { icons } from "icons";

<Image
  source={icons.a}
/>
</code>```

It works fine in dev mode on both iOS and Android. It also works fine on iOS archive in production. But in Android production bundle, the icons seem to be randomly switched up. Sometimes icon a is displayed instead of icon b, sometimes it is icon c that is displayed instead of icon a, and so on... Sometimes one of the icon is not even displayed at all.

Can the problem come from requiring all the files in the same file ?

I would appreciate any clue. Thanks a lot.

Body:
I am facing an issue with local images in a React Native app. I have a file where I require all of my app icons, something like this:

export const icons = {
  a: require("a.png"),
  b: require("b.png"),
  c: require("c.png")
};

Then I use these files in the React Native Image component. For instance:

import { icons } from "icons";

<Image
  source={icons.a}
/>

It works fine in dev mode on both iOS and Android. It also works fine on iOS archive in production. But in Android production bundle, the icons seem to be randomly switched up. Sometimes icon a is displayed instead of icon b, sometimes it is icon c that is displayed instead of icon a, and so on... Sometimes one of the icon is not even displayed at all.

Can the problem come from requiring all the files in the same file ?

I would appreciate any clue. Thanks a lot.


问:
What is the meaning of "recursive" and "full.names" in the list.files function?
I want to understand what recursive and full.names does in the list.files() function.

```<code>df <- list.files(
  path = "path/to/files",
  recursive = TRUE,
  pattern = "\\.csv$",
  full.names = TRUE
)
</code>```

I already read the R documentation but I still don't fully understand what it does.

I expect someone can help me explain the code with easy to understand example if can.

Body:
I want to understand what recursive and full.names does in the list.files() function.

df <- list.files(
  path = "path/to/files",
  recursive = TRUE,
  pattern = "\\.csv$",
  full.names = TRUE
)

I already read the R documentation but I still don't fully understand what it does.

I expect someone can help me explain the code with easy to understand example if can.


问:
An error was encountered processing the command (domain=FBSOpenApplicationServiceErrorDomain, code=3):
Trying to run this project on a MacBook but this error keeps showing. Looked for some solutions but they all failed.
I am working on Flutter project.
The code was built on a different MacBook.

That's the whole error:

Exception: Unable to launch com.projectname.client on 9CE7CA53-67B5-442B-AA2C-35A19A42CEEF:
ProcessException: Process exited abnormally:
An error was encountered processing the command (domain=FBSOpenApplicationServiceErrorDomain, code=3):
The request to open "com.bringitback.client" failed.
The process did launch, but has since exited or crashed.
Command: xcrun simctl launch 9CE7CA53-67B5-442B-AA2C-35A19A42CEEF com.bringitback.client --enable-dart-profiling --enable-checked-mode --verify-entry-points --start-paused --observatory-port=0
Error launching application on iPhone 14 Pro Max.


问:
Flutter web index.html not same as examples for fcm what to do now
I am building a flutter web app.  Using flutter 3.0.7.  I need to send push notifications and it looks like the only real way is with fcm.  So I created a project and with the cli I created a firebase_options.dart file.  Then I created a firebase-messaging-sw.js file.

If I send a message from the console I recieve the message but as soon as I try to send the message from y app to a topic or registration key I get no message.

I red in the examples the few out there to change my index.html file.

To theThis code is not in my index.html, dont know if it is because I am working with flutter 3.0.7

```<code><script>
</code>```

if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {

mine looks like this

```<code><script>
// The value below is injected by flutter build, do not touch.
var serviceWorkerVersion = null;
</code>```

So could that be the problem that I can not send with legacy fcm api to my app users?

The send method I use is as follows

```<code>sendPushMessageToWeb(String? fcm_token) async {
if (fcm_token == null) {
print('Unable to send FCM message, no token exists.');
return;
}
try {
await http
.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization':
'key=my server key'
},
body: json.encode({
'to': "${fcm_token}",
'message': {
'token': "${fcm_token}",
},
</code>```

"notification": {
"title": "Push Notification",
"body": "Firebase  push notification"
}
}),
)
.then((value) => print(value.body));
print('FCM request for web sent!');
} catch (e) {
print(e);
}
}

When I send the message the method it tells me the message was send but no message is recieved.  But when using console with the registration key it sends the message.  Could it be because I did not change my index.html?

Thank you


问:
Twitter Api v2 python filtered stream - not define Rule, no connection,why is the rule not working?
```<code>previousRules = stream.get_rules().data
if previousRules:
    stream.delete_rules(previousRules)

rule = StreamRule(value="from:BBC lang:en -is:retweet")
stream.add_rules(rule)
</code>```

with a simple request for a keyword, then it goes, but when you make such a rule, there is no flow

Body:
previousRules = stream.get_rules().data
if previousRules:
    stream.delete_rules(previousRules)

rule = StreamRule(value="from:BBC lang:en -is:retweet")
stream.add_rules(rule)

with a simple request for a keyword, then it goes, but when you make such a rule, there is no flow


问:
amqp library is thread-safe in node.js?
RabbitMQ recommends not sharing channels between threads.

3. Don’t share channels between threads.

Don’t share channels between threads, as most clients don’t make channels thread-safe for performance reasons.

And libuv inside Node.js either makes requests to the kernel or handles tasks in its own thread pool.

Now, Assumes one connection, one channel.

Multiple clients are requesting to publish messages at the same time.
I expect multiple threads in libuv's thread pool to publish messages using a single channel.

I'm confused if this is thread safe.

Can someone please answer what am I misunderstanding.

Title: amqp library is thread-safe in node.js?


问:
How to test scroll event in jest
I am calling  $(window).on('scroll', () =\>  { this method in my JS file. But I can't find out how to test this method using JEST.

The complete code is below:

```<code>$(document).ready(() => {
    $(window).on('scroll', () =>  {

        var scrollPos = $(window).scrollTop();
        var pagesection = ($('.pagesection-meet').offset().top);
        var height = ($('.pagesection-meet').height());

    if(scrollPos >= pagesection + height || scrollPos < pagesection)
        $('.meet-nav-header').removeClass('sticky');
    else
        $('.meet-nav-header').addClass('sticky');
});
});
</code>```

How may I test if and else conditions also?

Title: How to test scroll event in jest

Body:
I am calling  $(window).on('scroll', () =\>  { this method in my JS file. But I can't find out how to test this method using JEST.

The complete code is below:

$(document).ready(() => {
    $(window).on('scroll', () =>  {

        var scrollPos = $(window).scrollTop();
        var pagesection = ($('.pagesection-meet').offset().top);
        var height = ($('.pagesection-meet').height());

    if(scrollPos >= pagesection + height || scrollPos < pagesection)
        $('.meet-nav-header').removeClass('sticky');
    else
        $('.meet-nav-header').addClass('sticky');
});
});

How may I test if and else conditions also?


问:
Libary missing in Android Build?
When I run my application in the emulator everything looks fine, if i run it on my phone, it's missing something.

I have copied a lot of code from a working app. What is missing?

Phone

I have added the following libaries to my gradle

```<code>implementation "androidx.drawerlayout:drawerlayout:1.1.1"
implementation "androidx.gridlayout:gridlayout:1.0.0"
implementation "androidx.recyclerview:recyclerview:1.2.1"
implementation "androidx.cardview:cardview:1.0.0"
implementation "androidx.navigation:navigation-fragment-ktx:2.5.3"
implementation "androidx.appcompat:appcompat-resources:1.5.1"
</code>```

this did not solve the problem

Edit:
I don't know what is missing if it is a lib or something else. As you can see on the srceenshot there is no text in the menubar, in the emulator there is. The Actionbar is not displayed correctly, in the emulator it is. You can't see it on the screenshot, but there is no spinner, in the emulator there is. The Card's do not display any text, in the emulator they are. If you click on card the text, which is bound the same way, is displayed.

Title: Libary missing in Android Build?

Body:
When I run my application in the emulator everything looks fine, if i run it on my phone, it's missing something.

I have copied a lot of code from a working app. What is missing?

Phone

I have added the following libaries to my gradle

implementation "androidx.drawerlayout:drawerlayout:1.1.1"
implementation "androidx.gridlayout:gridlayout:1.0.0"
implementation "androidx.recyclerview:recyclerview:1.2.1"
implementation "androidx.cardview:cardview:1.0.0"
implementation "androidx.navigation:navigation-fragment-ktx:2.5.3"
implementation "androidx.appcompat:appcompat-resources:1.5.1"

this did not solve the problem

Edit:
I don't know what is missing if it is a lib or something else. As you can see on the srceenshot there is no text in the menubar, in the emulator there is. The Actionbar is not displayed correctly, in the emulator it is. You can't see it on the screenshot, but there is no spinner, in the emulator there is. The Card's do not display any text, in the emulator they are. If you click on card the text, which is bound the same way, is displayed.


问:
prometheus getting query result inside alert annotation
I need your help in setting prometheus alert with ability to insert list of specific labels inside annotation neither summary or description , below chunck of my alert config :
groups:

metric1 is metric with multiple vectors and multiple values of  labels , value of metric1 can be 0 or 1 , this alert is fired if one or more of metric1 vector equal to zero , my need is to get list of labels  of metric "metric1" which value equal to zero inside alert annotation

-name: NodeMissiong
rules:
- alert: Node1
expr : (sum(metric1{})-count(metric1{}))!=0
annotations:
description : "


问:
changes in series type while assigning it to a df
I have created a series called 'doy' and info about the series is as follows;

doy.info()
<class 'pandas.core.series.Series'>
RangeIndex: 282875 entries, 0 to 282874
Series name: None
Non-Null Count   Dtype

282875 non-null  int32
dtypes: int32(1)
memory usage: 1.1 MB

There are 282875 entries and doy is of int type.

However, when I assign the series to an existing df called 'dat2', the series seems to undergo some mysterious changes. The info about dat2 is given below. The inserted series 'doy' has 282675 entries and is of float type.

dat2["doy"]=doy

dat2.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 282875 entries, 0 to 283074
Data columns (total 15 columns):

Column     Non-Null Count   Dtype

0   period     282875 non-null  int64

1   gcm_rcp    282875 non-null  object

2   DATE       282875 non-null  int64

3   tmax       282875 non-null  float64

4   tmin       282875 non-null  float64

5   vprsd      282875 non-null  float64

6   wind       282875 non-null  float64

7   rain       282875 non-null  float64

8   srad       282875 non-null  float64

9   rhumd_tn   282875 non-null  float64

10  rhumd_tx   282875 non-null  float64

11  dewp       282875 non-null  float64

12  avgtemp    282875 non-null  float64

13  timestamp  282875 non-null  datetime64[ns]
14  doy        282675 non-null  float64

dtypes: datetime64ns, float64(11), int64(2), object(1)
memory usage: 34.5+ MB

Any clue as to why this could be happening?

Thanks for your help in deciphering this.

explained in the question above.


问:
How to include a matplotlib graph for an interactive dashboard?
I want to include a line chart (constructed with matplotlib) in an interactive dashboard. My graph describes the evolution for one year of the frequency of the word "France" in 7 media for Central Africa. The database is called: "df_france_pivot".

What I've seen so far is that first of all I have to transform my plot into an object with the go.figure function. So I tried this code:

```<code>`app = dash.Dash()

def update_graph():
    plt.style.use('seaborn-darkgrid')
    fig, ax = plt.subplots()
    ax.set_prop_cycle(color=['304558', 'FE9235', '526683', 'FE574B', 'FFD104', '6BDF9C'])
    num=0
    for column in df_france_pivot.drop('month_year', axis=1):
       num+=1
       plt.plot(df_france_pivot['month_year'], df_france_pivot[column], marker='',
       linewidth=1, alpha=0.9, label=column)
    plt.xticks(rotation=45)
    plt.legend(loc=0, prop={'size': 9},bbox_to_anchor=(1.05, 1.0), title='Media in South Africa')
    plt.title("Frequency of the word 'France' in the media ", loc='left', fontsize=12, fontweight=0, color='orange')
    plt.xlabel("Time")
    plt.ylabel("Percentage")

    figure = go.Figure(fig)
    return figure

app.layout = html.Div(id = 'parent', children = [
    html.H1(id = 'H1', children = 'Styling using html components', style = {'textAlign':'center',\
                                        'marginTop':40,'marginBottom':40}),

    dcc.Graph(id = 'line_plot', figure = update_graph())
    ]
                 )`
</code>```

When running it I got this response: Output exceeds the size limit. Open the full output data in a text editor. Is it because my linechart is more complex i.e. with 7 lines?

Thank you in advance!

Body:
I want to include a line chart (constructed with matplotlib) in an interactive dashboard. My graph describes the evolution for one year of the frequency of the word "France" in 7 media for Central Africa. The database is called: "df_france_pivot".

What I've seen so far is that first of all I have to transform my plot into an object with the go.figure function. So I tried this code:

`app = dash.Dash()

def update_graph():
    plt.style.use('seaborn-darkgrid')
    fig, ax = plt.subplots()
    ax.set_prop_cycle(color=['304558', 'FE9235', '526683', 'FE574B', 'FFD104', '6BDF9C'])
    num=0
    for column in df_france_pivot.drop('month_year', axis=1):
       num+=1
       plt.plot(df_france_pivot['month_year'], df_france_pivot[column], marker='',
       linewidth=1, alpha=0.9, label=column)
    plt.xticks(rotation=45)
    plt.legend(loc=0, prop={'size': 9},bbox_to_anchor=(1.05, 1.0), title='Media in South Africa')
    plt.title("Frequency of the word 'France' in the media ", loc='left', fontsize=12, fontweight=0, color='orange')
    plt.xlabel("Time")
    plt.ylabel("Percentage")

    figure = go.Figure(fig)
    return figure

app.layout = html.Div(id = 'parent', children = [
    html.H1(id = 'H1', children = 'Styling using html components', style = {'textAlign':'center',\
                                        'marginTop':40,'marginBottom':40}),

    dcc.Graph(id = 'line_plot', figure = update_graph())
    ]
                 )`

When running it I got this response: Output exceeds the size limit. Open the full output data in a text editor. Is it because my linechart is more complex i.e. with 7 lines?

Thank you in advance!


问:
KMM Image manupilation for Android and iOS
I don't know if I'm going about this the wrong way, but I'm really struggling to get this right or even get examples on the net.

So I want to create a KMM (Kotlin Multi Platform) library to use in my Android and iOS app.

In the Common section I want to either load a local image resource or create a new image and manipulate it, say write some text on it or draw a line on it.

Then I want to expose that image in the Android specific part to android and I want to expose that image in the iOS specific part to iOS.

So, some very basic pseudo code:

```<code>KMM
  Common
    fun loadLocalImageResource(): Image {...}
    fun createNewImage(): Image {...}

  Android
    fun getLoadLocalImageResource(): Image {return loadLocalImageResource()}
    fun getCreateNewImage(): Image {return createNewImage()}

  iOS
    fun getLoadLocalImageResource(): Image {return loadLocalImageResource()}
    fun getCreateNewImage(): Image {return createNewImage()}
</code>```

Thanks

Body:
I don't know if I'm going about this the wrong way, but I'm really struggling to get this right or even get examples on the net.

So I want to create a KMM (Kotlin Multi Platform) library to use in my Android and iOS app.

In the Common section I want to either load a local image resource or create a new image and manipulate it, say write some text on it or draw a line on it.

Then I want to expose that image in the Android specific part to android and I want to expose that image in the iOS specific part to iOS.

So, some very basic pseudo code:

KMM
  Common
    fun loadLocalImageResource(): Image {...}
    fun createNewImage(): Image {...}

  Android
    fun getLoadLocalImageResource(): Image {return loadLocalImageResource()}
    fun getCreateNewImage(): Image {return createNewImage()}

  iOS
    fun getLoadLocalImageResource(): Image {return loadLocalImageResource()}
    fun getCreateNewImage(): Image {return createNewImage()}

Thanks


问:
How can I separate Lexical error from Syntax error in flex & bison?
I want to make simple calculator using bison, and I have one problem.

Here is my code:

flex

[0-9]+[A-Za-z][A-Za-z0-9]* { printerr();  return LEXERR; }
[0-9]*"."[0-9]+[A-Za-z][A-Za-z0-9]* { printerr(); return LEXERR; }
. { printerr(); return LEXERR; }
```
<p>bison</p>
<pre class="lang-c prettyprint-override"><code>stmt:
    | err NEWLINE
    | error NEWLINE { yyerrok; }
    | stmt expr NEWLINE  { printf("%d\n", $2); }
    | stmt real_expr NEWLINE { printf("%f\n", $2); }
    ;

err: LEXERR
    | err LEXERR
    ;
</code>```

Even if Lexical and Syntax error occur at the same time, I want only Lexical error to be output.
But now, when ERROR occurs at the same time, both occur.

For example:

```<code>> %%
lexical error(1:1): %
lexical error(1:2): %
> %%
lexical error(2:1): %
syntax error(2)
lexical error(2:2): %
> 10 * %
lexical error(3:6): %
syntax error(3)
> 10 * *
syntax error(4)
</code>```

I want to print like this:

```<code>> %%
lexical error(1:1): %
lexical error(1:2): %
> %%
lexical error(2:1): %
lexical error(2:2): %
> 10 * %
lexical error(3:6): %
> 10 * *
syntax error(4)
</code>```

I tried use yyclearin, but it didn't work.

How can I solve this problem?

Body:
I want to make simple calculator using bison, and I have one problem.

Here is my code:

flex

[0-9]+[A-Za-z][A-Za-z0-9]* { printerr();  return LEXERR; }
[0-9]*"."[0-9]+[A-Za-z][A-Za-z0-9]* { printerr(); return LEXERR; }
. { printerr(); return LEXERR; }

bison

stmt:
    | err NEWLINE
    | error NEWLINE { yyerrok; }
    | stmt expr NEWLINE  { printf("%d\n", $2); }
    | stmt real_expr NEWLINE { printf("%f\n", $2); }
    ;

err: LEXERR
    | err LEXERR
    ;

Even if Lexical and Syntax error occur at the same time, I want only Lexical error to be output.
But now, when ERROR occurs at the same time, both occur.

For example:

> %%
lexical error(1:1): %
lexical error(1:2): %
> %%
lexical error(2:1): %
syntax error(2)
lexical error(2:2): %
> 10 * %
lexical error(3:6): %
syntax error(3)
> 10 * *
syntax error(4)

I want to print like this:

> %%
lexical error(1:1): %
lexical error(1:2): %
> %%
lexical error(2:1): %
lexical error(2:2): %
> 10 * %
lexical error(3:6): %
> 10 * *
syntax error(4)

I tried use yyclearin, but it didn't work.

How can I solve this problem?


问:
issue in fetching html components from ES6 script
Till now I was using require to import the npm installed moudles but, when I use import, my modules are being imported but I am not able to fetch the component of my html file.

here is my html code,

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My Hello World</title>
    <link rel="stylesheet" type="text/css" href="index.css" />
  </head>
  <body>
    <p id="value"></p>
    <h1 style="margin: auto">Working</h1>
    <script type="module" src="index.js"></script>
  </body>
</html>

</code>```

here is my js file(index.js)

```<code>import { faker } from "@faker-js/faker";

var pval = document.getElementById("value");
.....

</code>```

when I run node index.js it shows,

```<code>var pval = document.getElementById("value");
           ^

ReferenceError: document is not defined
    at file:///D:/alchemy%20practical/javascript%20fundamental/node/index.js:3:12
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:530:24)
    at async loadESM (node:internal/process/esm_loader:91:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)
</code>```

any idea why I'm getting this error?

I mentioned the type as module in my package.json and searched a lot on internet but no one was mentioning this problem.

Body:
Till now I was using require to import the npm installed moudles but, when I use import, my modules are being imported but I am not able to fetch the component of my html file.

here is my html code,

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>My Hello World</title>
    <link rel="stylesheet" type="text/css" href="index.css" />

Working

here is my js file(index.js)

import { faker } from "@faker-js/faker";

var pval = document.getElementById("value");
.....

when I run node index.js it shows,

var pval = document.getElementById("value");
           ^

ReferenceError: document is not defined
    at file:///D:/alchemy%20practical/javascript%20fundamental/node/index.js:3:12
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:530:24)
    at async loadESM (node:internal/process/esm_loader:91:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

any idea why I'm getting this error?

I mentioned the type as module in my package.json and searched a lot on internet but no one was mentioning this problem.


问:
How to mark 2 point and draw lines in betwwen them in babylonjs
Needto accomplish these kind of 3D box shapes and respective route paths (straight and curves) on this terrain


问:
Unable to save data received by Spring Boot WebCliet
The things I want to do is: to get data from https://jsonplaceholder.typicode.com/ and save those data into my machine. I want to save the posts from this site. I want to do it by Spring Boot WebClient. I have followed several tutorials, articles, and also WebClient documentation. But Unable to save the response in my local database.

The below URL will return one post.
https://jsonplaceholder.typicode.com/posts/1

If I want to return the post as the response of another API it is working fine, but not able to use the inside program. I have tried with WebClient .block(), but it is working for standalone applications but not for web application.

GitLab link of the project

Controller :

```<code>    @Autowired
    private PostService postService;

    // working fine.
    @GetMapping(value = "posts", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public Flux<Post> findAll() {
        return postService.findAll();
    }

    @GetMapping(value = "postsSave")
    @ResponseStatus(HttpStatus.OK)
    public String saveAll() {
        return postService.saveAll();
    }
</code>```

Service:

```<code>    @Override
    public String saveAll() {
//        Post posts = webClient.get()
//                .uri("/posts")
//                .retrieve()
//                .bodyToFlux(Post.class)
//                .timeout(Duration.ofMillis(10_000)).blockFirst();

        String url = "https://jsonplaceholder.typicode.com/posts/1";
        WebClient.Builder builder = WebClient.builder();
        Post p = builder.build()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(Post.class)
                .block(); // this line generating error.

        postRepository.save(p);
        return "saved";
    }
</code>```

Exception StackTrace:

```<code>2022-12-07 14:35:44.070 ERROR 6576 --- [ctor-http-nio-3] a.w.r.e.AbstractErrorWebExceptionHandler : [b48b7f19-1]  500 Server Error for HTTP GET "/postsSave"

java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-3
    at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83) ~[reactor-core-3.3.9.RELEASE.jar:3.3.9.RELEASE]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
    |_ checkpoint ⇢ HTTP GET "/postsSave" [ExceptionHandlingWebHandler]
Stack trace:
        at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83) ~[reactor-core-3.3.9.RELEASE.jar:3.3.9.RELEASE]
        at reactor.core.publisher.Mono.block(Mono.java:1680) ~[reactor-core-3.3.9.RELEASE.jar:3.3.9.RELEASE]
        at com.quantsys.service.PostService.saveAll(PostService.java:53) ~[classes/:na]
        at com.quantsys.controller.PostController.saveAll(PostController.java:26) ~[classes/:an]
</code>```

But the same code of snippet is working within the Bootstrap class:

```<code>@SpringBootApplication
public class QuanrsysPostService {
    public static void main(String[] args) {
        SpringApplication.run(QuanrsysPostService.class, args);

        String url = "https://jsonplaceholder.typicode.com/posts/1";
        WebClient.Builder builder = WebClient.builder();
        Post p = builder.build()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(Post.class)
                .block(); // working here.
        System.out.println(p.toString());
    }
}
</code>```

Body:
The things I want to do is: to get data from https://jsonplaceholder.typicode.com/ and save those data into my machine. I want to save the posts from this site. I want to do it by Spring Boot WebClient. I have followed several tutorials, articles, and also WebClient documentation. But Unable to save the response in my local database.

The below URL will return one post.
https://jsonplaceholder.typicode.com/posts/1

If I want to return the post as the response of another API it is working fine, but not able to use the inside program. I have tried with WebClient .block(), but it is working for standalone applications but not for web application.

GitLab link of the project

Controller :

    @Autowired
    private PostService postService;

    // working fine.
    @GetMapping(value = "posts", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public Flux<Post> findAll() {
        return postService.findAll();
    }

    @GetMapping(value = "postsSave")
    @ResponseStatus(HttpStatus.OK)
    public String saveAll() {
        return postService.saveAll();
    }

Service:

    @Override
    public String saveAll() {
//        Post posts = webClient.get()
//                .uri("/posts")
//                .retrieve()
//                .bodyToFlux(Post.class)
//                .timeout(Duration.ofMillis(10_000)).blockFirst();

        String url = "https://jsonplaceholder.typicode.com/posts/1";
        WebClient.Builder builder = WebClient.builder();
        Post p = builder.build()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(Post.class)
                .block(); // this line generating error.

        postRepository.save(p);
        return "saved";
    }

Exception StackTrace:

2022-12-07 14:35:44.070 ERROR 6576 --- [ctor-http-nio-3] a.w.r.e.AbstractErrorWebExceptionHandler : [b48b7f19-1]  500 Server Error for HTTP GET "/postsSave"

java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-3
    at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83) ~[reactor-core-3.3.9.RELEASE.jar:3.3.9.RELEASE]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
    |_ checkpoint ⇢ HTTP GET "/postsSave" [ExceptionHandlingWebHandler]
Stack trace:
        at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83) ~[reactor-core-3.3.9.RELEASE.jar:3.3.9.RELEASE]
        at reactor.core.publisher.Mono.block(Mono.java:1680) ~[reactor-core-3.3.9.RELEASE.jar:3.3.9.RELEASE]
        at com.quantsys.service.PostService.saveAll(PostService.java:53) ~[classes/:na]
        at com.quantsys.controller.PostController.saveAll(PostController.java:26) ~[classes/:an]

But the same code of snippet is working within the Bootstrap class:

@SpringBootApplication
public class QuanrsysPostService {
    public static void main(String[] args) {
        SpringApplication.run(QuanrsysPostService.class, args);

        String url = "https://jsonplaceholder.typicode.com/posts/1";
        WebClient.Builder builder = WebClient.builder();
        Post p = builder.build()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(Post.class)
                .block(); // working here.
        System.out.println(p.toString());
    }
}


问:
Python pandas SettingWithCopyWarning when duplicating a column
I'm trying to duplicate a column in my DataFrame and could not get rid off the warning SettingWithCopyWarning :

I've tried :

```<code>df['new_col'] = df['old_col']
df.loc[:, 'new_col'] = df['old_col']
df.loc[:, 'new_col'] = df['old_col'].copy()
df.loc[:, 'new_col'] = df.loc[:,'old_col']
</code>```

The result is always a Warning like this one

```<code>Warning (from warnings module):
  File "C:\Users\frank\Documents\orange\Python\Jira\jira_initiatives_dashboard.py", line 267
    df.loc[:, 'new_col'] = df['old_col']
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
</code>```

Documentation does not seem to explain when there are multiple values instead of one value. What's wrong?

Body:
I'm trying to duplicate a column in my DataFrame and could not get rid off the warning SettingWithCopyWarning :

I've tried :

df['new_col'] = df['old_col']
df.loc[:, 'new_col'] = df['old_col']
df.loc[:, 'new_col'] = df['old_col'].copy()
df.loc[:, 'new_col'] = df.loc[:,'old_col']

The result is always a Warning like this one

Warning (from warnings module):
  File "C:\Users\frank\Documents\orange\Python\Jira\jira_initiatives_dashboard.py", line 267
    df.loc[:, 'new_col'] = df['old_col']
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

Documentation does not seem to explain when there are multiple values instead of one value. What's wrong?


问:
React Baseweb Datepicker ,disabled all monday with excludeDates prop
i am using datepicker baseweb ui library(https://baseweb.design/components/datepicker/) and i want to exclude all monday or disabled all monday with excludeDates prop.
`

```<code>                      <DatePicker
                      value={nextDate}
                      onChange={handleDateArray}
                      minDate={nextDateCal}
                      maxDate={monthCount}
                      autoFocusCalendar="true"
                      excludeDates={[
                        new Date("2022-12-5"),
                        new Date("2022-12-12"),
                        new Date("2022-12-19"),
                        new Date("2022-12-26"),
                      ]}
                    />
</code>```

`
this how my datepicker looks like, anyone know how to do it

`

```<code> var monday = moment()
      .startOf("year")
      .day("Monday");
    if (monday.date() > 7) monday.add(7, "d");
    var year = monday.year();
    while (year === monday.year()) {
      // document.body.innerHTML += "<p>" + monday.toString() + "</p>";
      console.log(monday.toString());
      setExcludeMonday([monday.toString()]);
      monday.add(7, "d");
    }
</code>```

`
i tried above code but not working with excludeDates prop

Body:
i am using datepicker baseweb ui library(https://baseweb.design/components/datepicker/) and i want to exclude all monday or disabled all monday with excludeDates prop.
`

                      <DatePicker
                      value={nextDate}
                      onChange={handleDateArray}
                      minDate={nextDateCal}
                      maxDate={monthCount}
                      autoFocusCalendar="true"
                      excludeDates={[
                        new Date("2022-12-5"),
                        new Date("2022-12-12"),
                        new Date("2022-12-19"),
                        new Date("2022-12-26"),
                      ]}
                    />

`
this how my datepicker looks like, anyone know how to do it

`

 var monday = moment()
      .startOf("year")
      .day("Monday");
    if (monday.date() > 7) monday.add(7, "d");
    var year = monday.year();
    while (year === monday.year()) {
      // document.body.innerHTML += "
" + monday.toString() + "
";
      console.log(monday.toString());
      setExcludeMonday([monday.toString()]);
      monday.add(7, "d");
    }

`
i tried above code but not working with excludeDates prop


问:
Mock: What Is the right way to mock sqlalchemy database?
This is what I've done for testing database

```<code> @patch.object(query_functions, 'connection')
    def test_service_reg_return_correct_data(self, mock_sqlalchmey):
        data = {
            "user_name": "testuser53",
            "password": "123456",
            "email_address": "testuser53@example.com",
            "dob": "2022-06-07 00:00:00",
            "address": "Ahmedabad",

        }

        # json_data = json.dumps(data)
        # print("jsob", json_data)
        m1 = mock.MagicMock()
        m1.get_json.return_value = data

        print("m", m1)
        with mock.patch("backened.routes.register.request", m1):

            response =user_register()
            self.assertTrue(mock_sqlalchmey.called)
            self.assertEqual(response.json, {'Message': 'New user Created'},201)
</code>```

I've tested this function

```<code>def user_register():

    request_data = request.get_json()
    insert = service_register(request_data)
    print(type(insert))
    return insert
</code>```

inside service_register(), I've run_insert() for execution of queries i.e query_functions.py file.

query_functions.py

```<code>def connection():

    engine = create_engine('mysql://root:admin@172.17.0.2:3306/flask', poolclass = NullPool)
    conn = engine.connect()
    return conn

def run_insert(data):
    conn = connection()
    sql = text(CONST_INSERT)

    print(sql)
    conn.execute(sql, data)
    conn.close()
    return ("executed")

</code>```

I want to know whether it is right or wrong as I was trying to mock my database and don't want to insert data into DB. I'm not sure how database mock happened in this.

Body:
This is what I've done for testing database

 @patch.object(query_functions, 'connection')
    def test_service_reg_return_correct_data(self, mock_sqlalchmey):
        data = {
            "user_name": "testuser53",
            "password": "123456",
            "email_address": "testuser53@example.com",
            "dob": "2022-06-07 00:00:00",
            "address": "Ahmedabad",

        }

        # json_data = json.dumps(data)
        # print("jsob", json_data)
        m1 = mock.MagicMock()
        m1.get_json.return_value = data

        print("m", m1)
        with mock.patch("backened.routes.register.request", m1):

            response =user_register()
            self.assertTrue(mock_sqlalchmey.called)
            self.assertEqual(response.json, {'Message': 'New user Created'},201)

I've tested this function

def user_register():

    request_data = request.get_json()
    insert = service_register(request_data)
    print(type(insert))
    return insert

inside service_register(), I've run_insert() for execution of queries i.e query_functions.py file.

query_functions.py

def connection():

    engine = create_engine('mysql://root:admin@172.17.0.2:3306/flask', poolclass = NullPool)
    conn = engine.connect()
    return conn

def run_insert(data):
    conn = connection()
    sql = text(CONST_INSERT)

    print(sql)
    conn.execute(sql, data)
    conn.close()
    return ("executed")

I want to know whether it is right or wrong as I was trying to mock my database and don't want to insert data into DB. I'm not sure how database mock happened in this.


问:
in the word using addin i want to redirect the image when click on image id but its showing error
the error is shown in the attached image

hello every one please help me out with this i want to redirect the image when clicking on image id in the same document

```<code>  Office.context.document.addHandlerAsync(
    Office.EventType.DocumentSelectionChanged,
    (result:any) => {
      let bookmark = localStorage.getItem("bookmark")
      let bookmarkParse = JSON.parse(bookmark);
      console.log("bookmarkParse",bookmarkParse)
      bookmarkParse.map((item: any) => {
      Word.run(async (context) => {
        // var doc:any = context.document;
        console.log("result", result);
        const range :any = context.document.getSelection();
        return context.sync().then(async function (){
          context.load(range);
          await context.sync();
          let text = range.text
          console.log("item", item.ImageId, text);
          if (item.ImageId == text) {
            console.log("item bookmark",item.bookmark)
            // range.hyperlink = "#" + item.bookmark;
            context.document.getSelection().hyperlink = `"#" + ${item.bookmark}`;
            return context.sync();
          } else {
            console.log("range not matched");
          }
          await context.sync();
        });
      })
    })
    })

</code>```

Body:
the error is shown in the attached image

hello every one please help me out with this i want to redirect the image when clicking on image id in the same document

  Office.context.document.addHandlerAsync(
    Office.EventType.DocumentSelectionChanged,
    (result:any) => {
      let bookmark = localStorage.getItem("bookmark")
      let bookmarkParse = JSON.parse(bookmark);
      console.log("bookmarkParse",bookmarkParse)
      bookmarkParse.map((item: any) => {
      Word.run(async (context) => {
        // var doc:any = context.document;
        console.log("result", result);
        const range :any = context.document.getSelection();
        return context.sync().then(async function (){
          context.load(range);
          await context.sync();
          let text = range.text
          console.log("item", item.ImageId, text);
          if (item.ImageId == text) {
            console.log("item bookmark",item.bookmark)
            // range.hyperlink = "#" + item.bookmark;
            context.document.getSelection().hyperlink = `"#" + ${item.bookmark}`;
            return context.sync();
          } else {
            console.log("range not matched");
          }
          await context.sync();
        });
      })
    })
    })


问:
Scope records which don't have an associated record for a specific user
I have a chat function in my app. Chat::Messages are "read" by a user when an Chat::Message::Interaction exists for that message and that user.

When a user opens the chat, I want to mark all unread messages as read in a background job.  I'm finding the unread messages by doing chat.message.unread(user). This uses the unread scope on the message model, and with it's current implementation pulls every chat message from the database, which is obviously not ideal.

Is there a better way of getting all messages for a chats which don't have an interaction for a specific user?

class Chat::Message::Interaction < ApplicationRecord
  belongs_to :user
  belongs_to :message
  delegate :chat, to: :message

  validates :user, uniqueness: { scope: :message }
end
```
<pre class="lang-rb prettyprint-override"><code>class Chat::Message < ApplicationRecord
  belongs_to :user
  belongs_to :chat
  has_many :interactions, dependent: :destroy
  has_noticed_notifications

  default_scope { includes(:user) }

  scope :unread, ->(user) { where.not(id: Chat::Message::Interaction.where(user:).pluck(:message_id)) }

  def read?(user)
    interactions.find_by(user:).present?
  end
</code>```

To give an example. A chat has two users, and they have both read the first 10 messages in the chat. So there are 20 interactions, one per message per user.

user_one sends two new messages, interactions for these messages are created automatically for the message sender.

chat.messages.unread(user_two) should return the two new messages which user_two has not yet seen.

Edit: I'm not sure if I'm getting closer or further away.
Thanks to the, now deleted, answer, I made some progress. The suggestion was:

scope :unread, ->(user) { left_joins(:interactions).where.not('chat_message_interactions.user_id is distinct from ?', user.id) }
```
<p>This gives all messages that the user HAS read.</p>
<p>Taking all messages and then <code>excluding()</code> the messages the user has read gives us a the correct result and using the <code>left_joins</code> gives us a much better query than before. It also opens it up for easy further progressive enhancement such as scoping both queries to only look at messages sent after a certain date.</p>
<p>My current scope is:</p>
<pre class="lang-rb prettyprint-override"><code>scope :unread, ->(user) { where.not(user:).excluding(left_joins(:interactions).where(chat_message_interactions: {user:})) }
</code>```

Edit 2:

It's evolved. I've added a last_seen_at method to the chat_participant model which stores when the user was last in the chat.

This allows me to further reduce the scope of the scope. I hate this, but it works.

  scope :unread, lambda { |user, chat|
    where("created_at >= ?", chat.participants.find_by(user:).last_seen_at)
      .where.not(user:)
      .excluding(left_joins(:interactions)
                   .where("chat_messages.created_at >= ?", chat.participants.find_by(user:).last_seen_at)
                   .where(chat_message_interactions: { user: }))
  }
```

Body:
I have a chat function in my app. Chat::Messages are "read" by a user when an Chat::Message::Interaction exists for that message and that user.

When a user opens the chat, I want to mark all unread messages as read in a background job.  I'm finding the unread messages by doing chat.message.unread(user). This uses the unread scope on the message model, and with it's current implementation pulls every chat message from the database, which is obviously not ideal.

Is there a better way of getting all messages for a chats which don't have an interaction for a specific user?

class Chat::Message::Interaction < ApplicationRecord
  belongs_to :user
  belongs_to :message
  delegate :chat, to: :message

  validates :user, uniqueness: { scope: :message }
end

class Chat::Message < ApplicationRecord
  belongs_to :user
  belongs_to :chat
  has_many :interactions, dependent: :destroy
  has_noticed_notifications

  default_scope { includes(:user) }

  scope :unread, ->(user) { where.not(id: Chat::Message::Interaction.where(user:).pluck(:message_id)) }

  def read?(user)
    interactions.find_by(user:).present?
  end

To give an example. A chat has two users, and they have both read the first 10 messages in the chat. So there are 20 interactions, one per message per user.

user_one sends two new messages, interactions for these messages are created automatically for the message sender.

chat.messages.unread(user_two) should return the two new messages which user_two has not yet seen.

Edit: I'm not sure if I'm getting closer or further away.
Thanks to the, now deleted, answer, I made some progress. The suggestion was:

scope :unread, ->(user) { left_joins(:interactions).where.not('chat_message_interactions.user_id is distinct from ?', user.id) }

This gives all messages that the user HAS read.

Taking all messages and then excluding() the messages the user has read gives us a the correct result and using the left_joins gives us a much better query than before. It also opens it up for easy further progressive enhancement such as scoping both queries to only look at messages sent after a certain date.

My current scope is:

scope :unread, ->(user) { where.not(user:).excluding(left_joins(:interactions).where(chat_message_interactions: {user:})) }

Edit 2:

It's evolved. I've added a last_seen_at method to the chat_participant model which stores when the user was last in the chat.

This allows me to further reduce the scope of the scope. I hate this, but it works.

  scope :unread, lambda { |user, chat|
    where("created_at >= ?", chat.participants.find_by(user:).last_seen_at)
      .where.not(user:)
      .excluding(left_joins(:interactions)
                   .where("chat_messages.created_at >= ?", chat.participants.find_by(user:).last_seen_at)
                   .where(chat_message_interactions: { user: }))
  }


问:
Why iOS Push notification events are not triggered in C#
I'm trying to send iOS push notifications, but the code I'm using is not working due to the events OnNotificationSucceeded and OnNotificationFailed are not triggered.

My code is:

```<code>string p12fileName = "path to my iOS push certificate";
string p12password = "my iOS push certificate password";
string deviceToken = "my device ID";

var appleCert = File.ReadAllBytes(p12fileName);

var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, p12password);
config.ValidateServerCertificate = false;

var apnsBroker = new ApnsServiceBroker(config);

apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {

    aggregateEx.Handle(ex => {

        // See what kind of exception it was to further diagnose
        if (ex is ApnsNotificationException)
        {
            var notificationException = (ApnsNotificationException)ex;

            // Deal with the failed notification
            var apnsNotification = notificationException.Notification;
            var statusCode = notificationException.ErrorStatusCode;
            Response.Write("Apple Notification Failed: ID={" + apnsNotification.Identifier + "}, Code={" + statusCode + "}");
        }
        else
        {
            // Inner exception might hold more useful information like an ApnsConnectionException
            Response.Write("Notification Failed for some unknown reason : {" + ex.InnerException + "}");
        }

        // Mark it as handled
        return true;
    });
};
apnsBroker.OnNotificationSucceeded += (notification) => {
    LogDao.Info(deviceData.UserId, "Apple Notification Sent!");
};
SureAct.Helpers.LiteralsHelper literals = new SureAct.Helpers.LiteralsHelper(1, 0);

string message = "test";

apnsBroker.Start();
apnsBroker.QueueNotification(new ApnsNotification
{
    DeviceToken = deviceToken,
    Payload = JObject.Parse("{\"aps\":{\"alert\":\"" + message + "\",\"badge\":1,\"sound\":\"default\"}}")
});
apnsBroker.Stop();
</code>```

I checked the certificate and password and they are correct. And If I try to send a push notification using the webpage pushtry.com I receive the push.

What I'm doing wrong? Why the events are not triggered?

Kind regards

Body:
I'm trying to send iOS push notifications, but the code I'm using is not working due to the events OnNotificationSucceeded and OnNotificationFailed are not triggered.

My code is:

string p12fileName = "path to my iOS push certificate";
string p12password = "my iOS push certificate password";
string deviceToken = "my device ID";

var appleCert = File.ReadAllBytes(p12fileName);

var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, p12password);
config.ValidateServerCertificate = false;

var apnsBroker = new ApnsServiceBroker(config);

apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {

    aggregateEx.Handle(ex => {

        // See what kind of exception it was to further diagnose
        if (ex is ApnsNotificationException)
        {
            var notificationException = (ApnsNotificationException)ex;

            // Deal with the failed notification
            var apnsNotification = notificationException.Notification;
            var statusCode = notificationException.ErrorStatusCode;
            Response.Write("Apple Notification Failed: ID={" + apnsNotification.Identifier + "}, Code={" + statusCode + "}");
        }
        else
        {
            // Inner exception might hold more useful information like an ApnsConnectionException
            Response.Write("Notification Failed for some unknown reason : {" + ex.InnerException + "}");
        }

        // Mark it as handled
        return true;
    });
};
apnsBroker.OnNotificationSucceeded += (notification) => {
    LogDao.Info(deviceData.UserId, "Apple Notification Sent!");
};
SureAct.Helpers.LiteralsHelper literals = new SureAct.Helpers.LiteralsHelper(1, 0);

string message = "test";

apnsBroker.Start();
apnsBroker.QueueNotification(new ApnsNotification
{
    DeviceToken = deviceToken,
    Payload = JObject.Parse("{\"aps\":{\"alert\":\"" + message + "\",\"badge\":1,\"sound\":\"default\"}}")
});
apnsBroker.Stop();

I checked the certificate and password and they are correct. And If I try to send a push notification using the webpage pushtry.com I receive the push.

What I'm doing wrong? Why the events are not triggered?

Kind regards


问:
Is there any way to download data from disk station to the server directly?
I have disk station with some large files (site with interactive file system where I can download some files and archives). I also have server with ssh access. Can I download file directy to the server without downloading it to my local machine and then using scp to the server?

Some people say to use

```<code>wget http://link-to-the-file
</code>```

But I am not sure, that there is direct download link. Moreover you should specify language of achieve before downloading (confirming).

Note: I tried to use wget but can't understand is there downloading link.

Body:
I have disk station with some large files (site with interactive file system where I can download some files and archives). I also have server with ssh access. Can I download file directy to the server without downloading it to my local machine and then using scp to the server?

Some people say to use

wget http://link-to-the-file

But I am not sure, that there is direct download link. Moreover you should specify language of achieve before downloading (confirming).

Note: I tried to use wget but can't understand is there downloading link.


问:
How to make when a user clicks accept all cookies google analytics is enabled , but when user clicks only necessary google analytics is disabled
First thank you for reading my question and trying to help.

I'm trying to make a cookie accept footer and when user clicks on accept all I want to enable google analytics and google tag manager. But when user clicks on only necessary I only want google tag manager and I don't know how to make that.

This is my cookie footer :

```<code>import { useState } from "react";
import Cookies from 'js-cookie'

function FooterCookies() {

  cosnt [ show, setShow ] = useState(true)

  const content = {
    text : 'This site uses services that uses cookies to deliver better experience and analyze traffic. You can learn more about the services we use at our ',
    policy : 'Privacy Policy.'
  }

  const setCookies = () => {
    Cookies.set('cookie', 'true', { expires: 2 })
  }

  return (

    <>

      {show ?

        (
          <div
          className=" h-auto bg-black/30 fixed
          bottom-0 text-cus-yellow rounded
          py-4 px-8 flex justify-evenly items-center z-[100]
          max75:flex-col max75:px-5 max75:py-3 max30:py-1 max30:px-1.5 max75:items-start">

            <div className=" w-85%  max70:text-sm flex items-center max75:w-100% max75:items-start max75:mb-3 " >

              <p className=" text-[13px] pt-1">
                {content.text}

                <span className=" text-[16px] underline cursor-pointer ">
                  {content.policy}
                </span>

              </p>

            </div>

            <div className=" flex "  >

              <div onClick={() => setCookies()}>

                <div onClick={() => setShow(false)}
                className="border border-cus-yellow text-cus-yellow hover:bg-cus-yellow/60
                transition-all hover:text-black w-28 h-80% bg-black/40 cursor-pointer
                flex flex-col justify-center items-center whitespace-nowrap
                duration-500 text-lg max75:text-base  font-medium mx-2 px-1 py-2 max75:mx-0 max75:py-1 max75:px-0.5 "
                >Accept All</div>

              </div>

              <div onClick={() => setShow(false)}
              className="border border-cus-yellow text-cus-yellow hover:bg-cus-yellow/60
              transition-all hover:text-black w-36 h-80% bg-black/40 cursor-pointer
              flex flex-col justify-center items-center whitespace-nowrap
              duration-500 text-lg max75:text-base font-medium mx-2 px-1 py-[13.76px] max75:mx-0 max75:ml-3 max75:px-0.5 max75:py-[8.75px] "
              >Only Nessesary</div>

            </div>

          </div>
        )

      :

      <></>

    }

  </>
  )
}
</code>```

This is my gtag.js :

```<code>export const GA_TRACKING_ID = 'XXXXXXXXX'

export const pageview = (url) => {
  window.gtag('config', GA_TRACKING_ID, {
    page_path: url,
  })
}

export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value,
  })
}
</code>```

This is myApp.js :

```<code>import '../styles/globals.css'
import 'tailwindcss/tailwind.css'
import { useEffect } from 'react'
import Script from 'next/script'
import { useRouter } from 'next/router'
import * as gtag from '../lib/gtag'

function MyApp({ Component, pageProps }) {
  const router = useRouter()
  useEffect(() => {
    const handleRouteChange = (url) => {
      gtag.pageview(url)
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    router.events.on('hashChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
      router.events.off('hashChangeComplete', handleRouteChange)
    }
  }, [router.events])

  return (
    <>
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
      />
      <Script
        id="gtag-init"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${gtag.GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
        }}
      />

      <Script id="google-tag-manager" strategy="afterInteractive">
      {`
        (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','XXXXXXXX');
      `}
    </Script>
      <Component {...pageProps} />
    </>
  )

}

export default MyApp
</code>```

This is my document.js :

```<code>import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'

import { GA_TRACKING_ID } from '../lib/gtag'

export default function Document() {
  return (
    <Html>
      <Head>
        <Script
          id='google tags manager'
          dangerouslySetInnerHTML={{
          __html:`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
          new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
          j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
          'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
          })(window,document,'script','dataLayer','XXXXXXXX');`,
          }}
        />
        <Script
          async src={`https://www.googlemanager.com/gtag/js?id=${GA_TRACKING_ID}`}
        />
      </Head>
      <body>
      <noscript
        dangerouslySetInnerHTML={{
          __html: `<iframe src="https://www.googletagmanager.com/ns.html?id=XXXXXXX"
          height="0" width="0" style="display:none;visibility:hidden" />`,
        }}
        />

        <Main />
        <NextScript />
        <script
          dangerouslySetInnerHTML={{
            __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
          `,
          }}
        />
      </body>
    </Html>
  )
}
</code>```

Body:
First thank you for reading my question and trying to help.

I'm trying to make a cookie accept footer and when user clicks on accept all I want to enable google analytics and google tag manager. But when user clicks on only necessary I only want google tag manager and I don't know how to make that.

This is my cookie footer :

import { useState } from "react";
import Cookies from 'js-cookie'

function FooterCookies() {

  cosnt [ show, setShow ] = useState(true)

  const content = {
    text : 'This site uses services that uses cookies to deliver better experience and analyze traffic. You can learn more about the services we use at our ',
    policy : 'Privacy Policy.'
  }

  const setCookies = () => {
    Cookies.set('cookie', 'true', { expires: 2 })
  }

  return (

    <>

      {show ?

        (

                {content.text}

                  {content.policy}

 setCookies()}>

 setShow(false)}
                className="border border-cus-yellow text-cus-yellow hover:bg-cus-yellow/60
                transition-all hover:text-black w-28 h-80% bg-black/40 cursor-pointer
                flex flex-col justify-center items-center whitespace-nowrap
                duration-500 text-lg max75:text-base  font-medium mx-2 px-1 py-2 max75:mx-0 max75:py-1 max75:px-0.5 "
                >Accept All

 setShow(false)}
              className="border border-cus-yellow text-cus-yellow hover:bg-cus-yellow/60
              transition-all hover:text-black w-36 h-80% bg-black/40 cursor-pointer
              flex flex-col justify-center items-center whitespace-nowrap
              duration-500 text-lg max75:text-base font-medium mx-2 px-1 py-[13.76px] max75:mx-0 max75:ml-3 max75:px-0.5 max75:py-[8.75px] "
              >Only Nessesary

        )

      :

      <></>

    }

  </>
  )
}

This is my gtag.js :

export const GA_TRACKING_ID = 'XXXXXXXXX'

export const pageview = (url) => {
  window.gtag('config', GA_TRACKING_ID, {
    page_path: url,
  })
}

export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value,
  })
}

This is myApp.js :

import '../styles/globals.css'
import 'tailwindcss/tailwind.css'
import { useEffect } from 'react'
import Script from 'next/script'
import { useRouter } from 'next/router'
import * as gtag from '../lib/gtag'

function MyApp({ Component, pageProps }) {
  const router = useRouter()
  useEffect(() => {
    const handleRouteChange = (url) => {
      gtag.pageview(url)
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    router.events.on('hashChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
      router.events.off('hashChangeComplete', handleRouteChange)
    }
  }, [router.events])

  return (
    <>

      <Component {...pageProps} />
    </>
  )

}

export default MyApp

This is my document.js :

import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'

import { GA_TRACKING_ID } from '../lib/gtag'

export default function Document() {
  return (


问:
run cmake-tools targets in same terminal
I'm remotely developing a project based on yocto and I'm trying to set up remote debugger for my x86 target.

Obviously it is not working, but I can't see any logs - launching any target via cmake-tools GUI runs a new terminal and removes the command issued by the addon, so I can't really see what cmake-tools is trying to do.

e.g. if I run a simple UT - all the output I get is test result, but I can't see the path to the binary file.

Is there a way to keep all the output in a single terminal, and to not remove commands issued by the addon?


问:
ag-grid react exportMultipleSheetsAsExcel with coulmnKeys
I'm novice in ag-grid react. Currently I want to export the grid data as excel with multiple sheets. The requirement is, export only selected columns(User will be prompted to choose columns to be present in the excel on click of Export button). I know, we should be using columnKeys attribute. But something, I'm missing here. After clicking columns , I'm getting this error when I click export option

AG Grid: Invalid params supplied to getMultipleSheetsAsExcel() - ExcelExportParams.data is empty.

```<code>getRefsFromParent(childRefs) {
    this.setState({
        myRequestedRefs: childRefs
    });

    /* Export multiple sheets commence here  */
    var spreadsheets = []; // var for storing multiple sheets data
    for (let i = 0; i < this.state.checkedSheets.length; i++) {
        if (this.state.checkedSheets[i] == 'Engagements') {
            spreadsheets.push(
                //Referring Engagement Reference passed from Parent Component
                this.state.engRef.current.api.getSheetDataForExcel({
                    sheetName: 'Engagements'
                })

            )
        }
        else {
            spreadsheets.push(
                //Sheets will be created based on the selected items from the sheetsList
                this.state.ref.current.api.getSheetDataForExcel({
                    onlySelected: false,
                    sheetName: this.state.checkedSheets[i]

                })
            )
        }
        console.log("Spreadsheets ", spreadsheets);
    }
    this.state.ref.current.api.exportMultipleSheetsAsExcel({
        data: spreadsheets,
        columnKeys: this.state.pickedColumns, //columns selected in the modal by user
        fileName: 'client-details.xlsx',
    });
}
</code>```

Body:
I'm novice in ag-grid react. Currently I want to export the grid data as excel with multiple sheets. The requirement is, export only selected columns(User will be prompted to choose columns to be present in the excel on click of Export button). I know, we should be using columnKeys attribute. But something, I'm missing here. After clicking columns , I'm getting this error when I click export option

AG Grid: Invalid params supplied to getMultipleSheetsAsExcel() - ExcelExportParams.data is empty.

getRefsFromParent(childRefs) {
    this.setState({
        myRequestedRefs: childRefs
    });

    /* Export multiple sheets commence here  */
    var spreadsheets = []; // var for storing multiple sheets data
    for (let i = 0; i < this.state.checkedSheets.length; i++) {
        if (this.state.checkedSheets[i] == 'Engagements') {
            spreadsheets.push(
                //Referring Engagement Reference passed from Parent Component
                this.state.engRef.current.api.getSheetDataForExcel({
                    sheetName: 'Engagements'
                })

            )
        }
        else {
            spreadsheets.push(
                //Sheets will be created based on the selected items from the sheetsList
                this.state.ref.current.api.getSheetDataForExcel({
                    onlySelected: false,
                    sheetName: this.state.checkedSheets[i]

                })
            )
        }
        console.log("Spreadsheets ", spreadsheets);
    }
    this.state.ref.current.api.exportMultipleSheetsAsExcel({
        data: spreadsheets,
        columnKeys: this.state.pickedColumns, //columns selected in the modal by user
        fileName: 'client-details.xlsx',
    });
}


问:
React ant design cannot switch to dark style manually without using Setting Drawer
I am trying to put a Switch component in navigation bar where I can switch website to dark style which is in the settings drawer in ant design pro layout.

```<code><SettingDrawer
    pathname={location.pathname}
    enableDarkTheme
    getContainer={() => document.getElementById('test-pro-layout')}
    settings={settings}
    onSettingChange={(changeSetting) => {
        setSetting(changeSetting);
    }}
    disableUrlParams={false}
/>
</code>```

As you SettingDrawer has a property enableDarkTheme, but this is for the functionality and not for the switching. Is there any way to attach dark style to state change?
enter image description here

I have tryed to change the css file as I saw it in other stackoverflow questions but it only changed the color of the components it did not enable the dark style(which is in beta)

Body:
I am trying to put a Switch component in navigation bar where I can switch website to dark style which is in the settings drawer in ant design pro layout.

<SettingDrawer
    pathname={location.pathname}
    enableDarkTheme
    getContainer={() => document.getElementById('test-pro-layout')}
    settings={settings}
    onSettingChange={(changeSetting) => {
        setSetting(changeSetting);
    }}
    disableUrlParams={false}
/>

As you SettingDrawer has a property enableDarkTheme, but this is for the functionality and not for the switching. Is there any way to attach dark style to state change?
enter image description here

I have tryed to change the css file as I saw it in other stackoverflow questions but it only changed the color of the components it did not enable the dark style(which is in beta)


问:
Can I check a checkbox in CodeCeption without a form?
I'm trying to write a test using CodeCeption for a page that looks like this:

My code for the test is the following:

```<code>// tests
public function tryToUnifyAgents(FunctionalTester $I)
{
    $I->amLoggedInAs($this->operator);
    $I->amOnRoute('agent_index');
    $firstAgent = $I->grabAgentFromDB(self::FIRST_AGENT_NAME);
    $I->seeElement('#agent_' . $firstAgent->getId());
    $I->checkOption('#agent_' . $firstAgent->getId());
    $secondAgent = $I->grabAgentFromDB(self::SECOND_AGENT_NAME);

    $I->seeElement('#agent_' . $secondAgent->getId());
}
</code>```

I have all the needed objects in the database but when I run this test I get "The current node list is empty.".

I run the code with XDebug and noticed that the exception is raised because there's no form containing the checkbox. Is there some way to go around this?

Thanks,

Body:
I'm trying to write a test using CodeCeption for a page that looks like this:

My code for the test is the following:

// tests
public function tryToUnifyAgents(FunctionalTester $I)
{
    $I->amLoggedInAs($this->operator);
    $I->amOnRoute('agent_index');
    $firstAgent = $I->grabAgentFromDB(self::FIRST_AGENT_NAME);
    $I->seeElement('#agent_' . $firstAgent->getId());
    $I->checkOption('#agent_' . $firstAgent->getId());
    $secondAgent = $I->grabAgentFromDB(self::SECOND_AGENT_NAME);

    $I->seeElement('#agent_' . $secondAgent->getId());
}

I have all the needed objects in the database but when I run this test I get "The current node list is empty.".

I run the code with XDebug and noticed that the exception is raised because there's no form containing the checkbox. Is there some way to go around this?

Thanks,


问:
Base64 Encoding version 1.3 throwing error StreamCorruptedException
2022-11-28 13:01:20,720 WARN  [org.jbpm.process.audit.VariableInstanceLog] (default task-31) Variable content was trimmed as it was too long (more than 255 characters)
2022-11-28 13:01:20,748 INFO  [stdout] (default task-31) <<==========>> Process has been Started for Approval/ Rejection Updation <<==========>>
2022-11-28 13:01:20,757 ERROR [stderr] (default task-31) java.io.StreamCorruptedException: invalid handle value: 00400053
2022-11-28 13:01:20,762 ERROR [stderr] (default task-31)        at java.io.ObjectInputStream.readHandle(ObjectInputStream.java:1785

I tried several other version of Base64, but all other version has same issue.
we hard coded input values and then convert it into byteArrayStream() as input to base64.encode(ByteArrayStream). JBPM call with encoded input throwing error.


问:
Spring Data Rest Custom Controller ignored by OpenAPI
I'm usign Spring Data Rest and springdoc-openapi-ui.

```<code><dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
</code>```
```<code><dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.6.11</version>
</dependency>
<dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-data-rest</artifactId>
   <version>1.6.11</version>
</dependency>
</code>```

All my repository methods marked with

```<code>@RepositoryRestResource(...)
</code>```

are shown in the Swagger UI, but my custom Controller anotated with @BasePathAwareController is ignored.

I've seen few raised issues regarding this one, but no solution.
Annotating the controller with @RestController fixes the problem, but seems that will register  twice the dispatcher servlet, which is not good.

Body:
I'm usign Spring Data Rest and springdoc-openapi-ui.

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

<dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.6.11</version>
</dependency>
<dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-data-rest</artifactId>
   <version>1.6.11</version>
</dependency>

All my repository methods marked with

@RepositoryRestResource(...)

are shown in the Swagger UI, but my custom Controller anotated with @BasePathAwareController is ignored.

I've seen few raised issues regarding this one, but no solution.
Annotating the controller with @RestController fixes the problem, but seems that will register  twice the dispatcher servlet, which is not good.


问:
tFileUnarchive does not work in scheduled task
I've created a job where a ZIP file is downloaded to a folder and I use the component tFileUnarchive to extract files in the same folder where the ZIP file is located.

I've built my job and now it's running on a Windows Server as scheduled task. I've set up the task with my personal account on the server, but it is running with a service account and highest privileges. Obviously I've set the job to run whether the user is logged on or not.

The job starts correctly, it downloads the ZIP file correctly but it is unable to extract files from ZIP file.

The task scheduler returns the job is successfully completed, but it has 2147942401 as return code.

I've checked suggestions I've found here Batch file run as scheduled job returns 2147942659 and here batch file from scheduled task returns code 2147942401 without success.

The weird thing is that if I run the job manually (right click --> run) or If I log on the server with my account and I schedule a job after a couple of minutes (always running with the service account) it works correctly.

Do you have any suggestion?


问:
Consuming SOAP Services ASP.NET
I am working on an ASP.NET 3.5 C# Web Application in which I have to consume 3rd party web services. Their documentation says the following information needs to be passed in the SOAP header:

wsse: SecurityTokenReference: Value is the public key of the X.509 certificate

wsse:UsernameToken: Username and Password

ds:Signature xmlns="http://www.w3.org/2000/09/xmldsig#"

I have a X.509 certificate as well as the Username and Password. I have added a Service Reference to my project and now I am trying to figure out a way to pass this information in the SOAP header.  Any help would be greatly appreciated.

ContentLicense: CC BY-SA 3.0

Title: Consuming SOAP Services ASP.NET