问:
400 Bad Request (error code: 50006): Cannot send an empty message
I'm returning a string but it says it's not working.
I'm somewhat new to discord bot coding and am confused.

Code

```<code>from python_aternos import Client

aternos = Client.from_credentials('test', '123')
servs = aternos.list_servers()

testserv = None
for serv in servs:
    if serv.address == 'server.aternos.me':
        testserv = serv

def handle_response(message) -> str:
    p_message = message.lower()

    if p_message == 'status':
        return str(serv.status)
    # Here the issue starts
    if p_message == 'Start':
        serv.start(False,True)
        return "test"
    # Here the issue ends
    if p_message == 'help':
            return "Status - Tells the status of the server.\nStart - Starts the server for people to play.\nHelp - Lists all the commands."
</code>```

I tried to return a string and then use the start command but it doesn't work.

Body:
I'm returning a string but it says it's not working.
I'm somewhat new to discord bot coding and am confused.

Code

from python_aternos import Client

aternos = Client.from_credentials('test', '123')
servs = aternos.list_servers()

testserv = None
for serv in servs:
    if serv.address == 'server.aternos.me':
        testserv = serv

def handle_response(message) -> str:
    p_message = message.lower()

    if p_message == 'status':
        return str(serv.status)
    # Here the issue starts
    if p_message == 'Start':
        serv.start(False,True)
        return "test"
    # Here the issue ends
    if p_message == 'help':
            return "Status - Tells the status of the server.\nStart - Starts the server for people to play.\nHelp - Lists all the commands."

I tried to return a string and then use the start command but it doesn't work.


来源: stackexchange

问:
Visual Studio Docker debug failed. System.ArgumentException: The path must be absolute. (Parameter 'root')
I am working with a ASP dotnet 6 project and it working fine when build a docker container with external commands or debugging with IIS. But when debugging with docker support provided by visual studio it ended with below error inside the container.

Program.cs file content

```<code>using Microsoft.AspNetCore;
using Microsoft.Extensions.FileProviders;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");

app.Run();
</code>```

Here is the error inside the container

```<code>Unhandled exception. System.ArgumentException: The path must be absolute. (Parameter 'root')
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root, ExclusionFilters filters)
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.<>c.<UseStaticWebAssetsCore>b__1_0(String contentRoot)
   at Microsoft.AspNetCore.StaticWebAssets.ManifestStaticWebAssetFileProvider..ctor(StaticWebAssetManifest manifest, Func`2 fileProviderFactory)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssetsCore(IWebHostEnvironment environment, Stream manifest)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssets(IWebHostEnvironment environment, IConfiguration configuration)
   at Microsoft.AspNetCore.WebHost.<>c.<ConfigureWebDefaults>b__9_0(WebHostBuilderContext ctx, IConfigurationBuilder cb)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass9_0.<ConfigureAppConfiguration>b__0(HostBuilderContext context, IConfigurationBuilder builder)
   at Microsoft.AspNetCore.Hosting.BootstrapHostBuilder.RunDefaultCallbacks(ConfigurationManager configuration, HostBuilder innerBuilder)
   at Microsoft.AspNetCore.Builder.WebApplicationBuilder..ctor(WebApplicationOptions options, Action`1 configureDefaults)
   at Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(String[] args)
   at Program.<Main>$(String[] args) in D:\workspace\my\mdo\xx\src\xxx\Program.cs:line 1
Aborted
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working with a ASP dotnet 6 project and it working fine when build a docker container with external commands or debugging with IIS. But when debugging with docker support provided by visual studio it ended with below error inside the container.

Program.cs file content

using Microsoft.AspNetCore;
using Microsoft.Extensions.FileProviders;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");

app.Run();

Here is the error inside the container

Unhandled exception. System.ArgumentException: The path must be absolute. (Parameter 'root')
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root, ExclusionFilters filters)
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.<>c.<UseStaticWebAssetsCore>b__1_0(String contentRoot)
   at Microsoft.AspNetCore.StaticWebAssets.ManifestStaticWebAssetFileProvider..ctor(StaticWebAssetManifest manifest, Func`2 fileProviderFactory)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssetsCore(IWebHostEnvironment environment, Stream manifest)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssets(IWebHostEnvironment environment, IConfiguration configuration)
   at Microsoft.AspNetCore.WebHost.<>c.<ConfigureWebDefaults>b__9_0(WebHostBuilderContext ctx, IConfigurationBuilder cb)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass9_0.<ConfigureAppConfiguration>b__0(HostBuilderContext context, IConfigurationBuilder builder)
   at Microsoft.AspNetCore.Hosting.BootstrapHostBuilder.RunDefaultCallbacks(ConfigurationManager configuration, HostBuilder innerBuilder)
   at Microsoft.AspNetCore.Builder.WebApplicationBuilder..ctor(WebApplicationOptions options, Action`1 configureDefaults)
   at Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(String[] args)
   at Program.$(String[] args) in D:\workspace\my\mdo\xx\src\xxx\Program.cs:line 1
Aborted


问:
InvalidArgumentError: Graph execution error: word2vec
I am new to ML and I am creating a CNN model for Sentiment analysis using word2vec. My word2vec contains negative value also. While fitting the model I got an error -

InvalidArgumentError in model.fit(X_train, Y_train, epochs=3, batch_size=64)
InvalidArgumentError: Graph execution error: Detected at node 'sequential_30/embedding_29/embedding_lookup'

This is the code to create the model

```<code>def get_vec(x):
    doc = nlp(x)
    vec = doc.vector
    return vec

df['vec'] = df['text'].apply(lambda x: get_vec(x))

XTrain = df['vec'].to_numpy()
XTrain = XTrain.reshape(-1, 1)
XTrain = np.concatenate(np.concatenate(XTrain, axis = 0), axis = 0).reshape(-1, 300)
YTrain = df['target']

X_train, X_test, Y_train, Y_test = train_test_split(XTrain, YTrain, test_size = .3, random_state = 45, stratify = YTrain)

# Pad the sequence to the same length
max_review_length = 1600
X_train = pad_sequences(X_train, maxlen=max_review_length)

top_words = (len(nlp.vocab)) + 1

# Using embedding from Keras
embedding_vecor_length = 300
model = Sequential()
model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))

