问:
How to start a service even when the app is not open
Here I am creating a chat app. In this app I want to load data from firebase realtime database whenever user switch on his internet or connects his phone to wifi no matter whether the app is open or not. I am doing this using service and broadcast. But I don't know why its not working. The method of fetching data is working properly as I have checked it in another activity.  Kindly checkout my codes below

I have registered my broadcast and service in menifest file as

```<code><service android:name=".broadcasts.receiveMsgService" android:exported="true"/>
    <receiver android:name=".broadcasts.receiveChattersBroadcast"
    android:exported="true"
        android:enabled="true" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
</code>```

My broadcast file

```<code>public class receiveChattersBroadcast extends BroadcastReceiver {

 @Override
public void onReceive(Context context, Intent intent) {
    // Check the action of the intent
    String action = intent.getAction();
    if (action.equals(Intent.ACTION_BOOT_COMPLETED) ||
  action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        // Start the background service
        Intent serviceIntent = new Intent(context, receiveMsgService.class);
        context.startService(serviceIntent);
    }
}
}
</code>```

My service file

```<code>public class receiveMsgService extends Service {
private static final String LOG_TAG = "MyForegroundService";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(LOG_TAG, "onStartCommand");

    // Load the messages from Firebase
    loadMessagesFromFirebase();

    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public void loadMessagesFromFirebase(){
    FirebaseDatabase database;
    DatabaseReference refernec;

   // chatrecycler = view.findViewById(R.id.fragAllChatRecycler);
    database = FirebaseDatabase.getInstance();
    refernec = FirebaseDatabase.getInstance().getReference();
    refernec.keepSynced(true);
    ArrayList<chatterModal2> modals = new ArrayList();
    SharedPreferencelogin session = new SharedPreferencelogin(getApplicationContext());
    String userFireId = session.getFireId();
    databaseHelper db = new databaseHelper(getApplicationContext());
    database.getReference().child("chatters").addValueEventListener(new
 ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if(snapshot.exists()){
                for (DataSnapshot snapshot1:snapshot.getChildren()){
                    chatterModal2 modal = snapshot1.getValue(chatterModal2.class) ;

                    String receiverId = modal.getRecieverId();
                    String sender = modal.getSenderId();

                    if(receiverId.trim().equals(userFireId) ||
  sender.equals(userFireId)) {
                        modals.add(modal);
                        String addResult = db.addChatter(modal.getRecieverId(),
   modal.getSenderId(), modal.getMsg(), modal.getUnseen(), modal.getProId(),
    String.valueOf(modal.getTime()));

                    }else{
                        //do nothing
                    }

                }

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

     }
   }
</code>```

I have not mentioned this service and broadcast any where else. Do I have to mention it or call it in any activity? Please tell me what's wrong

Body:
Here I am creating a chat app. In this app I want to load data from firebase realtime database whenever user switch on his internet or connects his phone to wifi no matter whether the app is open or not. I am doing this using service and broadcast. But I don't know why its not working. The method of fetching data is working properly as I have checked it in another activity.  Kindly checkout my codes below

I have registered my broadcast and service in menifest file as

<service android:name=".broadcasts.receiveMsgService" android:exported="true"/>
    <receiver android:name=".broadcasts.receiveChattersBroadcast"
    android:exported="true"
        android:enabled="true" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

My broadcast file

public class receiveChattersBroadcast extends BroadcastReceiver {

 @Override
public void onReceive(Context context, Intent intent) {
    // Check the action of the intent
    String action = intent.getAction();
    if (action.equals(Intent.ACTION_BOOT_COMPLETED) ||
  action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        // Start the background service
        Intent serviceIntent = new Intent(context, receiveMsgService.class);
        context.startService(serviceIntent);
    }
}
}

My service file

public class receiveMsgService extends Service {
private static final String LOG_TAG = "MyForegroundService";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(LOG_TAG, "onStartCommand");

    // Load the messages from Firebase
    loadMessagesFromFirebase();

    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public void loadMessagesFromFirebase(){
    FirebaseDatabase database;
    DatabaseReference refernec;

   // chatrecycler = view.findViewById(R.id.fragAllChatRecycler);
    database = FirebaseDatabase.getInstance();
    refernec = FirebaseDatabase.getInstance().getReference();
    refernec.keepSynced(true);
    ArrayList<chatterModal2> modals = new ArrayList();
    SharedPreferencelogin session = new SharedPreferencelogin(getApplicationContext());
    String userFireId = session.getFireId();
    databaseHelper db = new databaseHelper(getApplicationContext());
    database.getReference().child("chatters").addValueEventListener(new
 ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if(snapshot.exists()){
                for (DataSnapshot snapshot1:snapshot.getChildren()){
                    chatterModal2 modal = snapshot1.getValue(chatterModal2.class) ;

                    String receiverId = modal.getRecieverId();
                    String sender = modal.getSenderId();

                    if(receiverId.trim().equals(userFireId) ||
  sender.equals(userFireId)) {
                        modals.add(modal);
                        String addResult = db.addChatter(modal.getRecieverId(),
   modal.getSenderId(), modal.getMsg(), modal.getUnseen(), modal.getProId(),
    String.valueOf(modal.getTime()));

                    }else{
                        //do nothing
                    }

                }

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

     }
   }

I have not mentioned this service and broadcast any where else. Do I have to mention it or call it in any activity? Please tell me what's wrong


来源: stackexchange

问:
Flask SocketIO in GCP Cloud Run experiencing issues with pub/sub using GCP Redis after a certain period of time
We are currently running Flask SocketIO in GCP Cloud Run, with message_queue utilizing GCP Redis (Memorystore) through a VPC network.

The GCP Redis instance is of Basic type, with a capacity of 12 GB.
Our VPC network comprises 2 min instances, 3 max instances, with 3 active instances, and other servers that use the same VPC network.
We are using Flask SocketIO version 5.3.2
We are using python package redis version 4.4.0

Initially, everything was functioning properly, but we have encountered issues after a certain period of time. The first instance happened after approximately 10 hours, and the second instance occurred after about 3 days. (Note that the revisions we were using were different between instances)

We have observed the following:

The first time, we added some log and re-deployed the Flask SocketIO server, and it started working properly again.

The second time:

We switched to the previous revision (1) of Flask SocketIO server, and it started working properly again.

We switched back to the newest revision (2), and it stopped working.

We switched back to the previous revision (1) again, and it started working properly again.

However, after a while, when we switched back to the newest revision (2), it started working again.

We checked the GCP logging explorer, around the last time the browser was able to receive websocket data, and found an error log: ERROR:socketio:Cannot publish to Redis... retrying

We didn't see Cannot publish to Redis... giving up

When the server stopped working, the log from Flask SocketIO (also Python-SocketIO and Python-EngineIO that it uses) only showed emitting event "message" to room_1 [/some-namespace], which is from Python-SocketIO.

In the logs from Python-SocketIO, there was no pubsub message: emit found, which is generated when it receives a message from Redis in the _thread function of the PubSubManager class.

(If more information is needed, please let me know)

ContentLicense: CC BY-SA 4.0


问:
tdengine 3.0.2.2 query order by ts desc limit 10 very slow
query stable order by ts desc limit 10 very slow. that stable only 30K+ rows, but it's very slow

Database parameters used:
Database parameters

Verbs used: select

Describe the total amount of data

Observed performance vs. expected performance

enter image description here
enter image description here

my environment:

OS: Rocky linux 8
16G Memory, 8C CPU, 100G SSD
TDengine Version [3.0.2.2]


问:
Argument of type 'typeof Bar' is not assignable to parameter of type 'typeof BaseDataModel'
I realised after spending some time that if I don't put a constructor in the BaseDataModel, I will get an error in the last line

Argument of type 'typeof Bar' is not assignable to parameter of type
'typeof BaseDataModel'.

So my question is WHY a missing constructor in the Base class creates incompatibility ?

```<code>abstract class BaseDataModel {
    static fromJson<T>(json: any): T {
        return Object.assign(new this(), json);
    }

    constructor(obj?: any) {
    } //if you remove this constructor, you will get an error
}

class Foo extends BaseDataModel {
    id: number;
    name: string;
}

export class Bar extends BaseDataModel {
    id: number;
    name: string;

    constructor(obj: NonFunctionProperties<NewPostPayload>) {
        super()
        Object.assign(this, obj)
        this.title = obj.title
        this.content = obj.content

    }

}

function validateServerPayload(body: any, asdfasf: typeof BaseDataModel) {
    const payload = asdfasf.fromJson(body);
    validate(payload)
}

validateServerPayload({id: 1, name: 'foo'}, NewPostPayload);
validateServerPayload({id: 1, name: 'foo'}, Foo);
validateServerPayload({id: 1, name: 'foo'}, Bar); // error here
</code>```

Body:
I realised after spending some time that if I don't put a constructor in the BaseDataModel, I will get an error in the last line

Argument of type 'typeof Bar' is not assignable to parameter of type
'typeof BaseDataModel'.

So my question is WHY a missing constructor in the Base class creates incompatibility ?

abstract class BaseDataModel {
    static fromJson<T>(json: any): T {
        return Object.assign(new this(), json);
    }

    constructor(obj?: any) {
    } //if you remove this constructor, you will get an error
}

class Foo extends BaseDataModel {
    id: number;
    name: string;
}

export class Bar extends BaseDataModel {
    id: number;
    name: string;

    constructor(obj: NonFunctionProperties<NewPostPayload>) {
        super()
        Object.assign(this, obj)
        this.title = obj.title
        this.content = obj.content

    }

}

function validateServerPayload(body: any, asdfasf: typeof BaseDataModel) {
    const payload = asdfasf.fromJson(body);
    validate(payload)
}

validateServerPayload({id: 1, name: 'foo'}, NewPostPayload);
validateServerPayload({id: 1, name: 'foo'}, Foo);
validateServerPayload({id: 1, name: 'foo'}, Bar); // error here


问:
Get host-address of other containers
I have a specific issue related to Docker compose.
I am currently using docker compose version: 3.8

I have a gateway build in nodejs
I need to get the container address of other application available in the gateway as environment variable.
I looked into various documents but none of them are working.

```<code>version: "3.8"
services:
  user_service:
    build:
      context: ./user-service
    environment:
      NODE_PORT: 4000
  authentication_service:
    build:
      context: ./authentication_service
    environment:
      NODE_PORT: 3001
  gateway:
    build: ./public-gateway
    environment:
      - NODE_PORT=2000
      - USER_SERVICE=user_service
    depends_on:
      - user_service
      - authentication_service
    links:
      - user_service:user_service
    restart: always
</code>```

Above is the docker compose file.
But in the gateway code i am not able to get the host address of USER_SERVICE.
I also read that links are deprecated in version 3.8 and host address are automatically available in all the application within the same network.

I printed process.env in nodejs application but i all i see is USER_SERVICE: user_service

I would really appreciate it if someone can pint me in the correct direction.

I would like to see the host address of the USER_SERVICE when i print process.env.USER_SERVICE in the nodejs application

Updated docker compose file which is working

```<code>version: "3.8"
services:
  user_service:
    build:
      context: ./user-service
    environment:
      NODE_PORT: 4000
  authentication_service:
    build:
      context: ./authentication_service
    environment:
      NODE_PORT: 3001
  gateway:
    build: ./public-gateway
    environment:
      - NODE_PORT=2000
      - USER_SERVICE=http://user_service:4000/user/service
    depends_on:
      - user_service
      - authentication_service
    restart: always
</code>```

Note: During run time of docker
USER_SERVICE=http://user_service:4000/user/service
user_service will be replaced by ip address. Even if you print the environment variable[USER_SERVICE] it would show http://user_service:4000/user/service.
user_service This would be resolved by the DNS.

Title: Get host-address of other containers

Body:
I have a specific issue related to Docker compose.
I am currently using docker compose version: 3.8

I have a gateway build in nodejs
I need to get the container address of other application available in the gateway as environment variable.
I looked into various documents but none of them are working.

version: "3.8"
services:
  user_service:
    build:
      context: ./user-service
    environment:
      NODE_PORT: 4000
  authentication_service:
    build:
      context: ./authentication_service
    environment:
      NODE_PORT: 3001
  gateway:
    build: ./public-gateway
    environment:
      - NODE_PORT=2000
      - USER_SERVICE=user_service
    depends_on:
      - user_service
      - authentication_service
    links:
      - user_service:user_service
    restart: always

Above is the docker compose file.
But in the gateway code i am not able to get the host address of USER_SERVICE.
I also read that links are deprecated in version 3.8 and host address are automatically available in all the application within the same network.

I printed process.env in nodejs application but i all i see is USER_SERVICE: user_service

I would really appreciate it if someone can pint me in the correct direction.

I would like to see the host address of the USER_SERVICE when i print process.env.USER_SERVICE in the nodejs application

Updated docker compose file which is working

version: "3.8"
services:
  user_service:
    build:
      context: ./user-service
    environment:
      NODE_PORT: 4000
  authentication_service:
    build:
      context: ./authentication_service
    environment:
      NODE_PORT: 3001
  gateway:
    build: ./public-gateway
    environment:
      - NODE_PORT=2000
      - USER_SERVICE=http://user_service:4000/user/service
    depends_on:
      - user_service
      - authentication_service
    restart: always

Note: During run time of docker
USER_SERVICE=http://user_service:4000/user/service
user_service will be replaced by ip address. Even if you print the environment variable[USER_SERVICE] it would show http://user_service:4000/user/service.
user_service This would be resolved by the DNS.


问:
Problems when trying to install the prisma dependency with NPM
I am trying to set up a project with next.js, and when I install the prisma dependency with the command npm i -D prisma I get the following error

```<code>npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! prisma@4.8.1 preinstall: `node scripts/preinstall-entry.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the prisma@4.8.1 preinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

Checking the logs I see the following capture

For whatever reason, when I try to run the script prisma@4.8.1 preinstall: node scripts/preinstall-entry.js I get those terminal errors and the installation is interrupted.

Checking and informing myself, https://www.prisma.io/docs/reference/system-requirements, I read about checking the node version, but they ask for a minimum version of 14.17.X or higher and I have version 14.16.0, on the other hand, npm completely updated.

If I update node, can I have compatibility problems with other projects I have?
I have also tried to delete the node_modules folder, package-lock, do npm clean cache --force, and re-run npm install with everything in my package.json, but the error persists....
If you can think of anything I would appreciate it

Best regards!

Body:
I am trying to set up a project with next.js, and when I install the prisma dependency with the command npm i -D prisma I get the following error

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! prisma@4.8.1 preinstall: `node scripts/preinstall-entry.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the prisma@4.8.1 preinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Checking the logs I see the following capture

For whatever reason, when I try to run the script prisma@4.8.1 preinstall: node scripts/preinstall-entry.js I get those terminal errors and the installation is interrupted.

Checking and informing myself, https://www.prisma.io/docs/reference/system-requirements, I read about checking the node version, but they ask for a minimum version of 14.17.X or higher and I have version 14.16.0, on the other hand, npm completely updated.

If I update node, can I have compatibility problems with other projects I have?
I have also tried to delete the node_modules folder, package-lock, do npm clean cache --force, and re-run npm install with everything in my package.json, but the error persists....
If you can think of anything I would appreciate it

Best regards!


问:
Memory leak caused by MobileAds.registerWebView
I add MobileAds.registerWebView (webView) in activity onCreate; However, a memory leak was found,
When I delete this code, I will not prompt for memory leak
How to solve this problem?</p>
```<code>GC Root: Thread object
│
├─ Dk instance
│    Leaking: NO (PathClassLoader↓ is not leaking)
│    Thread name: 'CleanupReference'
│    ↓ Thread.contextClassLoader
├─ dalvik.system.PathClassLoader instance
│    Leaking: NO (zzbzz↓ is not leaking and A ClassLoader is never leaking)
│    ↓ ClassLoader.runtimeInternalObjects
├─ java.lang.Object[] array
│    Leaking: NO (zzbzz↓ is not leaking)
│    ↓ Object[2266]
├─ com.google.android.gms.internal.ads.zzbzz class
│    Leaking: NO (a class is never leaking)
│    ↓ static zzbzz.zza
│                   ~~~
├─ com.google.android.gms.internal.ads.zzcfk instance
│    Leaking: UNKNOWN
│    Retaining 16 B in 1 objects
│    ↓ zzasd.zza
│            ~~~
├─ com.google.android.gms.ads.nonagon.signalgeneration.ab instance
│    Leaking: UNKNOWN
│    Retaining 379.4 kB in 5156 objects
│    e instance of sg.just4fun.tgasdk.ui.HomeActivity with mDestroyed = true
│    ↓ ab.e
│         ~
╰→ xxx.xxx.WebViewActivity instance
     Leaking: YES (ObjectWatcher was watching this because xxx.xxx.WebViewActivity received Activity#onDestroy() callback and
     Activity#mDestroyed is true)
     Retaining 376.6 kB in 5078 objects
     key = 9500b00e-35f4-476d-bb2e-836c21f4c80f
     watchDurationMillis = 7971
     retainedDurationMillis = 2971
     mApplication instance of com.just4fun.tga.App
     mBase instance of androidx.appcompat.view.ContextThemeWrapper
</code>```

Body:
I add MobileAds.registerWebView (webView) in activity onCreate; However, a memory leak was found,
When I delete this code, I will not prompt for memory leak
How to solve this problem?

GC Root: Thread object
│
├─ Dk instance
│    Leaking: NO (PathClassLoader↓ is not leaking)
│    Thread name: 'CleanupReference'
│    ↓ Thread.contextClassLoader
├─ dalvik.system.PathClassLoader instance
│    Leaking: NO (zzbzz↓ is not leaking and A ClassLoader is never leaking)
│    ↓ ClassLoader.runtimeInternalObjects
├─ java.lang.Object[] array
│    Leaking: NO (zzbzz↓ is not leaking)
│    ↓ Object[2266]
├─ com.google.android.gms.internal.ads.zzbzz class
│    Leaking: NO (a class is never leaking)
│    ↓ static zzbzz.zza
│                   ~~~
├─ com.google.android.gms.internal.ads.zzcfk instance
│    Leaking: UNKNOWN
│    Retaining 16 B in 1 objects
│    ↓ zzasd.zza
│            ~~~
├─ com.google.android.gms.ads.nonagon.signalgeneration.ab instance
│    Leaking: UNKNOWN
│    Retaining 379.4 kB in 5156 objects
│    e instance of sg.just4fun.tgasdk.ui.HomeActivity with mDestroyed = true
│    ↓ ab.e
│         ~
╰→ xxx.xxx.WebViewActivity instance
     Leaking: YES (ObjectWatcher was watching this because xxx.xxx.WebViewActivity received Activity#onDestroy() callback and
     Activity#mDestroyed is true)
     Retaining 376.6 kB in 5078 objects
     key = 9500b00e-35f4-476d-bb2e-836c21f4c80f
     watchDurationMillis = 7971
     retainedDurationMillis = 2971
     mApplication instance of com.just4fun.tga.App
     mBase instance of androidx.appcompat.view.ContextThemeWrapper


问:
Reference to type 'IHtmlString' claims it is defined in 'System.Web', but it could not be found
Error: Reference to type 'IHtmlString' claims it is defined in 'System.Web', but it could not be found

I am trying to display some data from database into a grid and doing sorting & pagging on that grid. Rather than creating sorting & pagging manually, i found about WebGrid or GridView(old framework). I need similar grid that I can use for new  .net6+

I am using visual studio 2022, asp.net core web app and .net 6 version.

i searched on google but said to either use older version of .net framework or use asp.net core MVC or adding reference inside system file

I dont want to use older version of .net or visual studio. I am not using MVC. I only have program.cs file in my project not system

ref link

```<code>@using System.Web.Helpers;
@{
    var webGrid = new WebGrid(Model.ShapesList);
    @webGrid.GetHtml()
}
</code>```

i downloaded following nugets:

```<code>Microsoft.AspNet.WebPages
Microsoft.AspNet.Mvc
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlSe
Microsoft.EntityFrameworkCore.Tool
</code>```

Body:
Error: Reference to type 'IHtmlString' claims it is defined in 'System.Web', but it could not be found

I am trying to display some data from database into a grid and doing sorting & pagging on that grid. Rather than creating sorting & pagging manually, i found about WebGrid or GridView(old framework). I need similar grid that I can use for new  .net6+

I am using visual studio 2022, asp.net core web app and .net 6 version.

i searched on google but said to either use older version of .net framework or use asp.net core MVC or adding reference inside system file

I dont want to use older version of .net or visual studio. I am not using MVC. I only have program.cs file in my project not system

ref link

@using System.Web.Helpers;
@{
    var webGrid = new WebGrid(Model.ShapesList);
    @webGrid.GetHtml()
}

i downloaded following nugets:

Microsoft.AspNet.WebPages
Microsoft.AspNet.Mvc
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlSe
Microsoft.EntityFrameworkCore.Tool


问:
Store external token using msal-angular
I have an angular web applicaton using Azure AD B2C for access control.

I have a different Android application that use the same authentication system.

Currently, the Android App can open the original web application, but it requires the user to log in again.

The user has to log into the web app separately, in spite of having already logged in via the Android app.

I feel I ought to be able to pass the token acquired by the Android App to the web app, possibly storing it in local storage for @azure/msal-angular to use.

This ought ought to be a trivial issue, but I can't see a straightforward solution.

Title: Store external token using msal-angular


问:
How to understand GetRedirectedTypeOrNull Methods？
Why should we redirect the implementation when registering singleton and scope services?

```<code>protected virtual ServiceDescriptor CreateServiceDescriptor(
    Type implementationType,
    Type exposingServiceType,
    List<Type> allExposingServiceTypes,
    ServiceLifetime lifeTime)
{
    if (lifeTime.IsIn(ServiceLifetime.Singleton, ServiceLifetime.Scoped))
    {
        var redirectedType = GetRedirectedTypeOrNull(
            implementationType,
            exposingServiceType,
            allExposingServiceTypes
        );
        if (redirectedType != null)
        {
            return ServiceDescriptor.Describe(
                exposingServiceType,
                provider => provider.GetService(redirectedType),
                lifeTime
            );
        }
    }
    return ServiceDescriptor.Describe(
        exposingServiceType,
        implementationType,
        lifeTime
    );
}
</code>```

If this is a design, Then I don't understand the following phenomenon:
1.If exposed IA1 and IA2, Then they access different instance.

```<code>[ExposeServices(typeof(IA1), typeof(IA2))]
public class A: IA1, IA2, IScopedDependency
</code>```

However, A is also exposed by default.
2.If exposed A, IA and IA2, Then they refer to the same instance

```<code>[ExposeServices(typeof(A), typeof(IA1), typeof(IA2))]
</code>```

Body:
Why should we redirect the implementation when registering singleton and scope services?

protected virtual ServiceDescriptor CreateServiceDescriptor(
    Type implementationType,
    Type exposingServiceType,
    List<Type> allExposingServiceTypes,
    ServiceLifetime lifeTime)
{
    if (lifeTime.IsIn(ServiceLifetime.Singleton, ServiceLifetime.Scoped))
    {
        var redirectedType = GetRedirectedTypeOrNull(
            implementationType,
            exposingServiceType,
            allExposingServiceTypes
        );
        if (redirectedType != null)
        {
            return ServiceDescriptor.Describe(
                exposingServiceType,
                provider => provider.GetService(redirectedType),
                lifeTime
            );
        }
    }
    return ServiceDescriptor.Describe(
        exposingServiceType,
        implementationType,
        lifeTime
    );
}

If this is a design, Then I don't understand the following phenomenon:
1.If exposed IA1 and IA2, Then they access different instance.

[ExposeServices(typeof(IA1), typeof(IA2))]
public class A: IA1, IA2, IScopedDependency

However, A is also exposed by default.
2.If exposed A, IA and IA2, Then they refer to the same instance

[ExposeServices(typeof(A), typeof(IA1), typeof(IA2))]


问:
QAbstractTextDocumentLayout.PaintContext works in PyQt5 but not PySide2
I'm working on a log console widget and to be able to achieve what I want I need something that can handle a VERY LARGE amount of line, I tried QPlainTextEdit (And QTextEdit) and they are not good enough for what I need, too slow when there's too much text.
-> Right now, everything works, I just have an issue with how selection highlight is drawn.

My implementation is based on a QTextDocument that hold all the text and I use it to draw it's content in a simple QWidget subclass. It works beautifully except the selection that does not seems to work in PySide2 but works as expected in PyQt5.
In fact it seems that PySide2 is missing the selection attribute on the QAbstractTextDocumentLayout.PaintContext. I tried to have a look to the woboq C++ source code but I can't find how to reimplement what is missing as it's using the D-Pointer (Q_D)

There's an MRE so you can test, you can just replace the import for PyQt5 or PySide2 and then the text selection will work only in PyQt5.

```<code>import sys
from PyQt5 import QtWidgets, QtGui, QtCore

LOREM_IPSUM = \
'''
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi dictum ligula mi, ut venenatis urna molestie et.
Phasellus velit nunc, consequat nec felis ut, egestas pulvinar mi.
In hac habitasse platea dictumst.
Mauris eget faucibus est, vitae suscipit neque.
Curabitur elementum tellus nec mauris rutrum laoreet.
Duis condimentum consequat dui sit amet semper.
Nam varius aliquet nibh, sit amet molestie ex scelerisque a.
Donec sodales, sapien non consequat luctus, ante quam pretium nibh, sed egestas augue nunc et augue.
'''

class TextEdit(QtWidgets.QWidget):
    def __init__(self, document, parent=None):
        super(TextEdit, self).__init__(parent=None)

        self._document = document
        self._selectionStart = 0
        self._selectionEnd = 0

        self.cur = QtGui.QTextCursor(self._document)

        self._selectionFormat = QtGui.QTextCharFormat()
        self._selectionFormat.setBackground(QtGui.QColor('#2B4A69'))

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)

        # This is the problematic area
        ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
        selection = QtGui.QAbstractTextDocumentLayout.Selection()
        selection.cursor = self.cur
        selection.format = self._selectionFormat
        # print(ctx.selections)  # Works in PyQt5, not PySide2 where the attribute is missing.
        ctx.selections = [selection]

        self._document.documentLayout().draw(painter, ctx)

    def mousePressEvent(self, event):
        start = end = self._document.documentLayout().hitTest(event.pos(), QtCore.Qt.FuzzyHit)
        self.cur.setPosition(start)
        self.cur.setPosition(end, QtGui.QTextCursor.KeepAnchor)

        self.update()

    def mouseMoveEvent(self, event):
        end = self._document.documentLayout().hitTest(event.pos(), QtCore.Qt.FuzzyHit)
        self.cur.setPosition(end, QtGui.QTextCursor.KeepAnchor)

        self.update()

if __name__ == "__main__":
    if QtWidgets.QApplication.instance() is not None:
        app = QtWidgets.QApplication.instance()
    else:
        app = QtWidgets.QApplication([])

    doc = QtGui.QTextDocument()
    doc.setPlainText(LOREM_IPSUM)

    widget = TextEdit(doc)
    widget.show()

    sys.exit(app.exec_())
</code>```

The reason why I need PySide2 and not PyQt5 is because I'm developing a tool for Autodesk Maya that ship with PySide2, so I need to stick with it, also that's what we use at my job so I don't have the choice.

PS: A ticket was opened 3 years ago but no answer and no workaround: https://bugreports.qt.io/browse/PYSIDE-1220

Body:
I'm working on a log console widget and to be able to achieve what I want I need something that can handle a VERY LARGE amount of line, I tried QPlainTextEdit (And QTextEdit) and they are not good enough for what I need, too slow when there's too much text.
-> Right now, everything works, I just have an issue with how selection highlight is drawn.

My implementation is based on a QTextDocument that hold all the text and I use it to draw it's content in a simple QWidget subclass. It works beautifully except the selection that does not seems to work in PySide2 but works as expected in PyQt5.
In fact it seems that PySide2 is missing the selection attribute on the QAbstractTextDocumentLayout.PaintContext. I tried to have a look to the woboq C++ source code but I can't find how to reimplement what is missing as it's using the D-Pointer (Q_D)

There's an MRE so you can test, you can just replace the import for PyQt5 or PySide2 and then the text selection will work only in PyQt5.

import sys
from PyQt5 import QtWidgets, QtGui, QtCore

LOREM_IPSUM = \
'''
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi dictum ligula mi, ut venenatis urna molestie et.
Phasellus velit nunc, consequat nec felis ut, egestas pulvinar mi.
In hac habitasse platea dictumst.
Mauris eget faucibus est, vitae suscipit neque.
Curabitur elementum tellus nec mauris rutrum laoreet.
Duis condimentum consequat dui sit amet semper.
Nam varius aliquet nibh, sit amet molestie ex scelerisque a.
Donec sodales, sapien non consequat luctus, ante quam pretium nibh, sed egestas augue nunc et augue.
'''

class TextEdit(QtWidgets.QWidget):
    def __init__(self, document, parent=None):
        super(TextEdit, self).__init__(parent=None)

        self._document = document
        self._selectionStart = 0
        self._selectionEnd = 0

        self.cur = QtGui.QTextCursor(self._document)

        self._selectionFormat = QtGui.QTextCharFormat()
        self._selectionFormat.setBackground(QtGui.QColor('#2B4A69'))

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)

        # This is the problematic area
        ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
        selection = QtGui.QAbstractTextDocumentLayout.Selection()
        selection.cursor = self.cur
        selection.format = self._selectionFormat
        # print(ctx.selections)  # Works in PyQt5, not PySide2 where the attribute is missing.
        ctx.selections = [selection]

        self._document.documentLayout().draw(painter, ctx)

    def mousePressEvent(self, event):
        start = end = self._document.documentLayout().hitTest(event.pos(), QtCore.Qt.FuzzyHit)
        self.cur.setPosition(start)
        self.cur.setPosition(end, QtGui.QTextCursor.KeepAnchor)

        self.update()

    def mouseMoveEvent(self, event):
        end = self._document.documentLayout().hitTest(event.pos(), QtCore.Qt.FuzzyHit)
        self.cur.setPosition(end, QtGui.QTextCursor.KeepAnchor)

        self.update()

if __name__ == "__main__":
    if QtWidgets.QApplication.instance() is not None:
        app = QtWidgets.QApplication.instance()
    else:
        app = QtWidgets.QApplication([])

    doc = QtGui.QTextDocument()
    doc.setPlainText(LOREM_IPSUM)

    widget = TextEdit(doc)
    widget.show()

    sys.exit(app.exec_())

The reason why I need PySide2 and not PyQt5 is because I'm developing a tool for Autodesk Maya that ship with PySide2, so I need to stick with it, also that's what we use at my job so I don't have the choice.

PS: A ticket was opened 3 years ago but no answer and no workaround: https://bugreports.qt.io/browse/PYSIDE-1220


问:
How do I filter some data that I just fetch/get from a spreadsheet?
I'm calling/fetching some data by Name from a spreadsheet, which the output of my current code is:

No.
Name
XXX
Location
Status
Date
Days

1.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
AAA
7-Sep-22
163 Days

2.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
BBB
4-Mar-22
135 Days

3.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
CCC
6-Jun-22
34 Days

4.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
DDD
6-Oct-22
5 Daysv

5.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
EEE
23-Dec-22
145 Days

6.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
FFF
12-Jan-22
6 Days

But the problem is I need to filter "AAA", "CCC", and "FFF", so that the column that has "AAA", "CCC", and "FFF" doesn't come out to be part of the output, and the output will be like this:

¬No.
Name
XXX
Location
Status
Date
Days

1.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
BBB
4-Mar-22
135 Days

2.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
DDD
6-Oct-22
5 Days

3.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
EEE
23-Dec-22
145 Days

How do I do that?

Here's my code:

```<code>function GetAllProject() {
  var rangeName = '//';
  var rows = Sheets.Spreadsheets.Values.get(SheetData, rangeName).values;
  return rows;
}

const WaspangList = [//,//,//]

function SearchProjectbyWaspang(Name) {

  if (WaspangList.indexOf(Name.toUpperCase()) == -1) return "The name is not registered!"

  var project = GetAllProject();
  var no = 1;
  var num = 1;
  const data = [];

  var table = '<b>No. | Name| XXX | Location | Status | Date | Days</b>\n';

  for (var row = 0; row < project.length; row++) {
    if (project[row][7] == Name.toUpperCase()) {
      var resi = num++ + ". | " + project[row][3] + " | " + project[row][5] + " | " + project[row][6] + " | " + project[row][10] + " | " + project[row][12] + " | " + project[row][80] + " Days" + '\n\n';
      data.push(resi);
    }
  }

  var join= table + data;
  var clearComa = join.toString();
  var dataNew = clearComa.replaceAll(",", "")
  return dataNew;
}

function RunSearchProjectbyWaspang() {
  WaspangList.forEach(Name => {
    let getData = SearchProjectbyWaspang(Name)
    let send = sendText(-xxxxxxxxxxx, getData)
    Logger.log("Successfully sent data : " + Name)
  })
}
</code>```

Body:
I'm calling/fetching some data by Name from a spreadsheet, which the output of my current code is:

No.
Name
XXX
Location
Status
Date
Days

1.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
AAA
7-Sep-22
163 Days

2.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
BBB
4-Mar-22
135 Days

3.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
CCC
6-Jun-22
34 Days

4.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
DDD
6-Oct-22
5 Daysv

5.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
EEE
23-Dec-22
145 Days

6.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
FFF
12-Jan-22
6 Days

But the problem is I need to filter "AAA", "CCC", and "FFF", so that the column that has "AAA", "CCC", and "FFF" doesn't come out to be part of the output, and the output will be like this:

¬No.
Name
XXX
Location
Status
Date
Days

1.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
BBB
4-Mar-22
135 Days

2.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
DDD
6-Oct-22
5 Days

3.
AAAAAAAAAAAAA
XXX
XXXXXXXXXXXX
EEE
23-Dec-22
145 Days

How do I do that?

Here's my code:

function GetAllProject() {
  var rangeName = '//';
  var rows = Sheets.Spreadsheets.Values.get(SheetData, rangeName).values;
  return rows;
}

const WaspangList = [//,//,//]

function SearchProjectbyWaspang(Name) {

  if (WaspangList.indexOf(Name.toUpperCase()) == -1) return "The name is not registered!"

  var project = GetAllProject();
  var no = 1;
  var num = 1;
  const data = [];

  var table = 'No. | Name| XXX | Location | Status | Date | Days\n';

  for (var row = 0; row < project.length; row++) {
    if (project[row][7] == Name.toUpperCase()) {
      var resi = num++ + ". | " + project[row][3] + " | " + project[row][5] + " | " + project[row][6] + " | " + project[row][10] + " | " + project[row][12] + " | " + project[row][80] + " Days" + '\n\n';
      data.push(resi);
    }
  }

  var join= table + data;
  var clearComa = join.toString();
  var dataNew = clearComa.replaceAll(",", "")
  return dataNew;
}

function RunSearchProjectbyWaspang() {
  WaspangList.forEach(Name => {
    let getData = SearchProjectbyWaspang(Name)
    let send = sendText(-xxxxxxxxxxx, getData)
    Logger.log("Successfully sent data : " + Name)
  })
}


问:
How to calculate factorial with masm32
I'm working on a compiler from C to masm32 code, the task is to calculate the factorial of some number (9 in this case), here is the code that I have:

```<code>.386
.model flat, stdcall
option casemap:none
include     C:\\masm32\\include\\masm32rt.inc
.data
res dword ?
.code
multiplyNumbers proc C n:dword
cmp n,0
jge ElsePart0
mov eax, 1
ret
ElsePart0:
ret
push 1
push n
call multiplyNumbers
multiplyNumbers endp
main proc C
push 0
pop res
push 9
call multiplyNumbers
mov res, eax
fn MessageBox,0,str$(eax),"Factroial",MB_OK
mov eax, res
ret
main endp

start:
call main
end start
</code>```

It looks messed up, as the compiler works like that for now...

The problem is that it's not calculating the factorial of 9 (nine is hardcoded) properly

I would be very thankful if somebody could fix that code with minimal code changes

Btw, here is similar C code:

```<code>int multiplyNumbers(int n) {
    if (n <= 0) {
        return 1;
    }
    return n * multiplyNumbers(n - 1);
}

int main() {
    int res = 0;
    res = multiplyNumbers(9);
    return res;
}
</code>```

The expected result is the asm code properly calculating factorial of 9

9! = 362880

right now it outputs 1703884

Title: How to calculate factorial with masm32

Body:
I'm working on a compiler from C to masm32 code, the task is to calculate the factorial of some number (9 in this case), here is the code that I have:

.386
.model flat, stdcall
option casemap:none
include     C:\\masm32\\include\\masm32rt.inc
.data
res dword ?
.code
multiplyNumbers proc C n:dword
cmp n,0
jge ElsePart0
mov eax, 1
ret
ElsePart0:
ret
push 1
push n
call multiplyNumbers
multiplyNumbers endp
main proc C
push 0
pop res
push 9
call multiplyNumbers
mov res, eax
fn MessageBox,0,str$(eax),"Factroial",MB_OK
mov eax, res
ret
main endp

start:
call main
end start

It looks messed up, as the compiler works like that for now...

The problem is that it's not calculating the factorial of 9 (nine is hardcoded) properly

I would be very thankful if somebody could fix that code with minimal code changes

Btw, here is similar C code:

int multiplyNumbers(int n) {
    if (n <= 0) {
        return 1;
    }
    return n * multiplyNumbers(n - 1);
}

int main() {
    int res = 0;
    res = multiplyNumbers(9);
    return res;
}

The expected result is the asm code properly calculating factorial of 9

9! = 362880

right now it outputs 1703884


问:
HTTP and custom TCP server with actix-web
I have a REST API service written in Rust with Actix Web, but now it needs to accept connections from a GPS tracker.

The GPS tracker report its position opening a TCP connection and sending data directly as a text stream, not a HTTP connection.

I know I should probably accept these connections in another port, but I have no clue how to implement it, since actix-web doesn't provide a way to create a TCP socket server.

For now I have a small Python script that receives the messages from the GPS trackers and does a POST request to the Rust service, but it is very hacky.

Is it possible to receive raw TCP and HTTP requests in the same binary with Actix Web?


问:
Using multithreading to modify global variables seems to cause a memory leak
testframe.jpg is a picture with a size of 1440*1080. I use thread pool to write them to a global dict. Then call clear dict. But the memory is not completely released. If I do not call multithreading using the following method, memory will be released normally. What causes the memory not to be released.

This script will not completely free memory

from multiprocessing.pool import ThreadPool
import time
import gc

def test(ids):
    global data
    for i in range(1000):
        with open("testframe.jpg","rb") as f:
            tmp=f.read()
        data[ids+i]=tmp
    print(len(data))

def gg():
    global data
    data.clear()

if __name__ == '__main__':
    data={}
    tmp=[i*1000 for i in range(20)]

    with ThreadPool(10) as thread_pool:
        result_list = thread_pool.map(test, tmp)

    thread_pool.close()
    thread_pool.join()
    gc.collect()
    time.sleep(5)
    print("clear")
    gg()
    # use memory 1GB
    time.sleep(5)
```
<p>This can free memory</p>
<pre class="lang-py prettyprint-override"><code>from multiprocessing.pool import ThreadPool
import time
import gc

def test(ids):
    global data
    for i in range(1000):
        with open("testframe.jpg","rb") as f:
            tmp=f.read()
        data[ids+i]=tmp
    print(len(data))

def gg():
    global data
    data.clear()

if __name__ == '__main__':
    data={}
    tmp=[i*1000 for i in range(20)]

    for i in range(20):
        test(1000*i)

    time.sleep(5)
    print("clear")
    gg()
    # use memory 100MB
    time.sleep(5)
</code>```

Body:
testframe.jpg is a picture with a size of 1440*1080. I use thread pool to write them to a global dict. Then call clear dict. But the memory is not completely released. If I do not call multithreading using the following method, memory will be released normally. What causes the memory not to be released.

This script will not completely free memory

from multiprocessing.pool import ThreadPool
import time
import gc

def test(ids):
    global data
    for i in range(1000):
        with open("testframe.jpg","rb") as f:
            tmp=f.read()
        data[ids+i]=tmp
    print(len(data))

def gg():
    global data
    data.clear()

if __name__ == '__main__':
    data={}
    tmp=[i*1000 for i in range(20)]

    with ThreadPool(10) as thread_pool:
        result_list = thread_pool.map(test, tmp)

    thread_pool.close()
    thread_pool.join()
    gc.collect()
    time.sleep(5)
    print("clear")
    gg()
    # use memory 1GB
    time.sleep(5)

This can free memory

from multiprocessing.pool import ThreadPool
import time
import gc

def test(ids):
    global data
    for i in range(1000):
        with open("testframe.jpg","rb") as f:
            tmp=f.read()
        data[ids+i]=tmp
    print(len(data))

def gg():
    global data
    data.clear()

if __name__ == '__main__':
    data={}
    tmp=[i*1000 for i in range(20)]

    for i in range(20):
        test(1000*i)

    time.sleep(5)
    print("clear")
    gg()
    # use memory 100MB
    time.sleep(5)


问:
Not getting XY image size after using "zoom to rect" in a matplotlib figure when using GUI
I am trying to get a ROI (region of interest) from a loaded image. Using the "Zoom to rect" option from the matplotlib figure and sing a GUI with 2 buttons:

Zoom to rect
Button1: "LoadImage"- load and plot the image and should also save into 2 list the new XY size of the zoomed image
Button2: "RunimgeAnalisis" should read the information of the 2 list in order to crop the ROI out of the original image

Problem: my code is not saving in the lists (xlist/ylist) the new XY information after using the "Zoom to rect". Whe running the code WITHOUT the GUI(bottons), I do obtain the XY size after selecting the zoom with the mouse but when implementing the code into a GUI-buttons, the new XY values of the zoom are not passed to the list. Right after selecting the zoom area in the image with the mouse,  the values are never passed to the execution of the program.

My code:

```<code>import numpy as np
import scipy.signal
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import BOTH, END, LEFT
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import os

xlist =[]
ylist =[]
image_path = 'C:/Users/Desktop/Images/TestImage1.raw'

# Load image, the image is ploted and the user will select with the mouse a ROI with the
#zoom rectangle option from matplotlib a new (x1, x2) and (y1,y2) will be saved on xlist ylist
def LoadImage(image_path):
    InputImage = np.fromfile(image_path, dtype='uint16', count=3840 \* 2160)
    InputImage = np.reshape(InputImage, (2160, 3840))
    xlist = []
    ylist = []
    plt.figure(1)
    plt.imshow(InputImage, interpolation_stage='rgba')

    #A ROI form the image is selected with the zoom rectantgle from matpotlib (Declare and register  callbacks)
    def on_xlims_change(event_ax):
        xlist.append(event_ax.get_xlim())
        print("updated xlims: ", event_ax.get_xlim())

    def on_ylims_change(event_ax):
        ylist.append(event_ax.get_ylim())
        print("updated ylims: ", event_ax.get_ylim())
    plt.colorbar()
</code>```
```<code>#with the information from xlist and ylist, the ROI is croped and saved in ImageRegion for
#further analisis
def RunImageAnalisis(xlist, ylist):
     x1 = int(xlist[0])
     x2 = int(xlist[1])
     y1 = int(ylist[0])
     y2 = int(ylist[1])
     ImageRegion = ImageToProcess[y1:y2, x1:x2]

#GUI with 2 buttons: LoadImage and RunAnalisis
root = tk.Tk()
root.title("Image Tool")
MainForm = tk.Canvas(root, width=145, height=320)
MainForm.grid(columnspan =3, row=2)

bottom_Name = tk.StringVar()
Run_btn = tk.Button(root, text='Run', command=lambda:RunImageAnalisis(xlist, ylist), height=1, width=9, fg="black", bg="grey")
bottom_Name.set("Run")
Run_btn.grid(column=1, row=1, sticky='nw', padx=15, pady=15)

bottom_Name1 = tk.StringVar()
GetData_btn = tk.Button(root, text='LoadIm', command=lambda:LoadImage(image_path),  height=1, width=9, fg="black", bg="grey")
bottom_Name.set("LoadIm")
GetData_btn.grid(column=2, row=1, sticky='nw',pady=15)

root.mainloop()
</code>```

I tried: I ran the code without using the GUI-implementation and this is working  correctly. The new xy values are correctly saved in the xlist and ylist after selecting the zoom area with the mouse

But when I ran the GUI implemented code on debug mode, I could corroborate that after selecting with the mouse the image zoom area, the values are never passed to the xlist/ylist. Seems like program execution is hanging on the image and data never return to the program and thus variable explorer is empty

Expected Result : Button "Load" should load and plot the image. then the user should select with the mouse the zoom area and new xy values should be saved in xlist and ylist

Then, button "RunImageAnalisis" should use new XY values saved on xlist and ylist to crop the ROI out of the original image. This new ROI image array will be used for further analysis

thank you for your help

Body:
I am trying to get a ROI (region of interest) from a loaded image. Using the "Zoom to rect" option from the matplotlib figure and sing a GUI with 2 buttons:

Zoom to rect
Button1: "LoadImage"- load and plot the image and should also save into 2 list the new XY size of the zoomed image
Button2: "RunimgeAnalisis" should read the information of the 2 list in order to crop the ROI out of the original image

Problem: my code is not saving in the lists (xlist/ylist) the new XY information after using the "Zoom to rect". Whe running the code WITHOUT the GUI(bottons), I do obtain the XY size after selecting the zoom with the mouse but when implementing the code into a GUI-buttons, the new XY values of the zoom are not passed to the list. Right after selecting the zoom area in the image with the mouse,  the values are never passed to the execution of the program.

My code:

import numpy as np
import scipy.signal
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import BOTH, END, LEFT
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import os

xlist =[]
ylist =[]
image_path = 'C:/Users/Desktop/Images/TestImage1.raw'

# Load image, the image is ploted and the user will select with the mouse a ROI with the
#zoom rectangle option from matplotlib a new (x1, x2) and (y1,y2) will be saved on xlist ylist
def LoadImage(image_path):
    InputImage = np.fromfile(image_path, dtype='uint16', count=3840 \* 2160)
    InputImage = np.reshape(InputImage, (2160, 3840))
    xlist = []
    ylist = []
    plt.figure(1)
    plt.imshow(InputImage, interpolation_stage='rgba')

    #A ROI form the image is selected with the zoom rectantgle from matpotlib (Declare and register  callbacks)
    def on_xlims_change(event_ax):
        xlist.append(event_ax.get_xlim())
        print("updated xlims: ", event_ax.get_xlim())

    def on_ylims_change(event_ax):
        ylist.append(event_ax.get_ylim())
        print("updated ylims: ", event_ax.get_ylim())
    plt.colorbar()

#with the information from xlist and ylist, the ROI is croped and saved in ImageRegion for
#further analisis
def RunImageAnalisis(xlist, ylist):
     x1 = int(xlist[0])
     x2 = int(xlist[1])
     y1 = int(ylist[0])
     y2 = int(ylist[1])
     ImageRegion = ImageToProcess[y1:y2, x1:x2]

#GUI with 2 buttons: LoadImage and RunAnalisis
root = tk.Tk()
root.title("Image Tool")
MainForm = tk.Canvas(root, width=145, height=320)
MainForm.grid(columnspan =3, row=2)

bottom_Name = tk.StringVar()
Run_btn = tk.Button(root, text='Run', command=lambda:RunImageAnalisis(xlist, ylist), height=1, width=9, fg="black", bg="grey")
bottom_Name.set("Run")
Run_btn.grid(column=1, row=1, sticky='nw', padx=15, pady=15)

bottom_Name1 = tk.StringVar()
GetData_btn = tk.Button(root, text='LoadIm', command=lambda:LoadImage(image_path),  height=1, width=9, fg="black", bg="grey")
bottom_Name.set("LoadIm")
GetData_btn.grid(column=2, row=1, sticky='nw',pady=15)

root.mainloop()

I tried: I ran the code without using the GUI-implementation and this is working  correctly. The new xy values are correctly saved in the xlist and ylist after selecting the zoom area with the mouse

But when I ran the GUI implemented code on debug mode, I could corroborate that after selecting with the mouse the image zoom area, the values are never passed to the xlist/ylist. Seems like program execution is hanging on the image and data never return to the program and thus variable explorer is empty

Expected Result : Button "Load" should load and plot the image. then the user should select with the mouse the zoom area and new xy values should be saved in xlist and ylist

Then, button "RunImageAnalisis" should use new XY values saved on xlist and ylist to crop the ROI out of the original image. This new ROI image array will be used for further analysis

thank you for your help


问:
Powershell Error "You cannot call a method on a null-valued expression" when I create new Doc document in power Automate desktop
I'd like to make power automate desktop flow for making PDF from Image.
I can't find direct method from image to PDF, so, I tried to make new word document and insert image. After that I tried to convert document to PDF with below code. However it doesn't work.
Can you please advise what is wrong?

(Error)
You cannot call a method on a null-valued expression.
At C:\Users\m\AppData\Local\Temp\Robin\3q3a3wvbqx1.tmp.ps1:33 char:2

```<code>$ObjectSelection.InlineShapes.AddPicture($ImageName)
</code>```

```<code>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code>```

CategoryInfo          : InvalidOperation: (:) [], RuntimeException

FullyQualifiedErrorId : InvokeMethodOnNull

I've tried Power automate desktop Code

```<code>Display.SelectFileDialog.SelectFile Title: $'''Select file''' IsTopMost: False CheckIfFileExists: False SelectedFile=> SelectedFile ButtonPressed=> ButtonPressed
Scripting.RunPowershellScript Script: $'''#############################################
# Doc2PDF                                   #
# Created: April 30, 2016                   #
# Last Modified: June 16, 2016              #
# Version: 1.0                              #
# Supported Office: 2010*, 2013, 2016       #
# Supported PowerShell: 4, 5                #
# Copyright © 2016 Erick Scott Johnson      #
# All rights reserved.                      #
#############################################
#Input
$Input = $args[0]

#Define Office Formats
$Wrd_Array = \'*.docx\', \'*.doc\', \'*.odt\', \'*.rtf\', \'*.txt\', \'*.wpd\'
$Img_Array = \'*.png\', \'*.jpg\', \'*.bmp\'
$Off_Array = $Wrd_Array + $Img_Array
$ExtChk    = [System.IO.Path]::GetExtension($Input)

#Convert Image to PDF
Function Img-PDF($f, $p)
{
    $Wrd = New-Object -ComObject word.application
    $Wrd.Visible = $False
    $Version     = $Wrd.Version
    $Doc    = $Wrd.Documents.add()
    $objSelection  = $Wrd.Selection
    $ImageName =\'%SelectedFile.FullName%\'
    $ObjectSelection.InlineShapes.AddPicture($ImageName)

    If ($Version -eq \'16.0\' -Or $Version -eq \'15.0\') {
        $Doc.SaveAs($p, 17)
        $Doc.Close($False)
    }
    ElseIf ($Version -eq \'14.0\') {
        $Doc.SaveAs([ref] $p,[ref] 17)
        $Doc.Close([ref]$False)
    }
    [gc]::Collect()
    [gc]::WaitForPendingFinalizers()
    $Wrd.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Wrd)
    Remove-Variable Wrd
}

#Check for Image Formats
Function Img-Chk($f, $e, $p){
    $f = [string]$f
    For ($i = 0; $i -le $Img_Array.Length; $i++) {
        $Temp = [string]$Img_Array[$i]
        $Temp = $Temp.TrimStart(\'*\')
        If ($e -eq $Temp) {
            Img-PDF $f $p
        }
    }
}

#Check for Word Formats
Function Wrd-Chk($f, $e, $p){
    $f = [string]$f
    For ($i = 0; $i -le $Wrd_Array.Length; $i++) {
        $Temp = [string]$Wrd_Array[$i]
        $Temp = $Temp.TrimStart(\'*\')
        If ($e -eq $Temp) {
            Wrd-PDF $f $p
        }
    }
}

    $File     = \'%SelectedFile.fullname%\'
    $Path     = [System.IO.Path]::GetDirectoryName($File)
    $Filename = [System.IO.Path]::GetFileNameWithoutExtension($File)
    $Ext      = [System.IO.Path]::GetExtension($File)
    $PDF      = $Path + \'\\\' + $Filename + \'.pdf\'
    Wrd-Chk $File $Ext $PDF
    Img-Chk $File $Ext $PDF

#Cleanup
Remove-Item Function:Img-PDF, Function:Img-Chk
Remove-Item Function:Wrd-PDF, Function:Wrd-Chk
''' ScriptOutput=> PowerSheelOutput ScriptError=> ScriptError

</code>```

Body:
I'd like to make power automate desktop flow for making PDF from Image.
I can't find direct method from image to PDF, so, I tried to make new word document and insert image. After that I tried to convert document to PDF with below code. However it doesn't work.
Can you please advise what is wrong?

(Error)
You cannot call a method on a null-valued expression.
At C:\Users\m\AppData\Local\Temp\Robin\3q3a3wvbqx1.tmp.ps1:33 char:2

$ObjectSelection.InlineShapes.AddPicture($ImageName)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

CategoryInfo          : InvalidOperation: (:) [], RuntimeException

FullyQualifiedErrorId : InvokeMethodOnNull

I've tried Power automate desktop Code

Display.SelectFileDialog.SelectFile Title: $'''Select file''' IsTopMost: False CheckIfFileExists: False SelectedFile=> SelectedFile ButtonPressed=> ButtonPressed
Scripting.RunPowershellScript Script: $'''#############################################
# Doc2PDF                                   #
# Created: April 30, 2016                   #
# Last Modified: June 16, 2016              #
# Version: 1.0                              #
# Supported Office: 2010*, 2013, 2016       #
# Supported PowerShell: 4, 5                #
# Copyright © 2016 Erick Scott Johnson      #
# All rights reserved.                      #
#############################################
#Input
$Input = $args[0]

#Define Office Formats
$Wrd_Array = \'*.docx\', \'*.doc\', \'*.odt\', \'*.rtf\', \'*.txt\', \'*.wpd\'
$Img_Array = \'*.png\', \'*.jpg\', \'*.bmp\'
$Off_Array = $Wrd_Array + $Img_Array
$ExtChk    = [System.IO.Path]::GetExtension($Input)

#Convert Image to PDF
Function Img-PDF($f, $p)
{
    $Wrd = New-Object -ComObject word.application
    $Wrd.Visible = $False
    $Version     = $Wrd.Version
    $Doc    = $Wrd.Documents.add()
    $objSelection  = $Wrd.Selection
    $ImageName =\'%SelectedFile.FullName%\'
    $ObjectSelection.InlineShapes.AddPicture($ImageName)

    If ($Version -eq \'16.0\' -Or $Version -eq \'15.0\') {
        $Doc.SaveAs($p, 17)
        $Doc.Close($False)
    }
    ElseIf ($Version -eq \'14.0\') {
        $Doc.SaveAs([ref] $p,[ref] 17)
        $Doc.Close([ref]$False)
    }
    [gc]::Collect()
    [gc]::WaitForPendingFinalizers()
    $Wrd.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Wrd)
    Remove-Variable Wrd
}

#Check for Image Formats
Function Img-Chk($f, $e, $p){
    $f = [string]$f
    For ($i = 0; $i -le $Img_Array.Length; $i++) {
        $Temp = [string]$Img_Array[$i]
        $Temp = $Temp.TrimStart(\'*\')
        If ($e -eq $Temp) {
            Img-PDF $f $p
        }
    }
}

#Check for Word Formats
Function Wrd-Chk($f, $e, $p){
    $f = [string]$f
    For ($i = 0; $i -le $Wrd_Array.Length; $i++) {
        $Temp = [string]$Wrd_Array[$i]
        $Temp = $Temp.TrimStart(\'*\')
        If ($e -eq $Temp) {
            Wrd-PDF $f $p
        }
    }
}

    $File     = \'%SelectedFile.fullname%\'
    $Path     = [System.IO.Path]::GetDirectoryName($File)
    $Filename = [System.IO.Path]::GetFileNameWithoutExtension($File)
    $Ext      = [System.IO.Path]::GetExtension($File)
    $PDF      = $Path + \'\\\' + $Filename + \'.pdf\'
    Wrd-Chk $File $Ext $PDF
    Img-Chk $File $Ext $PDF

#Cleanup
Remove-Item Function:Img-PDF, Function:Img-Chk
Remove-Item Function:Wrd-PDF, Function:Wrd-Chk
''' ScriptOutput=> PowerSheelOutput ScriptError=> ScriptError


问:
shooting a projectile from a location to the mouse location
I have a project I have working on. I am trying to create a cannon that can shoot a cannonball. Now I have code that allows me to draw a ball will gravity and a floor where the cannonball bounces. I want to find a way to use the mouse to control exactly where the ball is being shot.

if someone could help me figure it out I would greatly appreciate it.
thanks

here is the js that I am working with

```<code>const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')

canvas.width = innerWidth
canvas.height = innerHeight

// const mouse = {
//   x: 0,
//   y: 0
// }
const mouse = {
x: innerWidth / 2,
y: innerHeight / 2
}
const center = {x: canvas.width / 2,
y: canvas.height / 2}

// Event Listeners
addEventListener('mousemove', (event) => {
mouse.x = event.clientX
mouse.y = event.clientY - canvas.height

angle = Math.atan2(mouse.y, mouse.x)

//let distBetween = function(p1, p2){
//return Math.sqrt(Math.pow((p2.x - p1.x), 2) + Math.pow((p2.y - p1.y), 2));
//}

//let angleBetween = function(p1, p2){
//return Math.atan2(p2.y - p1.y, p2.x - p1.x)
//}
//})

addEventListener('resize', () =\> {
canvas.width = innerWidth
canvas.height = innerHeight

init()
})
let angle = 0

// Objects
class Particle {
constructor(x, y, radius, color, distanceFromCenter) {
this.x = x
this.y = y
this.radius = radius
this.color = color
this.distanceFromCenter = distanceFromCenter
}

    draw() {
        c.beginPath()
        c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
        c.fillStyle = this.color
        c.fill()
        c.closePath()
    }

    update() {
        this.draw()
        this.x = (0) + (this.distanceFromCenter + 30) * Math.cos(angle)
        this.y = canvas.height + (this. distanceFromCenter +30) * Math.sin(angle)
    }

}
class Cannonball {
constructor(x, y, radius, color){
this.x = x
this.y = y
this.radius = radius
this.color = color
this.dx = Math.cos(angle) \* 2;
this.dy = Math.sin(angle) \* 2;
this.velocity = 2
this.gravity = 1
this.friction = -0.75
}
draw(){
c.beginPath()
c.arc(this.x, this.y, this.radius, 0, Math.PI \* 2, false)
c.fillStyle = 'blue'
c.fill()
c.closePath()
}

    update(){
        if (this.y + this.radius + 5 > canvas.height){
            this.velocity = -this.velocity * this.gravity
        } else {
          this.velocity += this.gravity
        }

        this.y += this.velocity
        this.velocity += this.friction
        this.draw()

    }

}

// let cannonball = new Cannonball(center.x, center.y, 30, 'blue')

// particle Implementation
let particleCount = 400
let particles;

// let cannonballCount = 400
let cannonballs;

function init() {
particles = \[\]
for (let i = 0; i \< particleCount; i++) {
const x = 0 + i \* Math.cos(1)
const y = canvas.height + this. distanceFromCenter \* Math.sin()
particles.push(new Particle(x, y, 30, 'red', i))
}

cannonballs = \[\]
}

// Animation Loop
function animate() {
requestAnimationFrame(animate)

    c.clearRect(0, 0, canvas.width, canvas.height)

    particles.forEach((particle) => {
        particle.update()
    })
    cannonballs.forEach(cannonball => {
        cannonball.update()
       })

}

init()
animate()

addEventListener('click', (event) =\> {
mouse.x = event.clientX
mouse.y = event.clientY

    cannonballs.push(new Cannonball(mouse.x, mouse.y, 30, 'blue',  {
        x: Math.cos(angleIncrement * i),
        y: Math.sin(angleIncrement * i)

    })

}
</code>```

Body:
I have a project I have working on. I am trying to create a cannon that can shoot a cannonball. Now I have code that allows me to draw a ball will gravity and a floor where the cannonball bounces. I want to find a way to use the mouse to control exactly where the ball is being shot.

if someone could help me figure it out I would greatly appreciate it.
thanks

here is the js that I am working with

const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')

canvas.width = innerWidth
canvas.height = innerHeight

// const mouse = {
//   x: 0,
//   y: 0
// }
const mouse = {
x: innerWidth / 2,
y: innerHeight / 2
}
const center = {x: canvas.width / 2,
y: canvas.height / 2}

// Event Listeners
addEventListener('mousemove', (event) => {
mouse.x = event.clientX
mouse.y = event.clientY - canvas.height

angle = Math.atan2(mouse.y, mouse.x)

//let distBetween = function(p1, p2){
//return Math.sqrt(Math.pow((p2.x - p1.x), 2) + Math.pow((p2.y - p1.y), 2));
//}

//let angleBetween = function(p1, p2){
//return Math.atan2(p2.y - p1.y, p2.x - p1.x)
//}
//})

addEventListener('resize', () =\> {
canvas.width = innerWidth
canvas.height = innerHeight

init()
})
let angle = 0

// Objects
class Particle {
constructor(x, y, radius, color, distanceFromCenter) {
this.x = x
this.y = y
this.radius = radius
this.color = color
this.distanceFromCenter = distanceFromCenter
}

    draw() {
        c.beginPath()
        c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
        c.fillStyle = this.color
        c.fill()
        c.closePath()
    }

    update() {
        this.draw()
        this.x = (0) + (this.distanceFromCenter + 30) * Math.cos(angle)
        this.y = canvas.height + (this. distanceFromCenter +30) * Math.sin(angle)
    }

}
class Cannonball {
constructor(x, y, radius, color){
this.x = x
this.y = y
this.radius = radius
this.color = color
this.dx = Math.cos(angle) \* 2;
this.dy = Math.sin(angle) \* 2;
this.velocity = 2
this.gravity = 1
this.friction = -0.75
}
draw(){
c.beginPath()
c.arc(this.x, this.y, this.radius, 0, Math.PI \* 2, false)
c.fillStyle = 'blue'
c.fill()
c.closePath()
}

    update(){
        if (this.y + this.radius + 5 > canvas.height){
            this.velocity = -this.velocity * this.gravity
        } else {
          this.velocity += this.gravity
        }

        this.y += this.velocity
        this.velocity += this.friction
        this.draw()

    }

}

// let cannonball = new Cannonball(center.x, center.y, 30, 'blue')

// particle Implementation
let particleCount = 400
let particles;

// let cannonballCount = 400
let cannonballs;

function init() {
particles = \[\]
for (let i = 0; i \< particleCount; i++) {
const x = 0 + i \* Math.cos(1)
const y = canvas.height + this. distanceFromCenter \* Math.sin()
particles.push(new Particle(x, y, 30, 'red', i))
}

cannonballs = \[\]
}

// Animation Loop
function animate() {
requestAnimationFrame(animate)

    c.clearRect(0, 0, canvas.width, canvas.height)

    particles.forEach((particle) => {
        particle.update()
    })
    cannonballs.forEach(cannonball => {
        cannonball.update()
       })

}

init()
animate()

addEventListener('click', (event) =\> {
mouse.x = event.clientX
mouse.y = event.clientY

    cannonballs.push(new Cannonball(mouse.x, mouse.y, 30, 'blue',  {
        x: Math.cos(angleIncrement * i),
        y: Math.sin(angleIncrement * i)

    })

}


问:
Accessing JSON attributes Object Header vs Expanded Form
Can anyone clarify why some JSON attributes are present in expanded form (when you expand the object or click the drop-down) but not in the header or collapsed versions?

I can only seem to access the ones in the header. I am wondering why, and furthermore, how to access the ones in expanded form if possible.

Thanks


问:
curl --verbose works but ordinary curl fails
I want to connect to an API inside a docker container.

curl --verbose https://api_url works, but curl https://api_url hangs and times out.

Also the end line of curl --verbose https://api_url gives me this message:

Connection #0 to host api.quran.com left intact

The URL I'm trying to connect to is https://api.quran.com/api/v3/chapters.

Other APIs works just fine inside the container. And I can also curl that API from my local machine (outside the container).

And inside the container, the fetch of Node.js fails too.

What can be the reason for this strange behavior?


问:
Ajax request did not redirect to login page in laravel 8 with jetstream
Normally all the page requests, when the session is expired, it gets redirected to the login page .But for an ajax request it is not redirected and it is failed. Yes ajax call will not refresh the page. And there are many ways with which the Auth can be checked and perform the redirection.Yet ,is there anything missing in my authentication setup of the jetstream to solve this? Or is there any solution to achieve the requirement in a more systematic way with jetstream ?


问:
links in a Flipping card only works in mozzila but not working in chrome and edge
I'm working on a project with flipping cards and all the links within the card are working in mozzilla, however when I open it in chrome, it is not working anymore. or not clickable.
enter image description here

codepen :
https://codepen.io/gcadigoy/pen/BaPWeKv

here's the sample code

```<code>.projects-section {
  @extend %container-shared;
  margin: 0 auto;
  padding: 2rem;
  height: 100%;
  h2 {
    font-size: 2rem;
    border-bottom: 5px solid $primary-color;
    margin: 5rem 0;
  }
  .project-list {
    max-width: 1159px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-evenly;
    align-content: space-between;
    color: $secondary-color;
    text-align: center;

    .flip-card {
      background-color: transparent;
      width: 300px;
      height: 300px;
      perspective: 1000px;
      margin: 2em;
    }

    .flip-card-inner {
      position: relative;
      width: 100%;
      height: 100%;
      text-align: center;
      transition: transform 0.6s;
      transform-style: preserve-3d;
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
      backface-visibility: hidden;
      -moz-backface-visibility: hidden;
      border: 1px solid teal;
      -webkit-transform-style: preserve-3d;
      transform-style: preserve-3d;
      pointer-events: none;
    }

    .flip-card:focus {
      outline: 0;
    }

    .flip-card:hover .flip-card-inner,
    .flip-card:focus .flip-card-inner {
      transform: rotateY(180deg);
    }

    .flip-card-front,
    .flip-card-back {
      position: absolute;
      width: 100%;
      height: 100%;
      pointer-events: auto;
    }

    .flip-card-front {
      background: linear-gradient(to left, #d8dceb, #dcdfe4);
      color: black;
      z-index: 2;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-direction: column;
      -webkit-transform: translateZ(1px);
      h3 {
        font-size: 1.5rem;
        font-weight: 700;
        flex: 1 0 auto;
        color: $primary-color;
        padding-top: 1.5em;
      }
      img {
        width: 100%;
      }
    }

    .flip-card-back {
      background: linear-gradient(to right, $secondary-color, $secondary-color);
      color: #535050;
      transform: rotateY(180deg);
      z-index: 1;
      display: flex;
      justify-content: space-evenly;
      flex-direction: column;
      padding: 1em;
      h3 {
        font-size: 1.5rem;
        font-weight: bold;
        border-bottom: 2px solid $primary-color;
        color: $primary-color;
        span {
          font-size: 0.7em;
        }
      }
      p {
        font-size: 0.9rem;
        color: #f19713;
      }
      span {
        a {
          color: $primary-color;

          i {
            margin: 0 1em;
            font-size: 1.5rem;
            color: $primary-color;
            &:hover {
              color: gray;
              transform: scale(1.5);
              pointer-events: auto;
            }
          }
        }
      }
    }
  }
  @media screen and (min-width: 768px) {
    & {
      h2 {
        font-size: 3.5rem;
      }
    }
    .project-list {
      flex-direction: row;
      figure {
        width: 100%;
      }
    }
  }
}
</code>```

I've been trying to find a solution on google and I was able to find some same scenario but still none of them works on my case.
here's sample code pen.

https://codepen.io/gcadigoy/pen/BaPWeKv

is Anybody has a workaround solution on this? please advise. Thank you

Body:
I'm working on a project with flipping cards and all the links within the card are working in mozzilla, however when I open it in chrome, it is not working anymore. or not clickable.
enter image description here

codepen :
https://codepen.io/gcadigoy/pen/BaPWeKv

here's the sample code

.projects-section {
  @extend %container-shared;
  margin: 0 auto;
  padding: 2rem;
  height: 100%;
  h2 {
    font-size: 2rem;
    border-bottom: 5px solid $primary-color;
    margin: 5rem 0;
  }
  .project-list {
    max-width: 1159px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-evenly;
    align-content: space-between;
    color: $secondary-color;
    text-align: center;

    .flip-card {
      background-color: transparent;
      width: 300px;
      height: 300px;
      perspective: 1000px;
      margin: 2em;
    }

    .flip-card-inner {
      position: relative;
      width: 100%;
      height: 100%;
      text-align: center;
      transition: transform 0.6s;
      transform-style: preserve-3d;
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
      backface-visibility: hidden;
      -moz-backface-visibility: hidden;
      border: 1px solid teal;
      -webkit-transform-style: preserve-3d;
      transform-style: preserve-3d;
      pointer-events: none;
    }

    .flip-card:focus {
      outline: 0;
    }

    .flip-card:hover .flip-card-inner,
    .flip-card:focus .flip-card-inner {
      transform: rotateY(180deg);
    }

    .flip-card-front,
    .flip-card-back {
      position: absolute;
      width: 100%;
      height: 100%;
      pointer-events: auto;
    }

    .flip-card-front {
      background: linear-gradient(to left, #d8dceb, #dcdfe4);
      color: black;
      z-index: 2;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-direction: column;
      -webkit-transform: translateZ(1px);
      h3 {
        font-size: 1.5rem;
        font-weight: 700;
        flex: 1 0 auto;
        color: $primary-color;
        padding-top: 1.5em;
      }
      img {
        width: 100%;
      }
    }

    .flip-card-back {
      background: linear-gradient(to right, $secondary-color, $secondary-color);
      color: #535050;
      transform: rotateY(180deg);
      z-index: 1;
      display: flex;
      justify-content: space-evenly;
      flex-direction: column;
      padding: 1em;
      h3 {
        font-size: 1.5rem;
        font-weight: bold;
        border-bottom: 2px solid $primary-color;
        color: $primary-color;
        span {
          font-size: 0.7em;
        }
      }
      p {
        font-size: 0.9rem;
        color: #f19713;
      }
      span {
        a {
          color: $primary-color;

          i {
            margin: 0 1em;
            font-size: 1.5rem;
            color: $primary-color;
            &:hover {
              color: gray;
              transform: scale(1.5);
              pointer-events: auto;
            }
          }
        }
      }
    }
  }
  @media screen and (min-width: 768px) {
    & {
      h2 {
        font-size: 3.5rem;
      }
    }
    .project-list {
      flex-direction: row;
      figure {
        width: 100%;
      }
    }
  }
}

I've been trying to find a solution on google and I was able to find some same scenario but still none of them works on my case.
here's sample code pen.

https://codepen.io/gcadigoy/pen/BaPWeKv

is Anybody has a workaround solution on this? please advise. Thank you


问:
Setting background color tk.Entry when in focus
New to Python / tkinter

Looking for a way if possible to set background colour of a tkinter Entry and Combobox widgets when they have focus.  Have done some digging and did find a styling option where you configure the widget with the focus event and tie background colour and another where you use an import module but neither worked for me.

Environment is Debian Linux and Python 3.9

Thanks in Advance !

widget.configure('focus', '#colour_hex') doesn't work.

An import module for styling but found out it would only work for Windows not Linux.


问:
Why don't my Wix forms work, and return a 504 error on form submission?
I've got a series of Wix forms on our site, and somehow in the last few weeks, since our last round of testing, all our forms have stopped working. When a user clicks "submit", the button goes grey (correct behaviour), then stays like that and doesn't return a success message, and doesn't log the entry into the submission database. I don't see any errors in the console, but when I check the Network tab, there's a POST request to /_api/wix-forms/v1/submit-form with a 504. I tried deleting the forms, and rebuilding from scratch, and had the same issue.

I modified all the settings in Wix that I could think of, and deleted the forms and built new ones, but still no luck.


问:
Recovering local files after Pycharm 'Undo Commit' Error
I feel a very unique and stupid scenario.

I work within a team using a shared Github repository, just for our SQL code for BAU tasks and the like as a way to save/share our work. I had been using Pycharm community version to push these files into the github repository. For a while I haven't been able to update the master branch due to an issue (now resolved) , meaning I had a few files sitting in the local pycharm folder in a pre commit stage.

I went to commit after updating my branch but the push would fail, seems a large file had been put in the wrong folder. I tried to delete the file from the local folder, create another commit and push, but same issue came up. So I undid the commits via Pycharm, thinking that would allow me to delete the large file and then just push one commit without the file.

In a stupid moment it was this time i chose to update Pycharm as my tech support team had told me too due to being on version 2021 not 2022. I deleted the 2021 version but kept the cache. I now find myself in a position with all my files that had been in the 'pre' commit stage deleted from my local, and Pycharm has no log history or change history of any of the commits failed pushes i tried this morning.

Does anyone know how I can recover my files?

I have tried to find the commit history or any way to find a cached or other version of the files


问:
Springboot generates jar packages, but wants to make the installation more convenient
Springboot generates jar packages, but wants to make the installation more convenient, so it needs to be packaged as an exe. but this does not know whether their own operation is standardized, or there is no other better way to package into executable programs.
The current method is to use exe4j to package jre and programs into exe, use Inno SetUp for step customization, etc.But not sure how packing works and want to find a better way.
The way l currently implement it is as shown.My records</p>


问:
$_SESSION array objects not mapping to class after PHP 8 upgrade
Our previous website was on PHP 7. As part of upgrading to PHP 8 we installed and configured php 8. No changes have been done to codebase yet. With the existing code, objects stored in $_SESSION doesn't seem to be mapped to the correct class.

Our code is similar to this:

require_once './vendor/autoload.php';
# more code
$_SESSION['user']->getPrivileges(); // this fails! This used to work in 7.0
```
<p>As a fix I added a new line above the last line above:</p>
<pre class="lang-php prettyprint-override"><code>require_once './vendor/autoload.php';
# more code
$_SESSION['user'] = unserialise(serialise($_SESSION->['user']));
$_SESSION['user']->getPrivileges(); // now this works
</code>```

But later going forward I found more instances and more objects stored in $_SESSION array that has similar issue.

Instead of unserialising and serialising for each item in the array, there must be some way of making sure the data in $_SESSION resolves to the correct classes.

I couldn't find anything in PHP documentation that suggests any difference in $_SESSION.

I found a similar issue (PHP 8 Session Problem with Object serialization) but the case isn't the same. I am not using any static variables.

Any help would be highly appreciated.

Body:
Our previous website was on PHP 7. As part of upgrading to PHP 8 we installed and configured php 8. No changes have been done to codebase yet. With the existing code, objects stored in $_SESSION doesn't seem to be mapped to the correct class.

Our code is similar to this:

require_once './vendor/autoload.php';
# more code
$_SESSION['user']->getPrivileges(); // this fails! This used to work in 7.0

As a fix I added a new line above the last line above:

require_once './vendor/autoload.php';
# more code
$_SESSION['user'] = unserialise(serialise($_SESSION->['user']));
$_SESSION['user']->getPrivileges(); // now this works

But later going forward I found more instances and more objects stored in $_SESSION array that has similar issue.

Instead of unserialising and serialising for each item in the array, there must be some way of making sure the data in $_SESSION resolves to the correct classes.

I couldn't find anything in PHP documentation that suggests any difference in $_SESSION.

I found a similar issue (PHP 8 Session Problem with Object serialization) but the case isn't the same. I am not using any static variables.

Any help would be highly appreciated.


问:
Stopping Jmeter slave servers
Stuck in TEST START

I was running my Jmeter test, but halfway through I forced stop the test in Master machine, now my slave servers are stuck in Test Start!
Please help, how do I ping the slave servers to force stop or restart?

I need the server to be able to be unstuck from TEST RUN mode

Title: Stopping Jmeter slave servers


问:
Need help defining key-value pairs in json schema
I have a json which have the key : value pairs which trying to convert to JSON schema. How can I have the values dynamically for both key:value? [ i.e: test, testa, testb, testc, testd - needs to be dynamic ]

```<code>{"test" : {"content":{"testa" : "testb","testc" : "testd"}}}
</code>```

Steps to reproduce the behavior

Sample Json

{"test" : {"content":{"testa" : "testb","testc" : "testd"}}}

I have converted the json to json schema with the help of below URL.
https://codebeautify.org/json-to-json-schema-generator

Once it's converted copied and updated the json schema on Online Json editor to show the Editor view.

https://json-editor.github.io/json-editor/?data=N4Ig9gDgLglmB2BnEAuUMDGCA2MBGqIAZglAIYDuApomALZUCsIANOHgFZUZQD62ZAJ5gArlELwwAJzplsrEIgwALKrNSgAJEtXqUIZVCgQUAelMda8ALQ61ZAHTSA5qYAmUskSjWADADZTO1kAYgVNKSoiQhD3KJh4GFgERFMAdSpsLAYAdgU3eMTkpA0QDKz6Kjy0EChBCCpCME5ucTYyNzckuHg5AAUpSCopWBpUIjlEKjYIQYaRmDGaqBpxGoiomLiiBO6U0wAVVZAAXxO2SIBHERhIt1QAbVrjgF02WChsRv1y7KrTthHRBrUB1BpNFo8BQdLrFfpzYajZAoCbYKYzBELJagLDwFZ40obaL6WIFHZFHqpADCpCoBLOFyo11uVHuKCeuPx4jetSSX0IQPE5xANLxdJBtXq33YXCh7U6e162AGQyxyNR6JAs1VSNKK2BZD1UsIwKkCWcAOewIwRvB+lN5tOwquNzujyt5AU+qgNp5H35+lFXKdwsQyjAFF4w0GUmRIASK08PB6Xt00rwYDAUFNZAgABYnUA==

If you noticed in below Updated Form, Test, testa and testc are fixed values which I'm trying to have those as dynamic values.

```<code>{
   "test": {
     "content": {
       "testa": "test",
       "testc": "test"
     }
   }
 }
</code>```

I have tried converting the json to json schema but I'm unable to add the "key":"value" dynamically, instead of that key was getting fixed value.

Body:
I have a json which have the key : value pairs which trying to convert to JSON schema. How can I have the values dynamically for both key:value? [ i.e: test, testa, testb, testc, testd - needs to be dynamic ]

{"test" : {"content":{"testa" : "testb","testc" : "testd"}}}

Steps to reproduce the behavior

Sample Json

{"test" : {"content":{"testa" : "testb","testc" : "testd"}}}

I have converted the json to json schema with the help of below URL.
https://codebeautify.org/json-to-json-schema-generator

Once it's converted copied and updated the json schema on Online Json editor to show the Editor view.

<a href="https://json-editor.github.io/json-editor/?data=N4Ig9gDgLglmB2BnEAuUMDGCA2MBGqIAZglAIYDuApomALZUCsIANOHgFZUZQD62ZAJ5gArlELwwAJzplsrEIgwALKrNSgAJEtXqUIZVCgQUAelMda8ALQ61ZAHTSA5qYAmUskSjWADADZTO1kAYgVNKSoiQhD3KJh4GFgERFMAdSpsLAYAdgU3eMTkpA0QDKz6Kjy0EChBCCpCME5ucTYyNzckuHg5AAUpSCopWBpUIjlEKjYIQYaRmDGaqBpxGoiomLiiBO6U0wAVVZAAXxO2SIBHERhIt1QAbVrjgF02WChsRv1y7KrTthHRBrUB1BpNFo8BQdLrFfpzYajZAoCbYKYzBELJagLDwFZ40obaL6WIFHZFHqpADCpCoBLOFyo11uVHuKCeuPx4jetSSX0IQPE5xANLxdJBtXq33YXCh7U6e162AGQyxyNR6JAs1VSNKK2BZD1UsIwKkCWcAOewIwRvB+lN5tOwquNzujyt5AU+qgNp5H35+lFXKdwsQyjAFF4w0GUmRIASK08PB6Xt00rwYDAUFNZAgABYnUA==" rel="nofollow noreferrer">https://json-editor.github.io/json-editor/?data=N4Ig9gDgLglmB2BnEAuUMDGCA2MBGqIAZglAIYDuApomALZUCsIANOHgFZUZQD62ZAJ5gArlELwwAJzplsrEIgwALKrNSgAJEtXqUIZVCgQUAelMda8ALQ61ZAHTSA5qYAmUskSjWADADZTO1kAYgVNKSoiQhD3KJh4GFgERFMAdSpsLAYAdgU3eMTkpA0QDKz6Kjy0EChBCCpCME5ucTYyNzckuHg5AAUpSCopWBpUIjlEKjYIQYaRmDGaqBpxGoiomLiiBO6U0wAVVZAAXxO2SIBHERhIt1QAbVrjgF02WChsRv1y7KrTthHRBrUB1BpNFo8BQdLrFfpzYajZAoCbYKYzBELJagLDwFZ40obaL6WIFHZFHqpADCpCoBLOFyo11uVHuKCeuPx4jetSSX0IQPE5xANLxdJBtXq33YXCh7U6e162AGQyxyNR6JAs1VSNKK2BZD1UsIwKkCWcAOewIwRvB+lN5tOwquNzujyt5AU+qgNp5H35+lFXKdwsQyjAFF4w0GUmRIASK08PB6Xt00rwYDAUFNZAgABYnUA==

If you noticed in below Updated Form, Test, testa and testc are fixed values which I'm trying to have those as dynamic values.

{
   "test": {
     "content": {
       "testa": "test",
       "testc": "test"
     }
   }
 }

I have tried converting the json to json schema but I'm unable to add the "key":"value" dynamically, instead of that key was getting fixed value.


问:
Google CAPTCHA not fully showing
I am trying to embed a Google drive video and it did success but most of the time it says unusual traffic please verify your are human but the image and submit button is not showing. Evan in tablet view it doesn't shows properly. Please help me how can I fix this

Please help me how can I make CAPTCHA show

Title: Google CAPTCHA not fully showing


问:
Why am I getting an automatic \n whenever I print this?

#include<stdio.h>

int main(){

    int score[1001], j, n = 3;
    char name[4][11];

    for(j = 0; j < n; j++){

            scanf("%[^#]#%d", name[j], &score[j]);

        }

    for(j = 0; j < n; j++){

            printf("%s %d", name[j], score[j]);

        }
}
```

I dont know why it automatically adds a \n when I print it. I expected it to just take the string that I inputted and nothing more. An example of an input is "Jojo#40" where Jojo would be taken as string and 40 as int. Is there a way to fix this or a better way to take those inputs?

Body:
#include<stdio.h>

int main(){

    int score[1001], j, n = 3;
    char name[4][11];

    for(j = 0; j < n; j++){

            scanf("%[^#]#%d", name[j], &score[j]);

        }

    for(j = 0; j < n; j++){

            printf("%s %d", name[j], score[j]);

        }
}

I dont know why it automatically adds a \n when I print it. I expected it to just take the string that I inputted and nothing more. An example of an input is "Jojo#40" where Jojo would be taken as string and 40 as int. Is there a way to fix this or a better way to take those inputs?


问:
why std::vector cannot hold components has constant/volatile or reference objects?
As this answer said:

The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector is not allowed.

```<code>class test {
public:
  test(test &) = delete;
  test &operator=(test &) = delete;
};

int main() {
  std::vector<test> vec;
}
</code>```

class test is not assignable but this could compile.

Other answer like std::vector<T, std::allocator>'s allocator limitation, why those two static_assert was wrote in vector but not allocator ? Is this the real reason that limited the component type?

```<code>  template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
    class vector : protected _Vector_base<_Tp, _Alloc>
    {
#if __cplusplus >= 201103L
      static_assert(is_same<typename remove_cv<_Tp>::type, _Tp>::value,
      "std::vector must have a non-const, non-volatile value_type");
# ifdef __STRICT_ANSI__
      static_assert(is_same<typename _Alloc::value_type, _Tp>::value,
      "std::vector must have the same value_type as its allocator");
# endif
#endif
</code>```

Why volatile is so special that cannot use as vector's component qualifier?

Just expecting to know why, not the solution to bypass this.

Body:
As this answer said:

The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector is not allowed.

class test {
public:
  test(test &) = delete;
  test &operator=(test &) = delete;
};

int main() {
  std::vector<test> vec;
}

class test is not assignable but this could compile.

Other answer like std::vector<T, std::allocator>'s allocator limitation, why those two static_assert was wrote in vector but not allocator ? Is this the real reason that limited the component type?

  template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
    class vector : protected _Vector_base<_Tp, _Alloc>
    {
#if __cplusplus >= 201103L
      static_assert(is_same<typename remove_cv<_Tp>::type, _Tp>::value,
      "std::vector must have a non-const, non-volatile value_type");
# ifdef __STRICT_ANSI__
      static_assert(is_same<typename _Alloc::value_type, _Tp>::value,
      "std::vector must have the same value_type as its allocator");
# endif
#endif

Why volatile is so special that cannot use as vector's component qualifier?

Just expecting to know why, not the solution to bypass this.


问:
How to customize font type/size for Rmarkdown table output to PPT?
I am kniting my Rmd to PPT using a custom PPT template with different types of slides. I have all headers/text set to Alright Sans Font, mostly size 11.

When I knit to PPT, that all works except the table ouput is calibri and way too large of font. How can i customize?

How do I reduce vertical spacing between numbered/bulleted lists?

I think this might need to happen in the PPT template but not sure.


问:
Windows thread local storage bug
In Windows, a segment error occurs when an executable file accesses a thread local variable in the dynamic library in extern mode.This problem occurs when clang is used, but not when gcc is used.

```<code>// test.c
__thread int g_cnt = 1;
</code>```

Compile the dynamic library:

clang --target=x86_64-pc-windows-gnu test.c -shared -o libtest.dll

```<code>// main.c
#include <stdio.h>

extern __thread int g_cnt;

int get_cnt()
{
    return g_cnt;
}

int main() {
    int cnt = get_cnt();
    printf("cnt = %d\n", cnt);

    return 0;
}
</code>```

Generating an Executable File:

clang --target=x86_64-pc-windows-gnu main.c -L.\ -ltest -o main.exe

Segment error while accessing thread local variables

```<code>Thread 1 received signal SIGSEGV, Segmentation fault.
0x00007ff6bf5717e5 in get_cnt ()
(gdb) disassemble
Dump of assembler code for function get_cnt:
   0x00007ff6bf5717d0 <+0>:     mov    0xe8ea(%rip),%eax        # 0x7ff6bf5800c0 <_tls_index>
   0x00007ff6bf5717d6 <+6>:     mov    %eax,%ecx
   0x00007ff6bf5717d8 <+8>:     mov    %gs:0x58,%rax
   0x00007ff6bf5717e1 <+17>:    mov    (%rax,%rcx,8),%rax
=> 0x00007ff6bf5717e5 <+21>:    mov    0x7f5782f0(%rax),%eax
   0x00007ff6bf5717eb <+27>:    ret
   0x00007ff6bf5717ec <+28>:    nopl   0x0(%rax)
End of assembler dump.
(gdb) p *0x7ff6bf5800c0
$1 = 0
</code>```

Is this a clang bug?

The version of clang I tested was 12.0.1

Mingw uses x86_64-posix-seh-gcc-12.1.0-mingw-w64msvcrt-10.0.0.

Title: Windows thread local storage bug

Body:
In Windows, a segment error occurs when an executable file accesses a thread local variable in the dynamic library in extern mode.This problem occurs when clang is used, but not when gcc is used.

// test.c
__thread int g_cnt = 1;

Compile the dynamic library:

clang --target=x86_64-pc-windows-gnu test.c -shared -o libtest.dll

// main.c
#include <stdio.h>

extern __thread int g_cnt;

int get_cnt()
{
    return g_cnt;
}

int main() {
    int cnt = get_cnt();
    printf("cnt = %d\n", cnt);

    return 0;
}

Generating an Executable File:

clang --target=x86_64-pc-windows-gnu main.c -L.\ -ltest -o main.exe

Segment error while accessing thread local variables

Thread 1 received signal SIGSEGV, Segmentation fault.
0x00007ff6bf5717e5 in get_cnt ()
(gdb) disassemble
Dump of assembler code for function get_cnt:
   0x00007ff6bf5717d0 <+0>:     mov    0xe8ea(%rip),%eax        # 0x7ff6bf5800c0 <_tls_index>
   0x00007ff6bf5717d6 <+6>:     mov    %eax,%ecx
   0x00007ff6bf5717d8 <+8>:     mov    %gs:0x58,%rax
   0x00007ff6bf5717e1 <+17>:    mov    (%rax,%rcx,8),%rax
=> 0x00007ff6bf5717e5 <+21>:    mov    0x7f5782f0(%rax),%eax
   0x00007ff6bf5717eb <+27>:    ret
   0x00007ff6bf5717ec <+28>:    nopl   0x0(%rax)
End of assembler dump.
(gdb) p *0x7ff6bf5800c0
$1 = 0

Is this a clang bug?

The version of clang I tested was 12.0.1

Mingw uses x86_64-posix-seh-gcc-12.1.0-mingw-w64msvcrt-10.0.0.


问:
Powershell CSV to Excel in UTF-8
Editing the question with new findings.

SQL query results saved in to CSV. This CSV perfectly maintains special characters

CSV to Excel. Excel doesn't maintain special characters when opened via Excel app by double clicking the file

Excel does work perfectly maintaining special characters by opening a fresh Excel app and then browsing the above mentioned excel file using 'Data'->'From Text'

I'm exporting SQL results to a temporary CSV file which contains special characters. CSV file is created with no issues still maintaining special characters due to the use of UTF-8 format.

However when I try to create an excel workbook with the contents of CSV it messes up the special characters. How can I maintain UTF-8 format when creating the excel workbook?

```<code>$sqlresults  = Invoke-Sqlcmd -serverinstance $AppServerInstance -Database $databaseName -ApplicationIntent "ReadOnly" -Credential $Cred -InputFile $inputFile -Variable $dateValues -Verbose
$sqlresults | Export-Csv -path $temporaryCsvFile -Encoding UTF8 -noTypeInformation # Export to CSV temporarily

$excelObject = New-Object -comObject Excel.Application
$excelObject.Visible = $false

$workbookObject = $excelObject.Workbooks.Open($temporaryCsvFile)
</code>```

Title: Powershell CSV to Excel in UTF-8

Body:
Editing the question with new findings.

SQL query results saved in to CSV. This CSV perfectly maintains special characters

CSV to Excel. Excel doesn't maintain special characters when opened via Excel app by double clicking the file

Excel does work perfectly maintaining special characters by opening a fresh Excel app and then browsing the above mentioned excel file using 'Data'->'From Text'

I'm exporting SQL results to a temporary CSV file which contains special characters. CSV file is created with no issues still maintaining special characters due to the use of UTF-8 format.

However when I try to create an excel workbook with the contents of CSV it messes up the special characters. How can I maintain UTF-8 format when creating the excel workbook?

$sqlresults  = Invoke-Sqlcmd -serverinstance $AppServerInstance -Database $databaseName -ApplicationIntent "ReadOnly" -Credential $Cred -InputFile $inputFile -Variable $dateValues -Verbose
$sqlresults | Export-Csv -path $temporaryCsvFile -Encoding UTF8 -noTypeInformation # Export to CSV temporarily

$excelObject = New-Object -comObject Excel.Application
$excelObject.Visible = $false

$workbookObject = $excelObject.Workbooks.Open($temporaryCsvFile)


问:
Array Formula for a specific cell range that is expanding to an unknown length
I'm trying to perform an ARRAYFORMULA starting from a specific cell (K10 - first row of a specific section shown in green in the image) to an unknown end.  I basically have the ability to keep adding rows of data in this section so it could end at K15 or K300, it's an unknown quantity.

Also, the section below it needs the same treatment (shown in red in the image), but its starting cell will also change dynamically due to the above.