# Convolutional model (3x conv, flatten, 2x dense)
model.add(Convolution1D(64, 3, padding='same'))
model.add(Convolution1D(32, 3, padding='same'))
model.add(Convolution1D(16, 3, padding='same'))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(180,activation='sigmoid'))
model.add(Dropout(0.2))
model.add(Dense(1,activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(X_train, Y_train, epochs=3, batch_size=64)

</code>```

When I replace all negative values in df['vec'], code is working without error but with 0 accuracy. What is wrong in this? Please help. Thanks in advance..

Body:
I am new to ML and I am creating a CNN model for Sentiment analysis using word2vec. My word2vec contains negative value also. While fitting the model I got an error -

InvalidArgumentError in model.fit(X_train, Y_train, epochs=3, batch_size=64)
InvalidArgumentError: Graph execution error: Detected at node 'sequential_30/embedding_29/embedding_lookup'

This is the code to create the model

def get_vec(x):
    doc = nlp(x)
    vec = doc.vector
    return vec

df['vec'] = df['text'].apply(lambda x: get_vec(x))

XTrain = df['vec'].to_numpy()
XTrain = XTrain.reshape(-1, 1)
XTrain = np.concatenate(np.concatenate(XTrain, axis = 0), axis = 0).reshape(-1, 300)
YTrain = df['target']

X_train, X_test, Y_train, Y_test = train_test_split(XTrain, YTrain, test_size = .3, random_state = 45, stratify = YTrain)

# Pad the sequence to the same length
max_review_length = 1600
X_train = pad_sequences(X_train, maxlen=max_review_length)

top_words = (len(nlp.vocab)) + 1

# Using embedding from Keras
embedding_vecor_length = 300
model = Sequential()
model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))

# Convolutional model (3x conv, flatten, 2x dense)
model.add(Convolution1D(64, 3, padding='same'))
model.add(Convolution1D(32, 3, padding='same'))
model.add(Convolution1D(16, 3, padding='same'))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(180,activation='sigmoid'))
model.add(Dropout(0.2))
model.add(Dense(1,activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(X_train, Y_train, epochs=3, batch_size=64)

When I replace all negative values in df['vec'], code is working without error but with 0 accuracy. What is wrong in this? Please help. Thanks in advance..


问:
Create bar chart from multidimensional array (series) with Apexcharts (or VueApexCharts)
Is there a way to create charts (eg. bar charts) using a multidimensional array with ApexCharts? I mean grouped data automatically.
An example of the array (series) I want to use directly to create a grouped chart:

```<code>const series = [
      {
        date: '2023-01-01',
        arr: [
          {
            title: 'Group 1',
            data: 24,
          },
          {
            title: 'Group 2',
            data: 50,
          }
        ]
      },
      {
        date: '2023-01-02',
        arr: [
          {
            title: 'Group 1',
            data: 10,
          },
          {
            title: 'Group 2',
            data: 20,
          },
        ]
      }
    ]
</code>```

Body:
Is there a way to create charts (eg. bar charts) using a multidimensional array with ApexCharts? I mean grouped data automatically.
An example of the array (series) I want to use directly to create a grouped chart:

const series = [
      {
        date: '2023-01-01',
        arr: [
          {
            title: 'Group 1',
            data: 24,
          },
          {
            title: 'Group 2',
            data: 50,
          }
        ]
      },
      {
        date: '2023-01-02',
        arr: [
          {
            title: 'Group 1',
            data: 10,
          },
          {
            title: 'Group 2',
            data: 20,
          },
        ]
      }
    ]


问:
how to handle memory management in Bradley, Fayyad and Reina algorithm
I have to implement the BFR algorithm in C and one of the tasks is to handle memory: in the BFR algorithm we have to load a chunk of data (reading it from a file) that perfectly fits in main memory (I suppose RAM) and repeat the clustering process for each chunk. I'm here to ask which is the correct approach to this problem. How can I get the right amount of data that I can load in each iteration of the algorithm?</p>


问:
How to restrict access to package depencency embedded in SPM package?
Using Swift Package Manager I have packageB that is imported as dependency in packageA. My project1 only imports packageA, however I am still able to access packageB within the  project1. Is there a way to restrict the access topackageB only to scope of packageA ?

My use case:
The packageA is an API package with multiple versions. I want to import into the project1 another (the newest) version of packageB and use only the new version within project1 API. The old version of packageB should be still used and embedded only inside packageA.

This is structure of my PackageA defined in Package.swift:

```<code>let package = Package(
name: "PackageA",
platforms: [
     .iOS(.v11), .tvOS(.v11)
],
products: [
    .library(
        name: "PackageA",
        targets: ["PackageA"]),
],
dependencies: [
    .package(name: "PackageB",url: "https://my.packageB.git", from: "1.1.1"),
],
targets: [
    .target(
        name: "PackageA",
        dependencies: ["PackageB"])
]
</code>```

)

Body:
Using Swift Package Manager I have packageB that is imported as dependency in packageA. My project1 only imports packageA, however I am still able to access packageB within the  project1. Is there a way to restrict the access topackageB only to scope of packageA ?

My use case:
The packageA is an API package with multiple versions. I want to import into the project1 another (the newest) version of packageB and use only the new version within project1 API. The old version of packageB should be still used and embedded only inside packageA.

This is structure of my PackageA defined in Package.swift:

let package = Package(
name: "PackageA",
platforms: [
     .iOS(.v11), .tvOS(.v11)
],
products: [
    .library(
        name: "PackageA",
        targets: ["PackageA"]),
],
dependencies: [
    .package(name: "PackageB",url: "https://my.packageB.git", from: "1.1.1"),
],
targets: [
    .target(
        name: "PackageA",
        dependencies: ["PackageB"])
]

)


问:
Is there a Job-Searching API that I can implement in JavaScript? (like Indeed.com's API)
I'm looking for a job-searching API (sort of like Indeed.com's API) which can run oh HTML/JS. Preferably, it could locate the latitude and longitude of the jobs. It'd also be great if it were free, as this isn't a professional project.

I'm making a job-searching portal, which takes user's input and searches for jobs in a nearby radius. It then will return the data values back to the user. I have all the data I need, but I just need the API for locating such jobs.
Here's an example of what I was working with (before the API discontinued) :
https://rapidapi.com/indeed/api/indeed

I was originally planning on using Indeed.com's, but I found out it was discontinued and I am not able to find any more APIs, the ones that I find don't work (I'm using RapidAPI for searching for these APIs if that helps). If any of you know any such API, it would help a lot!


问:
Adding a new middleware in my django ( 4.1.4) project
```<code>The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 157, in inner_run
    handler = self.get_handler(*args, **options)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 31, in get_handler
    handler = super().get_handler(*args, **options)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 78, in get_handler
    return get_internal_wsgi_application()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\servers\basehttp.py", line 49, in get_internal_wsgi_application
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: WSGI application 'EZDAR.wsgi.application' could not be loaded; Error importing module.
</code>```

I'm trying to run my server by runserver. I found a post which was saying that it is about the new form of middleware on django version 4, but I don't know if it is and how to edit it

```<code>MIDDLEWARE = [
    'social_django.middleware.SocialAuthExceptionMiddleware', # I ADDED THIS ONE
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

</code>```

Body:
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 157, in inner_run
    handler = self.get_handler(*args, **options)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 31, in get_handler
    handler = super().get_handler(*args, **options)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 78, in get_handler
    return get_internal_wsgi_application()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\servers\basehttp.py", line 49, in get_internal_wsgi_application
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: WSGI application 'EZDAR.wsgi.application' could not be loaded; Error importing module.

I'm trying to run my server by runserver. I found a post which was saying that it is about the new form of middleware on django version 4, but I don't know if it is and how to edit it

MIDDLEWARE = [
    'social_django.middleware.SocialAuthExceptionMiddleware', # I ADDED THIS ONE
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


问:
AWS Bitbucket rest API. Where to find correct url formats
I am trying to create a script that we need to use to create a lot of repositories in bitbucket.

We use the AWS cloud service for bitbucket and I found the below documentation by searching for this on google:

https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-post

This link shows how to create a repository which is what I was looking for but the URL it suggests as the REST API interface is the following:

https://api.bitbucket.org/2.0/repositories/{workspace}/{repo_slug}

This does not work for our AWS cloud service, the correct link for this particular functionality which I found by looking through old scripts, etc, is:

'https://bitbucket.devops.aws.{company_name}/rest/api/1.0/projects/{project_name}/repos/'

I'm looking for documentation that explains the use of the above REST API interface. Preferably a list of URL paths and supported functionality. Similar to the first documentation link I have listed.

Regards


问:
How to add an service accessibility Android that registre Alert Dialog
I would Like to listen to Alert Dialog, and i have adding an exemple but it dont work, and i cant follow the starting and capturing the event like Key Up ..etc by using Log.d.

I confirm that the Accessibility Service has Enabled, but i would like to to assure that is executing
here is my code

```<code>public class MyService extends AccessibilityService {
 public static String TAG = "USD";
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

        Log.i(TAG, "onAccessibilityEvent: gettting");
        String text = event.getText().toString();
        if (event.getClassName().equals("android.app.AlertDialog")) {
            Log.i(TAG,  " Getting USSD"+text);
            Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        }
 }
</code>```

and the Manifest code

```<code><service android:name=".MyService"
    android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
    android:label=""
    android:exported="false">
    <intent-filter>
        <action android:name="android.accessibilityservice.AccessibilityService" />
    </intent-filter>
    <meta-data
        android:name="android.accessibilityservice"
        android:resource="@xml/accessibility_service_config" />
</service>
</code>```

and the config XML

```<code><?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"

android:packageNames="com.android.phone"
android:accessibilityEventTypes="typeWindowStateChanged|typeWindowContentChanged"
android:accessibilityFlags="flagDefault"
android:accessibilityFeedbackType="feedbackGeneric"
android:notificationTimeout="0"
android:canRetrieveWindowContent="true"
android:canRequestFilterKeyEvents="true"
android:settingsActivity="com.example.android.accessibility.ServiceSettingsActivity"
    />
</code>```

Body:
I would Like to listen to Alert Dialog, and i have adding an exemple but it dont work, and i cant follow the starting and capturing the event like Key Up ..etc by using Log.d.

I confirm that the Accessibility Service has Enabled, but i would like to to assure that is executing
here is my code

public class MyService extends AccessibilityService {
 public static String TAG = "USD";
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

        Log.i(TAG, "onAccessibilityEvent: gettting");
        String text = event.getText().toString();
        if (event.getClassName().equals("android.app.AlertDialog")) {
            Log.i(TAG,  " Getting USSD"+text);
            Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        }
 }

and the Manifest code

<service android:name=".MyService"
    android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
    android:label=""
    android:exported="false">
    <intent-filter>
        <action android:name="android.accessibilityservice.AccessibilityService" />
    </intent-filter>
    <meta-data
        android:name="android.accessibilityservice"
        android:resource="@xml/accessibility_service_config" />
</service>

and the config XML

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"

android:packageNames="com.android.phone"
android:accessibilityEventTypes="typeWindowStateChanged|typeWindowContentChanged"
android:accessibilityFlags="flagDefault"
android:accessibilityFeedbackType="feedbackGeneric"
android:notificationTimeout="0"
android:canRetrieveWindowContent="true"
android:canRequestFilterKeyEvents="true"
android:settingsActivity="com.example.android.accessibility.ServiceSettingsActivity"
    />


问:
Is there a way to way to use a VideoPlayer widget in place of an Image widget?
The panorama package on pub.dev only works with Image objects, but the premise should be the same if a video is used instead.

I want to modify this package to accept a VideoPlayer or VideoPlayerController widget from the video_player package. What are the things I must do to make it compatible?

The way panorama works is it takes the Image object and passes it to the package flutter_cube where it then makes a Mesh and texture out of it. The panorama viewing is done based off of this.

What I want to achieve is instead of Panorama accepting an Image widget, it should be the VideoPlayer widget. Width and height are really the only two variables needed so I wonder what I should do, those two are easily obtainable from the VideoPlayerController.


问:
Read input from console and perform some operation using java
I Have 3 input and sum that take an input and if sum is 180, it print yes and if it is less
than 180 it print NO.

```<code>3
40 40 100
45 45 90
180 1 1
</code>```

Above 3 means 3 row input that three row contain different value.

To perform this activity I have written the below function but its test case is wrong. How can I perform this function using Scanner.

```<code>import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;

public class CodeChef {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter value of A");
        int A = sc.nextInt();
        System.out.println("Enter value of B");
        int B = sc.nextInt();
        System.out.println("Enter value of AC");
        int C  = sc.nextInt();

        if (A+B+C == 180) {
            System.out.println("YES");
        }else {
            System.out.println("NO");
        }

    }

}
</code>```

Body:
I Have 3 input and sum that take an input and if sum is 180, it print yes and if it is less
than 180 it print NO.

3
40 40 100
45 45 90
180 1 1

Above 3 means 3 row input that three row contain different value.

To perform this activity I have written the below function but its test case is wrong. How can I perform this function using Scanner.

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;

public class CodeChef {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter value of A");
        int A = sc.nextInt();
        System.out.println("Enter value of B");
        int B = sc.nextInt();
        System.out.println("Enter value of AC");
        int C  = sc.nextInt();

        if (A+B+C == 180) {
            System.out.println("YES");
        }else {
            System.out.println("NO");
        }

    }

}


问:
GoogleOuth passport type argument error (nodejs typescript)
I am trying to develop an integration with google oAuth2 through passport, and I would like to do this using postgresql to define the user

```<code>import {
    Strategy as GoogleStrategy,
    Profile,
    VerifyCallback,
} from 'passport-google-oauth20';
import { AppDataSource } from '../database/config';
import { User } from '../entities/User';
import passport from 'passport';

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID as string,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    callbackURL: "/auth/google/callback"
  },
  async function(accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) {
    try {

      const defaultUser = {
        username: profile.name?.givenName,
        email: profile.emails,
        googleId: profile.id,
      }

      const userAlreadyExists = await AppDataSource.manager.findOneBy(User, {
        googleId: profile.id,
      });

      if (!userAlreadyExists) {
        await AppDataSource.manager.save(defaultUser);
      }

      done(null, userAlreadyExists);

    } catch (err) {
      console.log(err);
    }
  }
));
</code>```

The problem is that in "userAlreadyExists" in that line

```<code>done(null, userAlreadyExists);
</code>```

i am getting the error

```<code>const userAlreadyExists: User | null
Argument of type 'User | null' is not assignable to parameter of type 'User | undefined'.
  Type 'null' is not assignable to type 'User | undefined'.ts(2345)
</code>```

I would like someone to help me with this, and if possible give me some explanation of how this done works and what is its real function

database.config

```<code>import { DataSource } from "typeorm";
import dotenv from 'dotenv';

dotenv.config();

export const AppDataSource = new DataSource({
    type: "postgres",
    host: process.env.DATABASE_HOST,
    port: 5433,
    username: process.env.DATABASE_USERNAME,
    password: process.env.DATABASE_PASSWORD,
    database: process.env.DATABASE_NAME,
    synchronize: true,
    logging: true,
    entities: [`${__dirname}/../entities/*.{ts,js}`],
    migrations: [`${__dirname}/migrations/*.{ts,js}`],
});
</code>```

entity user

```<code>import { BeforeInsert, BeforeUpdate, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
import bcrypt from 'bcryptjs';

@Entity('users')
export class User {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column()
    username: string;

    @Column()
    email: string;

    @Column()
    password: string;

    @Column()
    googleId: string;

    @Column({
        default: ''
    })
    tokenResetPass: string;

    @Column({
        default: false,
    })
    isAdmin: boolean;

    @BeforeInsert()
    @BeforeUpdate()
    hashPassword() {
        this.password = bcrypt.hashSync(this.password, 8);
    }

}
</code>```

Body:
I am trying to develop an integration with google oAuth2 through passport, and I would like to do this using postgresql to define the user

import {
    Strategy as GoogleStrategy,
    Profile,
    VerifyCallback,
} from 'passport-google-oauth20';
import { AppDataSource } from '../database/config';
import { User } from '../entities/User';
import passport from 'passport';

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID as string,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    callbackURL: "/auth/google/callback"
  },
  async function(accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) {
    try {

      const defaultUser = {
        username: profile.name?.givenName,
        email: profile.emails,
        googleId: profile.id,
      }

      const userAlreadyExists = await AppDataSource.manager.findOneBy(User, {
        googleId: profile.id,
      });

      if (!userAlreadyExists) {
        await AppDataSource.manager.save(defaultUser);
      }

      done(null, userAlreadyExists);

    } catch (err) {
      console.log(err);
    }
  }
));

The problem is that in "userAlreadyExists" in that line

done(null, userAlreadyExists);

i am getting the error

const userAlreadyExists: User | null
Argument of type 'User | null' is not assignable to parameter of type 'User | undefined'.
  Type 'null' is not assignable to type 'User | undefined'.ts(2345)

I would like someone to help me with this, and if possible give me some explanation of how this done works and what is its real function

database.config

import { DataSource } from "typeorm";
import dotenv from 'dotenv';

dotenv.config();

export const AppDataSource = new DataSource({
    type: "postgres",
    host: process.env.DATABASE_HOST,
    port: 5433,
    username: process.env.DATABASE_USERNAME,
    password: process.env.DATABASE_PASSWORD,
    database: process.env.DATABASE_NAME,
    synchronize: true,
    logging: true,
    entities: [`${__dirname}/../entities/*.{ts,js}`],
    migrations: [`${__dirname}/migrations/*.{ts,js}`],
});

entity user

import { BeforeInsert, BeforeUpdate, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
import bcrypt from 'bcryptjs';

@Entity('users')
export class User {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column()
    username: string;

    @Column()
    email: string;

    @Column()
    password: string;

    @Column()
    googleId: string;

    @Column({
        default: ''
    })
    tokenResetPass: string;

    @Column({
        default: false,
    })
    isAdmin: boolean;

    @BeforeInsert()
    @BeforeUpdate()
    hashPassword() {
        this.password = bcrypt.hashSync(this.password, 8);
    }

}


问:
Headers but no data in file when downloaded via download.file from R
On this website (https://live.euronext.com/en/products/etfs/list), you can download a csv file. The file can be directly downloaded with this direct link: https://live.euronext.com/pd_es/data/track/download?mics=XAMS%2CXBRU%2CXLIS%2CXPAR%2CXLDN%2CXMSM%2CXOSL.

You can use that link by putting it directly in your web browser. You can observe that after having hit Enter button, the file is downloading directly with data in it (ISIN code).
I would like to download this file from R; it downloads the file but the data are not there: so I tried to mimick the browser, so I used the exact same User-Agent but downloaded file remains empty (no ISIN code)

```<code>url2call <- "https://live.euronext.com/pd_es/data/track/download?mics=XAMS%2CXBRU%2CXLIS%2CXPAR%2CXLDN%2CXMSM%2CXOSL"
options(HTTPUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36")
getOption("HTTPUserAgent")

options(internet.info = 0)
getOption("internet.info")

expr = download.file(url = url2call,
                              destfile = "./file.csv",
                              quiet = FALSE,
                              method = "libcurl",
                              cacheOK = FALSE,
                              mode = "w")
print(expr)
</code>```

Here is the log of code above:

```<code>trying URL 'https://live.euronext.com/pd_es/data/track/download?mics=XAMS%2CXBRU%2CXLIS%2CXPAR%2CXLDN%2CXMSM%2CXOSL'
*   Trying 45.223.139.7:443...
* Connected to live.euronext.com (45.223.139.7) port 443 (#0)
* schannel: disabled automatic use of client certificate
> GET /pd_es/data/track/download?mics=XAMS%2CXBRU%2CXLIS%2CXPAR%2CXLDN%2CXMSM%2CXOSL HTTP/1.1
Host: live.euronext.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
Accept: */*
Pragma: no-cache

* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Mon, 02 Jan 2023 15:12:20 GMT
< Server: Apache
* skipped cookie with bad tailmatch domain: priv.atos.fr
< Set-Cookie: SessionStatId=ec362863.5f14960ae7a67; path=/; expires=Tue, 31-Dec-30 15:12:20 GMT; domain=.priv.atos.fr; secure; httpOnly
< X-Content-Type-Options: nosniff
< Content-Disposition: attachment; filename="Euronext_ETPs_2023-01-02.csv"
< Vary: Accept-Encoding
< Content-Length: 263
< Content-Type: text/csv;charset=UTF-8
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Headers: X-Requested-With
* Added cookie visid_incap_2784297="TSHS7aJ+Sg+lIwsikCSFUFP0smMAAAAAQUIPAAAAAACORJXoFQ6SWQTy9K1vAVdW" for domain euronext.com, path /, expire 1704147471
< Set-Cookie: visid_incap_2784297=TSHS7aJ+Sg+lIwsikCSFUFP0smMAAAAAQUIPAAAAAACORJXoFQ6SWQTy9K1vAVdW; expires=Mon, 01 Jan 2024 22:17:51 GMT; HttpOnly; path=/; Domain=.euronext.com
* Added cookie incap_ses_1103_2784297="ib7VDHy0tnHw2/pdcKVOD1P0smMAAAAAPpueNm9TLrLE2TSGjw+A4Q==" for domain euronext.com, path /, expire 0
< Set-Cookie: incap_ses_1103_2784297=ib7VDHy0tnHw2/pdcKVOD1P0smMAAAAAPpueNm9TLrLE2TSGjw+A4Q==; path=/; Domain=.euronext.com
< X-CDN: Imperva
< X-Iinfo: 13-480095013-480095029 NNNY CT(21 45 0) RT(1672672339599 71) q(0 0 0 -1) r(3 3) U12
<
Content type 'text/csv;charset=UTF-8' length 263 bytes
* Connection #0 to host live.euronext.com left intact
downloaded 263 bytes
</code>```

Below you find an overview of file downloaded from R: it does not contain ISIN data.

What should I do to have data in my csv when downloaded from R?

Body:
On this website (https://live.euronext.com/en/products/etfs/list), you can download a csv file. The file can be directly downloaded with this direct link: https://live.euronext.com/pd_es/data/track/download?mics=XAMS%2CXBRU%2CXLIS%2CXPAR%2CXLDN%2CXMSM%2CXOSL.

You can use that link by putting it directly in your web browser. You can observe that after having hit Enter button, the file is downloading directly with data in it (ISIN code).
I would like to download this file from R; it downloads the file but the data are not there: so I tried to mimick the browser, so I used the exact same User-Agent but downloaded file remains empty (no ISIN code)

url2call <- "https://live.euronext.com/pd_es/data/track/download?mics=XAMS%2CXBRU%2CXLIS%2CXPAR%2CXLDN%2CXMSM%2CXOSL"
options(HTTPUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36")
getOption("HTTPUserAgent")

options(internet.info = 0)
getOption("internet.info")

expr = download.file(url = url2call,
                              destfile = "./file.csv",
                              quiet = FALSE,
                              method = "libcurl",
                              cacheOK = FALSE,
                              mode = "w")
print(expr)

Here is the log of code above:

trying URL 'https://live.euronext.com/pd_es/data/track/download?mics=XAMS%2CXBRU%2CXLIS%2CXPAR%2CXLDN%2CXMSM%2CXOSL'
*   Trying 45.223.139.7:443...
* Connected to live.euronext.com (45.223.139.7) port 443 (#0)
* schannel: disabled automatic use of client certificate
> GET /pd_es/data/track/download?mics=XAMS%2CXBRU%2CXLIS%2CXPAR%2CXLDN%2CXMSM%2CXOSL HTTP/1.1
Host: live.euronext.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
Accept: */*
Pragma: no-cache

* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Mon, 02 Jan 2023 15:12:20 GMT
< Server: Apache
* skipped cookie with bad tailmatch domain: priv.atos.fr
< Set-Cookie: SessionStatId=ec362863.5f14960ae7a67; path=/; expires=Tue, 31-Dec-30 15:12:20 GMT; domain=.priv.atos.fr; secure; httpOnly
< X-Content-Type-Options: nosniff
< Content-Disposition: attachment; filename="Euronext_ETPs_2023-01-02.csv"
< Vary: Accept-Encoding
< Content-Length: 263
< Content-Type: text/csv;charset=UTF-8
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Headers: X-Requested-With
* Added cookie visid_incap_2784297="TSHS7aJ+Sg+lIwsikCSFUFP0smMAAAAAQUIPAAAAAACORJXoFQ6SWQTy9K1vAVdW" for domain euronext.com, path /, expire 1704147471
< Set-Cookie: visid_incap_2784297=TSHS7aJ+Sg+lIwsikCSFUFP0smMAAAAAQUIPAAAAAACORJXoFQ6SWQTy9K1vAVdW; expires=Mon, 01 Jan 2024 22:17:51 GMT; HttpOnly; path=/; Domain=.euronext.com
* Added cookie incap_ses_1103_2784297="ib7VDHy0tnHw2/pdcKVOD1P0smMAAAAAPpueNm9TLrLE2TSGjw+A4Q==" for domain euronext.com, path /, expire 0
< Set-Cookie: incap_ses_1103_2784297=ib7VDHy0tnHw2/pdcKVOD1P0smMAAAAAPpueNm9TLrLE2TSGjw+A4Q==; path=/; Domain=.euronext.com
< X-CDN: Imperva
< X-Iinfo: 13-480095013-480095029 NNNY CT(21 45 0) RT(1672672339599 71) q(0 0 0 -1) r(3 3) U12
<
Content type 'text/csv;charset=UTF-8' length 263 bytes
* Connection #0 to host live.euronext.com left intact
downloaded 263 bytes

Below you find an overview of file downloaded from R: it does not contain ISIN data.

What should I do to have data in my csv when downloaded from R?


问:
Hibernate JPA @OneToMany join on 2 columns with OR statement in Entity
I have the following class:

```<code>public class Nomenclature extends BaseEntity {

    @Id
    @Column(name = "NOMENCLATURE_CODE")
    private String nomenclatureCode;

    @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, mappedBy = "nomenclatureCode",     orphanRemoval = true)
     private List<Cumul> cumuls = new ArrayList<>();
}
</code>```

I want to join the following Cumul class on 2 columns WHERE cumul.nomenclatureCode = nomenclature.nomenclatureCode OR cumul.nomenclatureCodeAllowedCumul = nomenclature.nomenclatureCode

```<code>public class Cumul extends BaseEntity  {

    @Id
    @Column(columnDefinition = "NUMERIC")
    @GeneratedValue(generator = "CUMUL", strategy = GenerationType.SEQUENCE)
    private Long id;

    @Column(name = "NOMENCLATURE_CODE")
    private String nomenclatureCode;

    @Column(name = "NOMENCLATURE_CODE_ALLOWED_CUMUL")
    private String nomenclatureCodeAllowedCumul;
</code>```
```<code>@OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL},orphanRemoval = true)
@JoinColumns(
        {
                @JoinColumn(name = "nomenclature_code", referencedColumnName = "nomenclature_code"),
                @JoinColumn(name = "nomenclature_code_allowed_cumul", referencedColumnName = "nomenclature_code")
        })
private List<Cumul> cumuls = new ArrayList<>();
</code>```

Worked but this an AND statement not an OR what I was looking for

Body:
I have the following class:

public class Nomenclature extends BaseEntity {

    @Id
    @Column(name = "NOMENCLATURE_CODE")
    private String nomenclatureCode;

    @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, mappedBy = "nomenclatureCode",     orphanRemoval = true)
     private List<Cumul> cumuls = new ArrayList<>();
}

I want to join the following Cumul class on 2 columns WHERE cumul.nomenclatureCode = nomenclature.nomenclatureCode OR cumul.nomenclatureCodeAllowedCumul = nomenclature.nomenclatureCode

public class Cumul extends BaseEntity  {

    @Id
    @Column(columnDefinition = "NUMERIC")
    @GeneratedValue(generator = "CUMUL", strategy = GenerationType.SEQUENCE)
    private Long id;

    @Column(name = "NOMENCLATURE_CODE")
    private String nomenclatureCode;

    @Column(name = "NOMENCLATURE_CODE_ALLOWED_CUMUL")
    private String nomenclatureCodeAllowedCumul;

@OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL},orphanRemoval = true)
@JoinColumns(
        {
                @JoinColumn(name = "nomenclature_code", referencedColumnName = "nomenclature_code"),
                @JoinColumn(name = "nomenclature_code_allowed_cumul", referencedColumnName = "nomenclature_code")
        })
private List<Cumul> cumuls = new ArrayList<>();

Worked but this an AND statement not an OR what I was looking for


问:
Start get request in Fragment A and show the data from response in Fragment B
trying to add a recyclerview to a fragment is driving me crazy...
I have Fragment A where I use a button to start 2 retrofit request, the first request fetches a token, that is used for the second request. When debugging I can see that the requests work and the needed data is fetched.
Then I have Fragment B, there I want the data from the second request to been shown in a recyclerview.
So first, is this easily handable or should I try to move the call of the second request in the Fragment B? (In that case I would have to pass the values entered in 2 edittext-fields in Fragment A to Fragment B).

To begin slowly I tried to create the recyclerview in Fragment A, having the request and the recyclerview in the same Fragment.
It worked:

```<code>class AddStalkerFragment : Fragment(R.layout.fragment_add_stalker) {
    private lateinit var binding: FragmentAddStalkerBinding
    private lateinit var sessionManager: SessionManager
    private lateinit var tvCategoryAdapter: TvCategoryAdapter

    val viewModel: StalkerViewModel by lazy {
        ViewModelProvider(this)[StalkerViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentAddStalkerBinding.inflate(inflater, container, false)
        val view = binding.root
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        prepareRecyclerView()

        sessionManager = SessionManager(this@AddStalkerFragment.requireActivity())

        val stalkerUrl = binding.etServerUrl.text
        val macAddress = binding.etMacAddress.text
        val buttonSave = binding.btnSaveStalker

        buttonSave.setOnClickListener {
            viewModel.getToken(
                url = stalkerUrl.toString(),
                cookie = "mac=${macAddress};stb_lang=en;timezone=Europe/Amsterdam;",
            )
            viewModel.getTvCategory(
                url = stalkerUrl.toString(),
                cookie = "mac=${macAddress};stb_lang=en;timezone=Europe/Amsterdam;",
                token = "Bearer ${sessionManager.fetchAuthToken()}"
            )
        }
            viewModel.getTokenLiveData.observe(viewLifecycleOwner) { response ->
                if (response == null) {
                    Toast.makeText(
                        this@AddStalkerFragment.requireActivity(),
                        "Token Error",
                        Toast.LENGTH_SHORT
                    ).show()
                    return@observe
                }
                val loginResponse = response.js.token
                Toast.makeText(
                    this@AddStalkerFragment.requireActivity(),
                    "Token Ok",
                    Toast.LENGTH_SHORT
                ).show()
                sessionManager.saveAuthToken(loginResponse)
            }
        viewModel.getTvCategoryLiveData.observe(viewLifecycleOwner) { response ->
            if (response == null) {
                Toast.makeText(
                    this@AddStalkerFragment.requireActivity(),
                    "Categories Error",
                    Toast.LENGTH_SHORT
                ).show()
                return@observe
            }
            Toast.makeText(
                this@AddStalkerFragment.requireActivity(),
                "Categories Ok",
                Toast.LENGTH_SHORT
            ).show()
            tvCategoryAdapter.setTvGenresList(response.js)
        }

        }
    private fun prepareRecyclerView() {
        tvCategoryAdapter = TvCategoryAdapter()
        binding.rvTest.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = tvCategoryAdapter
        }
    }
}
</code>```

And here is what I try in Fragment B to show the recyclerview with the data from Fragment A
Debugging"tvCategoryAdapter.setTvGenresList(response)" doesn't work in Fragment B, so it isn't even getting there :-)
I assume that I have to connect the two Fragments somehow (I did in Navigation Graph, is this enough?)

```<code>class TvCategoryFragment : Fragment(R.layout.fragment_tv_category) {
    private lateinit var binding: FragmentTvCategoryBinding
    private lateinit var tvCategoryAdapter: TvCategoryAdapter

    val viewModel: StalkerViewModel by lazy {
        ViewModelProvider(this)[StalkerViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentTvCategoryBinding.inflate(inflater, container, false)
        val view = binding.root
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        prepareRecyclerView()

        viewModel.getTvCategoryLiveData.observe(viewLifecycleOwner) { response ->
            if (response == null) {
                Toast.makeText(
                    this@TvCategoryFragment.requireActivity(),
                    "Categories Error",
                    Toast.LENGTH_SHORT
                ).show()
                return@observe
            }
            Toast.makeText(
                this@TvCategoryFragment.requireActivity(),
                "Categories Ok",
                Toast.LENGTH_LONG
            ).show()
            tvCategoryAdapter.setTvGenresList(response.js)
        }

    }
    private fun prepareRecyclerView() {
        tvCategoryAdapter = TvCategoryAdapter()
        binding.rvLayoutTvCategory.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = tvCategoryAdapter
        }
    }

}
</code>```

My adapter looks like this:

```<code>class TvCategoryAdapter : RecyclerView.Adapter<TvCategoryAdapter.ViewHolder>() {
    private var genreList = ArrayList<J>()
    fun setTvGenresList(genreList: List<J>) {
        this.genreList = genreList as ArrayList<J>
        notifyDataSetChanged()
    }

    class ViewHolder(val binding: RvItemTvcategoryBinding) : RecyclerView.ViewHolder(binding.root) {}

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            RvItemTvcategoryBinding.inflate(
                LayoutInflater.from(
                    parent.context
                )
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.rvItemTvcategory.text = genreList[position].title
    }

    override fun getItemCount(): Int {
        return genreList.size
    }
}
</code>```

Any hint that could help me to solve this? :-)

thanks in advance

Body:
trying to add a recyclerview to a fragment is driving me crazy...
I have Fragment A where I use a button to start 2 retrofit request, the first request fetches a token, that is used for the second request. When debugging I can see that the requests work and the needed data is fetched.
Then I have Fragment B, there I want the data from the second request to been shown in a recyclerview.
So first, is this easily handable or should I try to move the call of the second request in the Fragment B? (In that case I would have to pass the values entered in 2 edittext-fields in Fragment A to Fragment B).

To begin slowly I tried to create the recyclerview in Fragment A, having the request and the recyclerview in the same Fragment.
It worked:

class AddStalkerFragment : Fragment(R.layout.fragment_add_stalker) {
    private lateinit var binding: FragmentAddStalkerBinding
    private lateinit var sessionManager: SessionManager
    private lateinit var tvCategoryAdapter: TvCategoryAdapter

    val viewModel: StalkerViewModel by lazy {
        ViewModelProvider(this)[StalkerViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentAddStalkerBinding.inflate(inflater, container, false)
        val view = binding.root
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        prepareRecyclerView()

        sessionManager = SessionManager(this@AddStalkerFragment.requireActivity())

        val stalkerUrl = binding.etServerUrl.text
        val macAddress = binding.etMacAddress.text
        val buttonSave = binding.btnSaveStalker

        buttonSave.setOnClickListener {
            viewModel.getToken(
                url = stalkerUrl.toString(),
                cookie = "mac=${macAddress};stb_lang=en;timezone=Europe/Amsterdam;",
            )
            viewModel.getTvCategory(
                url = stalkerUrl.toString(),
                cookie = "mac=${macAddress};stb_lang=en;timezone=Europe/Amsterdam;",
                token = "Bearer ${sessionManager.fetchAuthToken()}"
            )
        }
            viewModel.getTokenLiveData.observe(viewLifecycleOwner) { response ->
                if (response == null) {
                    Toast.makeText(
                        this@AddStalkerFragment.requireActivity(),
                        "Token Error",
                        Toast.LENGTH_SHORT
                    ).show()
                    return@observe
                }
                val loginResponse = response.js.token
                Toast.makeText(
                    this@AddStalkerFragment.requireActivity(),
                    "Token Ok",
                    Toast.LENGTH_SHORT
                ).show()
                sessionManager.saveAuthToken(loginResponse)
            }
        viewModel.getTvCategoryLiveData.observe(viewLifecycleOwner) { response ->
            if (response == null) {
                Toast.makeText(
                    this@AddStalkerFragment.requireActivity(),
                    "Categories Error",
                    Toast.LENGTH_SHORT
                ).show()
                return@observe
            }
            Toast.makeText(
                this@AddStalkerFragment.requireActivity(),
                "Categories Ok",
                Toast.LENGTH_SHORT
            ).show()
            tvCategoryAdapter.setTvGenresList(response.js)
        }

        }
    private fun prepareRecyclerView() {
        tvCategoryAdapter = TvCategoryAdapter()
        binding.rvTest.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = tvCategoryAdapter
        }
    }
}

And here is what I try in Fragment B to show the recyclerview with the data from Fragment A
Debugging"tvCategoryAdapter.setTvGenresList(response)" doesn't work in Fragment B, so it isn't even getting there :-)
I assume that I have to connect the two Fragments somehow (I did in Navigation Graph, is this enough?)

class TvCategoryFragment : Fragment(R.layout.fragment_tv_category) {
    private lateinit var binding: FragmentTvCategoryBinding
    private lateinit var tvCategoryAdapter: TvCategoryAdapter

    val viewModel: StalkerViewModel by lazy {
        ViewModelProvider(this)[StalkerViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentTvCategoryBinding.inflate(inflater, container, false)
        val view = binding.root
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        prepareRecyclerView()

        viewModel.getTvCategoryLiveData.observe(viewLifecycleOwner) { response ->
            if (response == null) {
                Toast.makeText(
                    this@TvCategoryFragment.requireActivity(),
                    "Categories Error",
                    Toast.LENGTH_SHORT
                ).show()
                return@observe
            }
            Toast.makeText(
                this@TvCategoryFragment.requireActivity(),
                "Categories Ok",
                Toast.LENGTH_LONG
            ).show()
            tvCategoryAdapter.setTvGenresList(response.js)
        }

    }
    private fun prepareRecyclerView() {
        tvCategoryAdapter = TvCategoryAdapter()
        binding.rvLayoutTvCategory.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = tvCategoryAdapter
        }
    }

}

My adapter looks like this:

class TvCategoryAdapter : RecyclerView.Adapter<TvCategoryAdapter.ViewHolder>() {
    private var genreList = ArrayList<J>()
    fun setTvGenresList(genreList: List<J>) {
        this.genreList = genreList as ArrayList<J>
        notifyDataSetChanged()
    }

    class ViewHolder(val binding: RvItemTvcategoryBinding) : RecyclerView.ViewHolder(binding.root) {}

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            RvItemTvcategoryBinding.inflate(
                LayoutInflater.from(
                    parent.context
                )
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.rvItemTvcategory.text = genreList[position].title
    }

    override fun getItemCount(): Int {
        return genreList.size
    }
}

Any hint that could help me to solve this? :-)

thanks in advance


问:
MDLMesh strange buffer layout
I was curious to see the vertex positions of an MDLMesh for a boxWithExtent and I have notices a strange behaviour. When I print out the positions and normals for the first 3 vertices you get the below values. What I find weird is that for the 1st vertex we get 2 0.0s at the end to fit the stride for sims_float4 but weirdly for every subsequent vertex this becomes 1.0 - 0.0. Anyone has any idea why metal does this instead of just filling the last two positions with 0.0s as the first vertex. Thank you 0.5 0.5 0.5 -1.0 -0.0 -0.0 0.0 0.0 0.5 0.5 -0.5 -1.0 -0.0 -0.0 1.0 0.0 0.5 -0.5 0.5 -1.0 -0.0 -0.0 0.0 1.0

This behaviour goes away if I use a custom vertexDescriptor so I'm confused as what's going on here

Title: MDLMesh strange buffer layout


问:
Undertstanding UDP broadcast sending and receiving in C (system functions)
I'm trying to learn how sockets and networks work. For example in C in Linux. I have two simple programs. Both take ip and port as parameters. The first program is a server that broadcasts a message every second.

int main(int argc, char** argv){
    struct sockaddr_in server;
    if (argc < 3){ printf("\nToo few arguments. You need to pass ipv4 and port number!\n"); return 1; }

    int port = -1;
    if (isNumber(argv[2])) port = atoi(argv[2]);
    if (port < 0){
        printf("Error value for port!\n");
        return 1;
    }

    /** prepare server */
    server.sin_port = htons(port);
    server.sin_family = AF_INET;
    inet_aton(argv[1], &server.sin_addr);

    int serverSocket = socket(AF_INET, SOCK_DGRAM, 0);
    int broadcast=1;
    setsockopt(serverSocket, SOL_SOCKET, SO_BROADCAST,
               &broadcast, sizeof broadcast);

    bind(serverSocket, (struct sockaddr*) &server, sizeof(server));

    /** Client to send */
    struct sockaddr_in client;
    client.sin_port = htons(port);
    client.sin_family = AF_INET;
    client.sin_addr.s_addr = INADDR_BROADCAST;

    char buf[128] = "Test from server";
    while(1){
        sleep(1);
        sendto(serverSocket, buf, 18, 0, (struct sockaddr*) &client, sizeof(client));
    }
    close(serverSocket);
    return 0;
}
```
<p>The second program is a simple client that receives a message, prints it out, and outputs the sender's ip.</p>
<pre class="lang-cpp prettyprint-override"><code>int main(int argc, char** argv){
    struct sockaddr_in currUser;
    if (argc < 3){ printf("\nToo few arguments. You need to pass ipv4 and port number!\n"); return 1; }

    int port = -1;
    if (isNumber(argv[2])) port = atoi(argv[2]);
    if (port < 0){
        printf("Error value for port!\n");
        return 1;
    }

    currUser.sin_port = htons(port);
    currUser.sin_family = AF_INET;
    inet_aton(argv[1], &currUser.sin_addr);
    int userSocket = socket(AF_INET, SOCK_DGRAM, 0);
    bind(userSocket, (struct sockaddr*) &currUser, sizeof(currUser));

    /** listen */
    char buf[128];
    struct sockaddr_in brd;
    unsigned slen = sizeof(brd);
    while(1){
        int readCount = recvfrom(userSocket, buf, 128, 0, (struct sockaddr *)&brd, &slen);
        buf[readCount] = 0;
        printf("Get %s\n", buf);
        printf("Ip who send: %s\n", inet_ntoa(brd.sin_addr));
    }
    close(userSocket);
    return 0;
}
</code>```

I expect that  recvfrom get the source address of the message in brd . If I send directly to the client from the server (i.e. not broadcast, but in the client  parameter for sendto  specifying directly ip ),  it works. However, for the broadcast case, the address is different. Here is an example:

The output for $route is as follows:

```<code>Destination Gateway Genmask Flags Metric Ref Use Iface
default         _gateway        0.0.0.0         UG    600    0        0 wlp3s0
link-local      0.0.0.0         255.255.0.0     U     1000   0        0 br-29e12aa6bbb8
172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0
172.18.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-29e12aa6bbb8
192.168.0.0     0.0.0.0         255.255.255.0   U     600    0        0 wlp3s0

</code>```

Tell me please, I don't understand something in the operation of the recvfrom function or how the packet is transmitted over the network within these two programs?

Body:
I'm trying to learn how sockets and networks work. For example in C in Linux. I have two simple programs. Both take ip and port as parameters. The first program is a server that broadcasts a message every second.

int main(int argc, char** argv){
    struct sockaddr_in server;
    if (argc < 3){ printf("\nToo few arguments. You need to pass ipv4 and port number!\n"); return 1; }

    int port = -1;
    if (isNumber(argv[2])) port = atoi(argv[2]);
    if (port < 0){
        printf("Error value for port!\n");
        return 1;
    }

    /** prepare server */
    server.sin_port = htons(port);
    server.sin_family = AF_INET;
    inet_aton(argv[1], &server.sin_addr);

    int serverSocket = socket(AF_INET, SOCK_DGRAM, 0);
    int broadcast=1;
    setsockopt(serverSocket, SOL_SOCKET, SO_BROADCAST,
               &broadcast, sizeof broadcast);

    bind(serverSocket, (struct sockaddr*) &server, sizeof(server));

    /** Client to send */
    struct sockaddr_in client;
    client.sin_port = htons(port);
    client.sin_family = AF_INET;
    client.sin_addr.s_addr = INADDR_BROADCAST;

    char buf[128] = "Test from server";
    while(1){
        sleep(1);
        sendto(serverSocket, buf, 18, 0, (struct sockaddr*) &client, sizeof(client));
    }
    close(serverSocket);
    return 0;
}

The second program is a simple client that receives a message, prints it out, and outputs the sender's ip.

int main(int argc, char** argv){
    struct sockaddr_in currUser;
    if (argc < 3){ printf("\nToo few arguments. You need to pass ipv4 and port number!\n"); return 1; }

    int port = -1;
    if (isNumber(argv[2])) port = atoi(argv[2]);
    if (port < 0){
        printf("Error value for port!\n");
        return 1;
    }

    currUser.sin_port = htons(port);
    currUser.sin_family = AF_INET;
    inet_aton(argv[1], &currUser.sin_addr);
    int userSocket = socket(AF_INET, SOCK_DGRAM, 0);
    bind(userSocket, (struct sockaddr*) &currUser, sizeof(currUser));

    /** listen */
    char buf[128];
    struct sockaddr_in brd;
    unsigned slen = sizeof(brd);
    while(1){
        int readCount = recvfrom(userSocket, buf, 128, 0, (struct sockaddr *)&brd, &slen);
        buf[readCount] = 0;
        printf("Get %s\n", buf);
        printf("Ip who send: %s\n", inet_ntoa(brd.sin_addr));
    }
    close(userSocket);
    return 0;
}

I expect that  recvfrom get the source address of the message in brd . If I send directly to the client from the server (i.e. not broadcast, but in the client  parameter for sendto  specifying directly ip ),  it works. However, for the broadcast case, the address is different. Here is an example:

The output for $route is as follows:

Destination Gateway Genmask Flags Metric Ref Use Iface
default         _gateway        0.0.0.0         UG    600    0        0 wlp3s0
link-local      0.0.0.0         255.255.0.0     U     1000   0        0 br-29e12aa6bbb8
172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0
172.18.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-29e12aa6bbb8
192.168.0.0     0.0.0.0         255.255.255.0   U     600    0        0 wlp3s0

Tell me please, I don't understand something in the operation of the recvfrom function or how the packet is transmitted over the network within these two programs?


问:
Compressing an image-data string returned by captureVisibleTab (chrome api) and then edited by Konva
I have an extension which's taking a screenshot of a browser's tab. Later on, using Konva I'm editing the image and saving it in the following way:

When I print the image, it appears as the following:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABaAAAAOECAYAAABXTZbSAAAAAXNSR0IArs4c6QAAIABJREFUeF7snQeYJVWZ/t+quqnTJHKOgiQDSpiRICqKoitmzKvuuu7fALrrBjO7BgTDmuMGd03rGjEAMiQFUZSkiIKA...

and it continues with 587346 characters in total.

I'm attempting to compress the image. I was thinking of doing it using sharp, but it seems like they're not receiving image data string.

Any ideas how should I approach this?

Below is the component which was passed with the captureVisibleTab's return value (img data string):

```<code>// @ts-nocheck
import React from 'react';
import { Stage, Layer, Line, Image } from 'react-konva';
import { useState, useRef } from 'react';
import useImage from 'use-image';
import { Button, Stack, IconButton, Toolbar } from '@mui/material';
import useStackState from "@rooks/use-stack-state";

//import GestureIcon from '@mui/icons-material/Gesture';
import UndoIcon from '@mui/icons-material/Undo';
import RedoIcon from '@mui/icons-material/Redo';
import SaveIcon from '@mui/icons-material/Save';

type Props = {
    imgSrc: string,
    finishedEditing: (editedImg: string) => void;
}

function DrawingArea(props: Props) {
    const imgSrc = props.imgSrc;
    const finishedEditing = props.finishedEditing;

    const [lines, setLines] = useState<any[]>([]);
    const isDrawing = useRef(false);
    const [image, imageSet] = useImage(imgSrc);
    const [toRedo, toRedoSet] = useState(false);
    const [toUndo, toUndoSet] = useState(false);
    const [undoList, undoControls, undoStack] = useStackState([])
    const { push, peek, pop, length } = undoControls;

    const handleMouseDown = (e: any) => {
        isDrawing.current = true;
        const pos = e.target.getStage().getPointerPosition();
        setLines([...lines, { points: [pos.x, pos.ay] }]);
    };

    const handleRedo = () => {
        if (length === 0) {
            console.log("empty stack - no redos");
            return;
        }
        const elementToRedo = pop();
        setLines((lines) => {
            lines.push(elementToRedo)
            return lines;
        })
    };

    const handleClear = () => {
        if (lines.length === 0) return;
        setLines((lines) => {
            lines = [];
            return lines;
        })
        // need to empty redoStack
    }

    const handleUndo = () => {
        if (lines.length < 1) return //empty lines - no undo action needed.
        console.log(lines);
        console.log(lines.length);
        //pop into the stack
        const poppedElement = lines[lines.length - 1];
        undoControls.push(poppedElement); // for the redos
        setLines((lines: any[]) => {
            lines.pop();
            return lines;
        })
    };

    const handleMouseMove = (e: any) => {
        // no drawing - skipping
        if (!isDrawing.current) {
            return;
        }
        const stage = e.target.getStage();
        const point = stage.getPointerPosition();
        // To draw line
        let lastLine: any = lines[lines.length - 1];
        if (lastLine) {
            // add point
            lastLine.points = lastLine.points.concat([point.x, point.y]);

            // replace last
            lines.splice(lines.length - 1, 1, lastLine);
            setLines(lines.concat());
        }
    };

    const handleMouseUp = () => {
        isDrawing.current = false;
    };

    const stageRef = useRef(null);

    const handleSave = async () => {
        const dataURL = await stageRef.current.getStage().toDataURL();
        console.log(dataURL);

        finishedEditing(dataURL);
    }

    return (
        <Stack>
            <Stage
                width={window.screen.width}
                height={window.screen.height}
                onMouseDown={handleMouseDown}
                onMousemove={handleMouseMove}
                onMouseup={handleMouseUp}
                className="canvas-stage"
                ref={stageRef}
            >
                <Layer>
                    <Image image={image} />
                    {lines.map((line: any, i: number) => (
                        <Line
                            key={i}
                            points={line.points}
                            stroke="#df4b26"
                            strokeWidth={2}
                            tension={0.5}
                            lineCap="round"
                            globalCompositeOperation={
                                line.tool === 'eraser' ? 'destination-out' : 'source-over'
                            }
                        />
                    ))}
                </Layer>
            </Stage>

            <Toolbar sx={{ alignItems: "center" }}>
                <IconButton onClick={() => { toUndoSet(!toRedo); handleUndo(); }}> <UndoIcon /> </IconButton>
                <IconButton onClick={() => { toRedoSet(!toRedo); handleRedo(); }}> <RedoIcon /> </IconButton>
                <IconButton onClick={handleSave}> <SaveIcon /> </IconButton>
                <Button variant="contained" sx={{ width: "fit-content", alignItems: "flex-end" }} onClick={handleClear}>Clear</Button>
            </Toolbar>
        </Stack>
    )
}

export default DrawingArea
</code>```

Regards :_)

Body:
I have an extension which's taking a screenshot of a browser's tab. Later on, using Konva I'm editing the image and saving it in the following way:

When I print the image, it appears as the following:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABaAAAAOECAYAAABXTZbSAAAAAXNSR0IArs4c6QAAIABJREFUeF7snQeYJVWZ/t+quqnTJHKOgiQDSpiRICqKoitmzKvuuu7fALrrBjO7BgTDmuMGd03rGjEAMiQFUZSkiIKA...

and it continues with 587346 characters in total.

I'm attempting to compress the image. I was thinking of doing it using sharp, but it seems like they're not receiving image data string.

Any ideas how should I approach this?

Below is the component which was passed with the captureVisibleTab's return value (img data string):

// @ts-nocheck
import React from 'react';
import { Stage, Layer, Line, Image } from 'react-konva';
import { useState, useRef } from 'react';
import useImage from 'use-image';
import { Button, Stack, IconButton, Toolbar } from '@mui/material';
import useStackState from "@rooks/use-stack-state";

//import GestureIcon from '@mui/icons-material/Gesture';
import UndoIcon from '@mui/icons-material/Undo';
import RedoIcon from '@mui/icons-material/Redo';
import SaveIcon from '@mui/icons-material/Save';

type Props = {
    imgSrc: string,
    finishedEditing: (editedImg: string) => void;
}

function DrawingArea(props: Props) {
    const imgSrc = props.imgSrc;
    const finishedEditing = props.finishedEditing;

    const [lines, setLines] = useState<any[]>([]);
    const isDrawing = useRef(false);
    const [image, imageSet] = useImage(imgSrc);
    const [toRedo, toRedoSet] = useState(false);
    const [toUndo, toUndoSet] = useState(false);
    const [undoList, undoControls, undoStack] = useStackState([])
    const { push, peek, pop, length } = undoControls;

    const handleMouseDown = (e: any) => {
        isDrawing.current = true;
        const pos = e.target.getStage().getPointerPosition();
        setLines([...lines, { points: [pos.x, pos.ay] }]);
    };

    const handleRedo = () => {
        if (length === 0) {
            console.log("empty stack - no redos");
            return;
        }
        const elementToRedo = pop();
        setLines((lines) => {
            lines.push(elementToRedo)
            return lines;
        })
    };

    const handleClear = () => {
        if (lines.length === 0) return;
        setLines((lines) => {
            lines = [];
            return lines;
        })
        // need to empty redoStack
    }

    const handleUndo = () => {
        if (lines.length < 1) return //empty lines - no undo action needed.
        console.log(lines);
        console.log(lines.length);
        //pop into the stack
        const poppedElement = lines[lines.length - 1];
        undoControls.push(poppedElement); // for the redos
        setLines((lines: any[]) => {
            lines.pop();
            return lines;
        })
    };

    const handleMouseMove = (e: any) => {
        // no drawing - skipping
        if (!isDrawing.current) {
            return;
        }
        const stage = e.target.getStage();
        const point = stage.getPointerPosition();
        // To draw line
        let lastLine: any = lines[lines.length - 1];
        if (lastLine) {
            // add point
            lastLine.points = lastLine.points.concat([point.x, point.y]);

            // replace last
            lines.splice(lines.length - 1, 1, lastLine);
            setLines(lines.concat());
        }
    };

    const handleMouseUp = () => {
        isDrawing.current = false;
    };

    const stageRef = useRef(null);

    const handleSave = async () => {
        const dataURL = await stageRef.current.getStage().toDataURL();
        console.log(dataURL);

        finishedEditing(dataURL);
    }

    return (
        <Stack>
            <Stage
                width={window.screen.width}
                height={window.screen.height}
                onMouseDown={handleMouseDown}
                onMousemove={handleMouseMove}
                onMouseup={handleMouseUp}
                className="canvas-stage"
                ref={stageRef}
            >
                <Layer>
                    <Image image={image} />
                    {lines.map((line: any, i: number) => (
                        <Line
                            key={i}
                            points={line.points}
                            stroke="#df4b26"
                            strokeWidth={2}
                            tension={0.5}
                            lineCap="round"
                            globalCompositeOperation={
                                line.tool === 'eraser' ? 'destination-out' : 'source-over'
                            }
                        />
                    ))}
                </Layer>
            </Stage>

            <Toolbar sx={{ alignItems: "center" }}>
                <IconButton onClick={() => { toUndoSet(!toRedo); handleUndo(); }}> <UndoIcon /> </IconButton>
                <IconButton onClick={() => { toRedoSet(!toRedo); handleRedo(); }}> <RedoIcon /> </IconButton>
                <IconButton onClick={handleSave}> <SaveIcon /> </IconButton>
                <Button variant="contained" sx={{ width: "fit-content", alignItems: "flex-end" }} onClick={handleClear}>Clear</Button>
            </Toolbar>
        </Stack>
    )
}

export default DrawingArea

Regards :_)


问:
Adding listener to Cucumber
I need to add listener in Cucumber (v7.2) to write a log (log4j) to a file, something like ItestListener in TestNG I use Java (v17) and JUnit 5.Thanks a lot.</p>
```<code>My scenario

 Feature: Login
  As a user
  I want to test login functionality

   Scenario Outline: Check login with valid credentials
    Given User opens  homePage page
    When User clicks on 'login' link
    And User enter '<email>' into email field
    And User enter '<password>' into password field
    And User click on 'login' button
    Then User checks that current url '<url>'
</code>```

Title: Adding listener to Cucumber

Body:
I need to add listener in Cucumber (v7.2) to write a log (log4j) to a file, something like ItestListener in TestNG I use Java (v17) and JUnit 5.Thanks a lot.

My scenario

 Feature: Login
  As a user
  I want to test login functionality

   Scenario Outline: Check login with valid credentials
    Given User opens  homePage page
    When User clicks on 'login' link
    And User enter '<email>' into email field
    And User enter '<password>' into password field
    And User click on 'login' button
    Then User checks that current url '<url>'


问:
EOF Exception in DBeaver when establishing a connection
I'm using DBeaver and all of a sudden I'm facing this message whenever I try to establish a connection.

I don't have any additional information about this issue, but if you know where I can find it please let me know and I will provide it.

This occured moments after DBeaver popped a message asking to update de the drivers, so this might be related. So far I have tried to restart the PC and reinstall DBeaver, but with no success so far.

Did this ever happened to you? Any idea on what the problem might be?


问:
Foreach on 2 variables in csh
Is it possible in csh to do foreach on 2 variables like tcl ?

```<code>set test = (a 1 b 2)
foreach a b ($test) then
    echo $a
    echo $b
endif
</code>```

this code retrun an error

Title: Foreach on 2 variables in csh

Body:
Is it possible in csh to do foreach on 2 variables like tcl ?

set test = (a 1 b 2)
foreach a b ($test) then
    echo $a
    echo $b
endif

this code retrun an error


问:
Reduce line spacing in ggplot axis title?
THIS QUESTION WAS EDITED. PLEASE REFER TO THE EDITED PART.

SECOND EDIT: Problem solved using theme(axis.title.y = element_text(lineheight = 1))

I have created the following plot per ggplot

To implement a y-axis title with line spacing, I used

labs(y = paste0("Mean Precipitation Height across \nall days and all years"))

What I'd like to know is how to reduce the line spacing after splitting the text in the y-axis title in two.

EDIT:

I have figured out the following: When I simply print the plot,
the spacing of the y-axis title is ok. If I use ggsave(),
it weirdly changes.

Please refer to this reproducible code:

```<code>library(tidyverse)
library(here)

{
  set.seed(123)
  index = rep(c(1:10),
              each = 100) ; year = rep(c(1951:1960),
                                       each = 10, times = 10); month = rep(c(1:10),
                                                                           each = 1,
                                                                           times = 100)

  variable_of_interest = runif(1000,
                               min = 0,
                               max = 0.4); season = rep(x = c("Winter", "Winter", "Spring", "Spring", "Spring",
                                                              "Summer", "Summer", "Summer", "Autmn", "Autmn"),
                                                        times = 100)

  lat = rep(c(seq(from = 48,
                  to = 53,
                  length = 10)),
            each = 100); lon = rep(c(seq(from = 7,
                                         to = 14,
                                         length = 10)),
                                   each = 100)

  Variable_of_Interest = as.data.frame(cbind(index, year, month, variable_of_interest, season, lat, lon))

  Variable_of_Interest$month_of_year = paste0(Variable_of_Interest$year,
                                              "-",
                                              Variable_of_Interest$month)

  #Variable_of_Interest = Variable_of_Interest[order(Variable_of_Interest$year,
  #                                                                              Variable_of_Interest$month),]

  rownames(Variable_of_Interest) = NULL

  # Transform columns from character to numeric
  Variable_of_Interest = mutate_at(Variable_of_Interest,
                                   c(1,2,3,4,6,7),
                                   as.numeric)
}

Spatial_Means =
  group_by(.data = Variable_of_Interest,
           lat,
           lon) %>%
  summarise(mean_variable_of_interest = mean(variable_of_interest))

Spatial_Means_per_Latitudinal_Degree = ggplot(Spatial_Means) +

  geom_point(aes(x = lat,
                 y = mean_variable_of_interest),
             size = 1) +

  labs(title = "Latitudinal Means of Variable of Interest Across Time",
       x = "Latitude (degree)",
       y = paste0("Mean Variable of Interest across \nall days and all years")) +

  theme_bw() +

  theme(plot.title = element_text(hjust = 0.5,
                                  size = 40),
        axis.title.x = element_text(size = 20),
        axis.title.y = element_text(size = 20),
        axis.text.x = element_text(size = 20,
                                   face = "bold"),
        axis.text.y = element_text(size = 20,
                                   face =  "bold"))

ggsave(filename = "Spatial-Means-per-Latitudinal-Degree.JPG",
       plot = Spatial_Means_per_Latitudinal_Degree,
       path = here(),
       width = 10,
       height = 5)
</code>```

Body:
THIS QUESTION WAS EDITED. PLEASE REFER TO THE EDITED PART.

SECOND EDIT: Problem solved using theme(axis.title.y = element_text(lineheight = 1))

I have created the following plot per ggplot

To implement a y-axis title with line spacing, I used

labs(y = paste0("Mean Precipitation Height across \nall days and all years"))

What I'd like to know is how to reduce the line spacing after splitting the text in the y-axis title in two.

EDIT:

I have figured out the following: When I simply print the plot,
the spacing of the y-axis title is ok. If I use ggsave(),
it weirdly changes.

Please refer to this reproducible code:

library(tidyverse)
library(here)

{
  set.seed(123)
  index = rep(c(1:10),
              each = 100) ; year = rep(c(1951:1960),
                                       each = 10, times = 10); month = rep(c(1:10),
                                                                           each = 1,
                                                                           times = 100)

  variable_of_interest = runif(1000,
                               min = 0,
                               max = 0.4); season = rep(x = c("Winter", "Winter", "Spring", "Spring", "Spring",
                                                              "Summer", "Summer", "Summer", "Autmn", "Autmn"),
                                                        times = 100)

  lat = rep(c(seq(from = 48,
                  to = 53,
                  length = 10)),
            each = 100); lon = rep(c(seq(from = 7,
                                         to = 14,
                                         length = 10)),
                                   each = 100)

  Variable_of_Interest = as.data.frame(cbind(index, year, month, variable_of_interest, season, lat, lon))

  Variable_of_Interest$month_of_year = paste0(Variable_of_Interest$year,
                                              "-",
                                              Variable_of_Interest$month)

  #Variable_of_Interest = Variable_of_Interest[order(Variable_of_Interest$year,
  #                                                                              Variable_of_Interest$month),]

  rownames(Variable_of_Interest) = NULL

  # Transform columns from character to numeric
  Variable_of_Interest = mutate_at(Variable_of_Interest,
                                   c(1,2,3,4,6,7),
                                   as.numeric)
}

Spatial_Means =
  group_by(.data = Variable_of_Interest,
           lat,
           lon) %>%
  summarise(mean_variable_of_interest = mean(variable_of_interest))

Spatial_Means_per_Latitudinal_Degree = ggplot(Spatial_Means) +

  geom_point(aes(x = lat,
                 y = mean_variable_of_interest),
             size = 1) +

  labs(title = "Latitudinal Means of Variable of Interest Across Time",
       x = "Latitude (degree)",
       y = paste0("Mean Variable of Interest across \nall days and all years")) +

  theme_bw() +

  theme(plot.title = element_text(hjust = 0.5,
                                  size = 40),
        axis.title.x = element_text(size = 20),
        axis.title.y = element_text(size = 20),
        axis.text.x = element_text(size = 20,
                                   face = "bold"),
        axis.text.y = element_text(size = 20,
                                   face =  "bold"))

ggsave(filename = "Spatial-Means-per-Latitudinal-Degree.JPG",
       plot = Spatial_Means_per_Latitudinal_Degree,
       path = here(),
       width = 10,
       height = 5)


问:
Javascript Short-circuit expression gives confusing result
I am quite confused and don't understand what's going on with the output of this javascript expression evaluation.

let m = 6;
let x=true;

m = m || x ? 10 : 0;
console.log(m); //10```
</div>
</div>
</p>
<p>In above example we have m = 6 || 10, so m should be 6 but it outputs 10.</p>
<pre class="lang-js prettyprint-override"><code>let m = 6;
let x=false;

m = m || x ? 10 : 0;
console.log(m); //10
</code>```

Similarly in above expression we have m = 6 || 0 which should also output 6 but still it outputs 10.

Can someone please explain what's going on here?

Body:
I am quite confused and don't understand what's going on with the output of this javascript expression evaluation.

let m = 6;
let x=true;

m = m || x ? 10 : 0;
console.log(m); //10

In above example we have m = 6 || 10, so m should be 6 but it outputs 10.

let m = 6;
let x=false;

m = m || x ? 10 : 0;
console.log(m); //10

Similarly in above expression we have m = 6 || 0 which should also output 6 but still it outputs 10.

Can someone please explain what's going on here?


问:
After connecting firebase in my project , output will gone When i remove firebase code in Main.dart project will run correct
Image of issue

Please help to solve it

Body:
Image of issue

Please help to solve it


问:
CPU usage linux - Prometheus to c#
I've been reading this article: https://www.robustperception.io/understanding-machine-cpu-usage/

And I'm trying to understand how can we translate this good example of CPU usage by percentage excluding the "idle" to c#:

```<code>100 - (avg by (instance) (rate(node_cpu_seconds_total{job="node",mode="idle"}[1m])) * 100)
</code>```

I've tried doing this but the values are off..:

```<code>Dictionary<string, ExporterParam> currentExporterDic = new Dictionary<string, ExporterParam>();
double cpuLoad = 100* (currentExporterDic["node_cpu_seconds_total"].GetSum("idle") - _previousExporterDic["node_cpu_seconds_total"].GetSum("idle")) / delta.TotalSeconds;
_previousExporterDic = currentExporterDic;
</code>```

Any ideas?

Title: CPU usage linux - Prometheus to c#

Body:
I've been reading this article: https://www.robustperception.io/understanding-machine-cpu-usage/

And I'm trying to understand how can we translate this good example of CPU usage by percentage excluding the "idle" to c#:

100 - (avg by (instance) (rate(node_cpu_seconds_total{job="node",mode="idle"}[1m])) * 100)

I've tried doing this but the values are off..:

Dictionary<string, ExporterParam> currentExporterDic = new Dictionary<string, ExporterParam>();
double cpuLoad = 100* (currentExporterDic["node_cpu_seconds_total"].GetSum("idle") - _previousExporterDic["node_cpu_seconds_total"].GetSum("idle")) / delta.TotalSeconds;
_previousExporterDic = currentExporterDic;

Any ideas?


问:
Redirecting to other url when specific url is called from the browser through nginx
I have hosted my JavaScript application in aws ec2 server. I'm using centos 7 and placed my JavaScript static files in /usr/share/nginx/html directory. I'm using nginx as reverse proxy.I have one yaml file inside this JavaScript files that is accessible through the browser. The yaml file contains all the sensitive information but that file is necessary to load my application. Is there any way to disable direct access to that file in browser. Or is there any way to disable that information disclosure in browser through nginx.Thanks in advance for the help.

I have tried

```<code> location /properties.yaml {
rewrite ^/$ /login.html permanent;
}
</code>```

But this is not working. Then i tried to read that file from other location like

```<code>location /properties.yaml{
try_files $uri /var/www/html/properties.yaml;
}
</code>```

Could you please guide.

Body:
I have hosted my JavaScript application in aws ec2 server. I'm using centos 7 and placed my JavaScript static files in /usr/share/nginx/html directory. I'm using nginx as reverse proxy.I have one yaml file inside this JavaScript files that is accessible through the browser. The yaml file contains all the sensitive information but that file is necessary to load my application. Is there any way to disable direct access to that file in browser. Or is there any way to disable that information disclosure in browser through nginx.Thanks in advance for the help.

I have tried

 location /properties.yaml {
rewrite ^/$ /login.html permanent;
}

But this is not working. Then i tried to read that file from other location like

location /properties.yaml{
try_files $uri /var/www/html/properties.yaml;
}

Could you please guide.


问:
Unable to install homebrew on mac
I wanted to install homebrew on my mac but wasn't able to

i tried running the homebrew cmd on my terminal but i keep getting an error
something like this

curl: (35) error:140943E8:SSL routines:ssl3_read_bytes:reason(1000)

Title: Unable to install homebrew on mac


问:
Why are some external libc symbols not resolved in my "perf report" output?
My "perf report" output has things like this:

```<code>18.31%     0.00%  tclsqlite3  libc.so.6             [.] 0x00007f0aaa322be4
        |
        ---0x7f0aaa322be4

18.28%    18.28%  tclsqlite3  libc.so.6             [.] 0x00000000001a0be4
        |
        ---__strncat_ssse3
           ttThreadMain
           sqlite3_step
           sqlite3VdbeExec
           sqlite3VdbeHalt
           sqlite3HctBtreeCommitPhaseTwo
           btreeFlushData
           |
            --18.27%--sqlite3HctDbInsert
                      |
                       --18.21%--0x7f0aaa322be4
</code>```

and elsewhere stuff like:

```<code>|--63.81%--sqlite3HctDbInsert
|          |--43.69%--hctDbInsert
|           --18.24%--0x7f0aaa322be4
</code>```

How should this be interpreted? Is the 18% some libc function? How does one get a symbol for it?

Body:
My "perf report" output has things like this:

18.31%     0.00%  tclsqlite3  libc.so.6             [.] 0x00007f0aaa322be4
        |
        ---0x7f0aaa322be4

18.28%    18.28%  tclsqlite3  libc.so.6             [.] 0x00000000001a0be4
        |
        ---__strncat_ssse3
           ttThreadMain
           sqlite3_step
           sqlite3VdbeExec
           sqlite3VdbeHalt
           sqlite3HctBtreeCommitPhaseTwo
           btreeFlushData
           |
            --18.27%--sqlite3HctDbInsert
                      |
                       --18.21%--0x7f0aaa322be4

and elsewhere stuff like:

|--63.81%--sqlite3HctDbInsert
|          |--43.69%--hctDbInsert
|           --18.24%--0x7f0aaa322be4

How should this be interpreted? Is the 18% some libc function? How does one get a symbol for it?


问:
NextJS module aliases double declaration needed for import of index
I am setting up my module aliases in a NextJS project and everything runs fine so far.

The issue I have comes when I have a folder utils that includes both, an index.ts but also another someModule.ts.

My imports looked like this before:

```<code>import { someHelper } from '../utils'
import { anotherHelper } from '../utils/someModule'
</code>```

Assuming I am setting the following module alias "@/utils/*": ["utils/*"], I would need to amend the first of the two imports like this:

```<code>import { someHelper } from '@/utils/index' // <-- see how I need to add index
</code>```

unless I am extending the tsconfig with a second module alias like this: "@/utils": ["utils"].

This feels a bit like duplication to me, so I am wondering whether this is needed or do you have another option how to solve this?

Body:
I am setting up my module aliases in a NextJS project and everything runs fine so far.

The issue I have comes when I have a folder utils that includes both, an index.ts but also another someModule.ts.

My imports looked like this before:

import { someHelper } from '../utils'
import { anotherHelper } from '../utils/someModule'

Assuming I am setting the following module alias "@/utils/*": ["utils/*"], I would need to amend the first of the two imports like this:

import { someHelper } from '@/utils/index' // <-- see how I need to add index

unless I am extending the tsconfig with a second module alias like this: "@/utils": ["utils"].

This feels a bit like duplication to me, so I am wondering whether this is needed or do you have another option how to solve this?