问:
Problems with Clone gameObject in Unity 2D
Im trying to make collision work for the GameObject Clone, but is not working

The newWaterBottle i wanted to collide with player same as the original WaterBottlePrefab, but is not working, newWaterBottle is spawning perfect but collision not work

Game Files

Here is the Code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;

public class GameManager : MonoBehaviour
{
public Image healthBar;
public float healthAmount = 100f;
// get WaterBottle game Tag
public GameObject waterBottlePrefab;
// get player game Tag
public GameObject player;

public GameObject scoreText;

int score = 0;

TextMeshProUGUI scoreText_test;
// Start is called before the first frame update
void Start()
{
    scoreText_test=scoreText.GetComponent<TextMeshProUGUI>();
    StartCoroutine(SpawnWaterBottles());
}

// Update is called once per frame
void Update()
{

    if (healthAmount <= 0){
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }

    // if player detect collision with waterBottle display in console "You drink water"
    if (player.GetComponent<Collider2D>().IsTouching(waterBottlePrefab.GetComponent<Collider2D>()))
    {
        score += 1;
        Debug.Log("You drink water");
        Heal();

        // set active false the waterBottle
        waterBottlePrefab.SetActive(false);
    }
    else
    {
        // From the begin of the game, the player will be take automatically 1 damage per second
        TakeDamge(5f * Time.deltaTime);
    }

    scoreText_test.SetText(score.ToString());
}

IEnumerator SpawnWaterBottles()
{
    while (true)
    {
        // Wait for a random interval of time between 10 and 20 seconds
        yield return new WaitForSeconds(Random.Range(5, 15));

        // Spawn a new water bottle at a random distance between 30 and 40 meters in front of the player
        Vector3 spawnPos = player.transform.position + (player.transform.forward * Random.Range(30f, 40f) + new Vector3(40f, 2f, 0));
        GameObject newWaterBottle = Instantiate(waterBottlePrefab, spawnPos, Quaternion.identity);
        newWaterBottle.SetActive(true);

    scoreText_test.SetText(score.ToString());

    // Player colision with newWaterBottle
    if (player.GetComponent<Collider2D>().IsTouching(newWaterBottle.GetComponent<Collider2D>()))
    {
        score += 1;
        Debug.Log("You drink waterson");
        Heal();

        // set active false the waterBottle
        newWaterBottle.SetActive(false);
    }
    else
    {
        // From the begin of the game, the player will be take automatically 1 damage per second
        TakeDamge(5f * Time.deltaTime);
    }
}
}

// Coroutine to spawn water bottles along the road at ground level
    // Method to heal the player
void Heal()
{
    // Increase the health amount by 10
    healthAmount += 100;

    // Clamp the health amount to 100
    healthAmount = Mathf.Clamp(healthAmount, 0, 100);

    // Update the health bar UI
    healthBar.fillAmount = healthAmount / 100f;
}

// Method to take damage from the player
void TakeDamge(float amount)
{
    // Decrease the health amount by the amount passed in
    healthAmount -= amount;

    // Clamp the health amount to 100
    healthAmount = Mathf.Clamp(healthAmount, 0, 100);

    // Update the health bar UI
    healthBar.fillAmount = healthAmount / 100f;
}
}

</code>```

This is The part where "clone collision hapen"

```<code>if (player.GetComponent<Collider2D>().IsTouching(newWaterBottle.GetComponent<Collider2D>()))
{
    score += 1;
    Debug.Log("You drink waterson");
    Heal();

    // set active false the waterBottle
    newWaterBottle.SetActive(false);
}
else
{
    // From the begin of the game, the player will be take automatically 1 damage per second
    TakeDamge(5f * Time.deltaTime);
}
</code>```

I tried with Debug.Log() I thoutht it will be the problem with set active or score but no.

Body:
Im trying to make collision work for the GameObject Clone, but is not working

The newWaterBottle i wanted to collide with player same as the original WaterBottlePrefab, but is not working, newWaterBottle is spawning perfect but collision not work

Game Files

Here is the Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;

public class GameManager : MonoBehaviour
{
public Image healthBar;
public float healthAmount = 100f;
// get WaterBottle game Tag
public GameObject waterBottlePrefab;
// get player game Tag
public GameObject player;

public GameObject scoreText;

int score = 0;

TextMeshProUGUI scoreText_test;
// Start is called before the first frame update
void Start()
{
    scoreText_test=scoreText.GetComponent<TextMeshProUGUI>();
    StartCoroutine(SpawnWaterBottles());
}

// Update is called once per frame
void Update()
{

    if (healthAmount <= 0){
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }

    // if player detect collision with waterBottle display in console "You drink water"
    if (player.GetComponent<Collider2D>().IsTouching(waterBottlePrefab.GetComponent<Collider2D>()))
    {
        score += 1;
        Debug.Log("You drink water");
        Heal();

        // set active false the waterBottle
        waterBottlePrefab.SetActive(false);
    }
    else
    {
        // From the begin of the game, the player will be take automatically 1 damage per second
        TakeDamge(5f * Time.deltaTime);
    }

    scoreText_test.SetText(score.ToString());
}

IEnumerator SpawnWaterBottles()
{
    while (true)
    {
        // Wait for a random interval of time between 10 and 20 seconds
        yield return new WaitForSeconds(Random.Range(5, 15));

        // Spawn a new water bottle at a random distance between 30 and 40 meters in front of the player
        Vector3 spawnPos = player.transform.position + (player.transform.forward * Random.Range(30f, 40f) + new Vector3(40f, 2f, 0));
        GameObject newWaterBottle = Instantiate(waterBottlePrefab, spawnPos, Quaternion.identity);
        newWaterBottle.SetActive(true);

    scoreText_test.SetText(score.ToString());

    // Player colision with newWaterBottle
    if (player.GetComponent<Collider2D>().IsTouching(newWaterBottle.GetComponent<Collider2D>()))
    {
        score += 1;
        Debug.Log("You drink waterson");
        Heal();

        // set active false the waterBottle
        newWaterBottle.SetActive(false);
    }
    else
    {
        // From the begin of the game, the player will be take automatically 1 damage per second
        TakeDamge(5f * Time.deltaTime);
    }
}
}

// Coroutine to spawn water bottles along the road at ground level
    // Method to heal the player
void Heal()
{
    // Increase the health amount by 10
    healthAmount += 100;

    // Clamp the health amount to 100
    healthAmount = Mathf.Clamp(healthAmount, 0, 100);

    // Update the health bar UI
    healthBar.fillAmount = healthAmount / 100f;
}

// Method to take damage from the player
void TakeDamge(float amount)
{
    // Decrease the health amount by the amount passed in
    healthAmount -= amount;

    // Clamp the health amount to 100
    healthAmount = Mathf.Clamp(healthAmount, 0, 100);

    // Update the health bar UI
    healthBar.fillAmount = healthAmount / 100f;
}
}

This is The part where "clone collision hapen"

if (player.GetComponent<Collider2D>().IsTouching(newWaterBottle.GetComponent<Collider2D>()))
{
    score += 1;
    Debug.Log("You drink waterson");
    Heal();

    // set active false the waterBottle
    newWaterBottle.SetActive(false);
}
else
{
    // From the begin of the game, the player will be take automatically 1 damage per second
    TakeDamge(5f * Time.deltaTime);
}

I tried with Debug.Log() I thoutht it will be the problem with set active or score but no.


来源: stackexchange

问:
Issues with Compose Recomposition
i'm trying to use multiple screens in my app. I've defined navhost with routes. To cut long story short, my app goes from splash screen to Tasks screen which has just one text label and one button. Clicking button is supposed to update the text but its not. Following is the code for the TaskScreen.kt:

```<code>@Composable
fun TasksScreen(
    modifier: Modifier = Modifier,
    viewModel: TasksViewModel
) {
    var countClicks by remember{ mutableStateOf(0) }
    Column(){
        Text(
            text = "Task: ${countClicks}",
        )
        Button(onClick = {
            countClicks++
            Log.d("TAG", "TasksScreen() --> $countClicks")
        }) {
            Text("Click Me: $countClicks")
        }
    }
}
</code>```

In the layout inspector I see that both the button and the text are being recomposed, but they don't actually updated the value:

Logcat window shows the countClicks being correctly updated too:

```<code>D  TasksScreen() --> 1
D  TasksScreen() --> 2
D  TasksScreen() --> 3
D  TasksScreen() --> 4
</code>```

Really confused why this isn't working properly.

ContentLicense: CC BY-SA 4.0

Title: Issues with Compose Recomposition

Body:
i'm trying to use multiple screens in my app. I've defined navhost with routes. To cut long story short, my app goes from splash screen to Tasks screen which has just one text label and one button. Clicking button is supposed to update the text but its not. Following is the code for the TaskScreen.kt:

@Composable
fun TasksScreen(
    modifier: Modifier = Modifier,
    viewModel: TasksViewModel
) {
    var countClicks by remember{ mutableStateOf(0) }
    Column(){
        Text(
            text = "Task: ${countClicks}",
        )
        Button(onClick = {
            countClicks++
            Log.d("TAG", "TasksScreen() --> $countClicks")
        }) {
            Text("Click Me: $countClicks")
        }
    }
}

In the layout inspector I see that both the button and the text are being recomposed, but they don't actually updated the value:

Logcat window shows the countClicks being correctly updated too:

D  TasksScreen() --> 1
D  TasksScreen() --> 2
D  TasksScreen() --> 3
D  TasksScreen() --> 4

Really confused why this isn't working properly.


问:
Getting current location in a Broadcast receiver- Android
My goal is to get a single pair of coordinates upon a received broadcast. What I've done so far is the following:

```<code> @Override
public void onReceive(Context context, Intent intent) {
        // API 31 and above
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            locationManager.getCurrentLocation(LocationManager.FUSED_PROVIDER, null, context.getMainExecutor(), new Consumer<Location>() {
                @Override
                public void accept(Location location) {
                    if(location == null)
                        return;

                    MyObject myObject = new MyObject(location.getLatitude(), location.getLongitude());
                }
            });
        }

        // Legacy (API < 31)
        else{
            Criteria locationCriteria = new Criteria();
            locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
            locationManager.requestSingleUpdate(locationCriteria, new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    MyObject myObject = new MyObject(location.getLatitude(), location.getLongitude());
                }

                @Override
                public void onProviderEnabled(@NonNull String provider) {
                    Log.d("SmsHandler", "PROVIDER ENABLED");
                }

                @Override
                public void onProviderDisabled(@NonNull String provider) {
                    Log.d("SmsHandler", "PROVIDER DISABLED");
                }
            }, null);
        }
}
</code>```

but it seems unstable. Should I use Services or something similar? Might I ask you why? I've read from the official documentation:

If this BroadcastReceiver was launched through a  tag, then the object is no longer alive after returning from this function. This means you should not perform any operations that return a result to you asynchronously.

is that why? But to be honest I do not well understand what is being said very well (not so experienced with Android yet).

Furthermore, during some tests, if the user toggles the location just a second before the execution of the code above, neither getCurrentLocation() nor onLocationChanged() get fired, but, the next time the broadcast triggers onReceive(), getCurrentLocation() or onLocationChanged() get executed twice (like it remembers it did not execute the last time).

Might you be so kind to help me? Thank you.

Body:
My goal is to get a single pair of coordinates upon a received broadcast. What I've done so far is the following:

 @Override
public void onReceive(Context context, Intent intent) {
        // API 31 and above
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            locationManager.getCurrentLocation(LocationManager.FUSED_PROVIDER, null, context.getMainExecutor(), new Consumer<Location>() {
                @Override
                public void accept(Location location) {
                    if(location == null)
                        return;

                    MyObject myObject = new MyObject(location.getLatitude(), location.getLongitude());
                }
            });
        }

        // Legacy (API < 31)
        else{
            Criteria locationCriteria = new Criteria();
            locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
            locationManager.requestSingleUpdate(locationCriteria, new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    MyObject myObject = new MyObject(location.getLatitude(), location.getLongitude());
                }

                @Override
                public void onProviderEnabled(@NonNull String provider) {
                    Log.d("SmsHandler", "PROVIDER ENABLED");
                }

                @Override
                public void onProviderDisabled(@NonNull String provider) {
                    Log.d("SmsHandler", "PROVIDER DISABLED");
                }
            }, null);
        }
}

but it seems unstable. Should I use Services or something similar? Might I ask you why? I've read from the official documentation:

If this BroadcastReceiver was launched through a  tag, then the object is no longer alive after returning from this function. This means you should not perform any operations that return a result to you asynchronously.

is that why? But to be honest I do not well understand what is being said very well (not so experienced with Android yet).

Furthermore, during some tests, if the user toggles the location just a second before the execution of the code above, neither getCurrentLocation() nor onLocationChanged() get fired, but, the next time the broadcast triggers onReceive(), getCurrentLocation() or onLocationChanged() get executed twice (like it remembers it did not execute the last time).

Might you be so kind to help me? Thank you.


问:
when i clicked on add to cart button it first check "is user login??" then execute jquery
when i clicked on Add to cart button , it first chek that user login or not if login then continue otherwise redirect to login page

```<code>$('.divpr').on('click', 'button.cart' ,function () {
    var idstr = this.id.toString();

    if (cart[idstr] != undefined) {
      console.log("exist");
      cart[idstr][0] = cart[idstr][0] + 1;
      cart[idstr][4]=cart[idstr][4]+cart[idstr][3]
      localStorage.setItem('cart', JSON.stringify(cart));

    } else {
      qty = 1;

     price = document.getElementById('price' + idstr).innerHTML;
      totalPrice=document.getElementById('price' + idstr).innerHTML;
      image = document.getElementById('img' + idstr).src;
      aname = document.getElementById('name' + idstr).innerHTML;
      console.log("not");
      cart[idstr] = [qty, aname, image, parseInt(price),parseInt(totalPrice)];
    }

    localStorage.setItem('cart', JSON.stringify(cart));

    console.log(cart)
  });
</code>```

it add item to cart even i am not login

i want it redirect when i am not loggedin

Body:
when i clicked on Add to cart button , it first chek that user login or not if login then continue otherwise redirect to login page

$('.divpr').on('click', 'button.cart' ,function () {
    var idstr = this.id.toString();

    if (cart[idstr] != undefined) {
      console.log("exist");
      cart[idstr][0] = cart[idstr][0] + 1;
      cart[idstr][4]=cart[idstr][4]+cart[idstr][3]
      localStorage.setItem('cart', JSON.stringify(cart));

    } else {
      qty = 1;

     price = document.getElementById('price' + idstr).innerHTML;
      totalPrice=document.getElementById('price' + idstr).innerHTML;
      image = document.getElementById('img' + idstr).src;
      aname = document.getElementById('name' + idstr).innerHTML;
      console.log("not");
      cart[idstr] = [qty, aname, image, parseInt(price),parseInt(totalPrice)];
    }

    localStorage.setItem('cart', JSON.stringify(cart));

    console.log(cart)
  });

it add item to cart even i am not login

i want it redirect when i am not loggedin


问:
How to use the execute option in searchkick 5.1.0?
My code

Hi all, this code is not working for me. I only need a request

i tried
User.search("*", execute: false)
User.search("*", load: false)


问:
How to update Flask SQLAlchemy binds?
Is it possible to update SQLALCHEMY_BINDS after they have been used by SQLAlchemy initialization?

Details:

I have a Flask app that serves as the AI player replacement in a boardgame. It uses a main database with users and one separate database per user - each user has his own database that holds the game options, game progress, tech levels etc. all spread into several tables. I need to bind the user database file corresponding to a logged user.

The Flask app reads the SQLAlchemy variables by importing a Config class. The SQLALCHEMY_BINDS is an empty dict as the app doesn´t know which user will log in (=which user database file is going to be used):

```<code>class Config:
    SQLALCHEMY_DATABASE_URI =  <path to main db>
    SQLALCHEMY_BINDS = {}
    ...
</code>```

Then the app factory creates the app and the db gets initialized:

```<code>...
db = SQLAlchemy()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    db.init_app(app)
    ...
</code>```

The User model (main database with users) and e.g. Game model (binded database) are like:

```<code>class User(UserMixin, db.Model):
    ... variables assignments...

class Game(UserMixin, db.Model):
    __bind_key__ = "user_db"
    ... variables assignments ...

... more classes binded to user_db ...
</code>```

The Flask app starts up with the class´ Game __bind_key__ = "user_db" despite the fact the SQLALCHEMY_BINDS variable is an empty dict. When I preset SQLALCHEMY_BINDS = {"user_db": None} the flask app raises an exception because of the NoneType.

I can´t figure out how to bind the right user_db database to the user who has just logged in. In other words how to update the SQLALCHEMY_BINDS after a successfull user login. I can have many user databases but I need to work with the right one corresponding to the logged user.

I have tried:

creating secondary SQLAlchemy instance to work separately - one for User and the other for UserDB, not working.

creating a new dict with key-value pair but was unable to figure out how to load it using flask´s current_app.config.fromkeys method.

creating a new file with SQLALCHEMY_BINDS every time a user logs in and loading it by current_app.config.fromfile is weird if possible at all.

I have searched the already answered questions but haven´t found a similar one.
Is the binds updating possible at all?

Title: How to update Flask SQLAlchemy binds?

Body:
Is it possible to update SQLALCHEMY_BINDS after they have been used by SQLAlchemy initialization?

Details:

I have a Flask app that serves as the AI player replacement in a boardgame. It uses a main database with users and one separate database per user - each user has his own database that holds the game options, game progress, tech levels etc. all spread into several tables. I need to bind the user database file corresponding to a logged user.

The Flask app reads the SQLAlchemy variables by importing a Config class. The SQLALCHEMY_BINDS is an empty dict as the app doesn´t know which user will log in (=which user database file is going to be used):

class Config:
    SQLALCHEMY_DATABASE_URI =  <path to main db>
    SQLALCHEMY_BINDS = {}
    ...

Then the app factory creates the app and the db gets initialized:

...
db = SQLAlchemy()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    db.init_app(app)
    ...

The User model (main database with users) and e.g. Game model (binded database) are like:

class User(UserMixin, db.Model):
    ... variables assignments...

class Game(UserMixin, db.Model):
    __bind_key__ = "user_db"
    ... variables assignments ...

... more classes binded to user_db ...

The Flask app starts up with the class´ Game __bind_key__ = "user_db" despite the fact the SQLALCHEMY_BINDS variable is an empty dict. When I preset SQLALCHEMY_BINDS = {"user_db": None} the flask app raises an exception because of the NoneType.

I can´t figure out how to bind the right user_db database to the user who has just logged in. In other words how to update the SQLALCHEMY_BINDS after a successfull user login. I can have many user databases but I need to work with the right one corresponding to the logged user.

I have tried:

creating secondary SQLAlchemy instance to work separately - one for User and the other for UserDB, not working.

creating a new dict with key-value pair but was unable to figure out how to load it using flask´s current_app.config.fromkeys method.

creating a new file with SQLALCHEMY_BINDS every time a user logs in and loading it by current_app.config.fromfile is weird if possible at all.

I have searched the already answered questions but haven´t found a similar one.
Is the binds updating possible at all?


问:
Sympy : issue in Differentiation of function
the aim of this script is to obtain the standard deviation of the wind direction using U, V wind speed components and their respective standard wind speed deviation (std_u, std_v).

```<code>
from sympy import *
import numpy as np

# wind direction calculation function
def f(u,v):
    return (270-180*sym.atan2(v,u)/sym.pi)%360

u,v= sym.symbols('u v')

dfdu1 = diff(f(u,v),u).doit()
dfdv2 = diff(f(u,v),v).doit()

# example of value for the test
dfdu=dfdu1.evalf(subs={u: 2,v: 6}).doit()
dfdv=dfdv1.evalf(subs={u: 2,v: 6}).doit()
std_u=0.5
std_v=0.3

np.sqrt(float(dfdu**2*st_u**2+dfdv**2*std_v**2))

</code>```

One of the result:

```<code>dfdu1=180*v*Subs(Derivative(Mod(_xi_1, 4), _xi_1), _xi_1, -2*atan2(v, u)/pi + 3)/(pi*(u**2 + v**2))

dfdv1=-180*u*Subs(Derivative(Mod(_xi_1, 4), _xi_1), _xi_1, -2*atan2(v, u)/pi + 3)/(pi*(u**2 + v**2))
</code>```

I saw on github that this means that sympy is not yet able to determine the derivative of my function.

I have tried to break down the calculation but did not know what should be _xi_1 (I am not familiar with sympy)

Is there another way to do this calculation?

Thanks for your help !

Body:
the aim of this script is to obtain the standard deviation of the wind direction using U, V wind speed components and their respective standard wind speed deviation (std_u, std_v).

from sympy import *
import numpy as np

# wind direction calculation function
def f(u,v):
    return (270-180*sym.atan2(v,u)/sym.pi)%360

u,v= sym.symbols('u v')

dfdu1 = diff(f(u,v),u).doit()
dfdv2 = diff(f(u,v),v).doit()

# example of value for the test
dfdu=dfdu1.evalf(subs={u: 2,v: 6}).doit()
dfdv=dfdv1.evalf(subs={u: 2,v: 6}).doit()
std_u=0.5
std_v=0.3

np.sqrt(float(dfdu**2*st_u**2+dfdv**2*std_v**2))

One of the result:

dfdu1=180*v*Subs(Derivative(Mod(_xi_1, 4), _xi_1), _xi_1, -2*atan2(v, u)/pi + 3)/(pi*(u**2 + v**2))

dfdv1=-180*u*Subs(Derivative(Mod(_xi_1, 4), _xi_1), _xi_1, -2*atan2(v, u)/pi + 3)/(pi*(u**2 + v**2))

I saw on github that this means that sympy is not yet able to determine the derivative of my function.

I have tried to break down the calculation but did not know what should be _xi_1 (I am not familiar with sympy)

Is there another way to do this calculation?

Thanks for your help !


问:
Python sorting list of dictionary sort by key with multiple decimals
I have a list of dictionary named code[] which has values

```<code>[{'sectionnumber': '1010.1.9.1', ...},
{'sectionnumber': '1010.1.9.2', ...}
{'sectionnumber': '1010.1.9', ...},
{'sectionnumber': '1010.1.9.10', ...}]
</code>```

and I want to sort them by sectionnumber. I tried using :

```<code>codelist = sorted(codelist, key=lambda codelist:codelist["sectionnumber"])
</code>```

but it returns

```<code>[{'sectionnumber': '1010.1.9', ...},
{'sectionnumber': '1010.1.9.1', ...}
{'sectionnumber': '1010.1.9.10', ...},
{'sectionnumber': '1010.1.9.2', ...}]
</code>```

when it supposed to be

```<code>[{'sectionnumber': '1010.1.9', ...},
{'sectionnumber': '1010.1.9.1', ...}
{'sectionnumber': '1010.1.9.2', ...},
{'sectionnumber': '1010.1.9.10', ...}]
</code>```

Body:
I have a list of dictionary named code[] which has values

[{'sectionnumber': '1010.1.9.1', ...},
{'sectionnumber': '1010.1.9.2', ...}
{'sectionnumber': '1010.1.9', ...},
{'sectionnumber': '1010.1.9.10', ...}]

and I want to sort them by sectionnumber. I tried using :

codelist = sorted(codelist, key=lambda codelist:codelist["sectionnumber"])

but it returns

[{'sectionnumber': '1010.1.9', ...},
{'sectionnumber': '1010.1.9.1', ...}
{'sectionnumber': '1010.1.9.10', ...},
{'sectionnumber': '1010.1.9.2', ...}]

when it supposed to be

[{'sectionnumber': '1010.1.9', ...},
{'sectionnumber': '1010.1.9.1', ...}
{'sectionnumber': '1010.1.9.2', ...},
{'sectionnumber': '1010.1.9.10', ...}]


问:
TypeScript class imports and extends CommonJS class from CommonJS package
In a TypeScript Angular project, I'm trying to extend a class from a CommonJS JavaScript package.
This is the CommonJS JavaScript package:

https://github.com/orbitdb/orbit-db-access-controllers

https://www.npmjs.com/package/orbit-db-access-controllers

I have npm installed the package in my TypeScript project.

Now, I want my TypeScript Angular class to extend one of the CommonJS JavaScript classes in the package:

https://github.com/orbitdb/orbit-db-access-controllers/blob/main/src/ipfs-access-controller.js

My TypeScript Angular class currently looks like this:

I am importing IPFSAccessController by require() because it's a CommonJS module. As far as I know, this is the right thing to do when TypeScript code needs to import a CommonJS module.

(Pay attention that here I am using a TypeScript class to extend a JavaScript class)

```<code>const IPFSAccessController = require('../../../../../node_modules/orbit-db-access-controllers/src/ipfs-access-controller')

export class MyAccessController extends IPFSAccessController {

  constructor (ipfs: any, options: any) {
    super(ipfs, options)
    console.log("inside TS constructor")
  }

  static get type () {
    console.log("inside TS type")
    return "myType"
  }

  async canAppend(entry: any, identityProvider: any) {
    console.log("inside TS canAppend")
    return true
  }
}
</code>```

In the IPFSAccessController JavaScript class that I am importing, I added similar console logging, but with "JS" instead of "TS".

According to the instructions in the GitHub link above, I have in my project the following TypeScript code:

```<code>let AccessControllers = require('orbit-db-access-controllers')
AccessControllers.addAccessController({ AccessController: MyAccessController })

const orbitdb = await OrbitDB.createInstance(ipfs, {
  AccessControllers: AccessControllers
})

const db = await orbitdb.keyvalue('first-database', {
  accessController: {
    type: 'myType',
    write: [identity.id]
  }
})
</code>```

It compiles and runs, but I notice the following problem:

Where MyAccessController subclass is supposed to be used, actually the superclass IPFSAccessController is being used instead. So all the console logging from the methods constructor() and canAppend(), are called from the superclass. Only the static method type() is called from the subclass (according to the logging).

Why is that and how can I correct this?

Body:
In a TypeScript Angular project, I'm trying to extend a class from a CommonJS JavaScript package.
This is the CommonJS JavaScript package:

https://github.com/orbitdb/orbit-db-access-controllers

https://www.npmjs.com/package/orbit-db-access-controllers

I have npm installed the package in my TypeScript project.

Now, I want my TypeScript Angular class to extend one of the CommonJS JavaScript classes in the package:

https://github.com/orbitdb/orbit-db-access-controllers/blob/main/src/ipfs-access-controller.js

My TypeScript Angular class currently looks like this:

I am importing IPFSAccessController by require() because it's a CommonJS module. As far as I know, this is the right thing to do when TypeScript code needs to import a CommonJS module.

(Pay attention that here I am using a TypeScript class to extend a JavaScript class)

const IPFSAccessController = require('../../../../../node_modules/orbit-db-access-controllers/src/ipfs-access-controller')

export class MyAccessController extends IPFSAccessController {

  constructor (ipfs: any, options: any) {
    super(ipfs, options)
    console.log("inside TS constructor")
  }

  static get type () {
    console.log("inside TS type")
    return "myType"
  }

  async canAppend(entry: any, identityProvider: any) {
    console.log("inside TS canAppend")
    return true
  }
}

In the IPFSAccessController JavaScript class that I am importing, I added similar console logging, but with "JS" instead of "TS".

According to the instructions in the GitHub link above, I have in my project the following TypeScript code:

let AccessControllers = require('orbit-db-access-controllers')
AccessControllers.addAccessController({ AccessController: MyAccessController })

const orbitdb = await OrbitDB.createInstance(ipfs, {
  AccessControllers: AccessControllers
})

const db = await orbitdb.keyvalue('first-database', {
  accessController: {
    type: 'myType',
    write: [identity.id]
  }
})

It compiles and runs, but I notice the following problem:

Where MyAccessController subclass is supposed to be used, actually the superclass IPFSAccessController is being used instead. So all the console logging from the methods constructor() and canAppend(), are called from the superclass. Only the static method type() is called from the subclass (according to the logging).

Why is that and how can I correct this?


问:
Play byte array in Exo player
I'm trying to play byte array with exo player is there any suggestion for me
This is what I tryed

```<code>private fun playAudio(bytes: ByteArray) {
    lifecycleScope.launch {

        player!!.apply {
            setMediaSource(createMediaSource(bytes))
            prepare()
            playWhenReady = true // start playing when the exoplayer has setup

        }
    }
}

fun createMediaSource(bytes: ByteArray): MediaSource {
    val byteArrayDataSource = ByteArrayDataSource(bytes)
    val factory = DataSource.Factory {
        return@Factory byteArrayDataSource
    }
    return ProgressiveMediaSource.Factory(factory,
        ExtractorsFactory { return@ExtractorsFactory arrayOf(Mp3Extractor()) })
        .createMediaSource(
            MediaItem.fromUri(
                Uri.EMPTY
            )
        )
}
</code>```

also this is my recording function which has a function to return byteString/byteArray

```<code>suspend fun recordVoice(audioRecord: AudioRecord?) = withContext(Dispatchers.IO) {
    Log.i("LOG", "BUFFER SIZE: $BUFFER_SIZE_RECORDING")
    audioRecord?.startRecording()
    val buf = ByteArray(BUFFER_SIZE_RECORDING)
    try {
        do {
            val byteRead = audioRecord?.read(buf, 0, buf.size) ?: break

            if (byteRead < -1)
                break
            onRecordedByteString.byteString(buf.toByteString(0, byteRead))
        } while (true)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
</code>```

And buffer

```<code>companion object {
    private const val RECORDER_SAMPLE_RATE = 44100
    private const val RECORDER_CHANNELS: Int = AudioFormat.CHANNEL_IN_STEREO
    private const val RECORDER_AUDIO_ENCODING: Int = AudioFormat.ENCODING_PCM_16BIT
    private val BUFFER_SIZE_RECORDING = AudioRecord.getMinBufferSize(
        RECORDER_SAMPLE_RATE,
        RECORDER_CHANNELS,
        RECORDER_AUDIO_ENCODING
    ) * 4

}
</code>```

after recording and pushing play button this issue happening

Title: Play byte array in Exo player

Body:
I'm trying to play byte array with exo player is there any suggestion for me
This is what I tryed

private fun playAudio(bytes: ByteArray) {
    lifecycleScope.launch {

        player!!.apply {
            setMediaSource(createMediaSource(bytes))
            prepare()
            playWhenReady = true // start playing when the exoplayer has setup

        }
    }
}

fun createMediaSource(bytes: ByteArray): MediaSource {
    val byteArrayDataSource = ByteArrayDataSource(bytes)
    val factory = DataSource.Factory {
        return@Factory byteArrayDataSource
    }
    return ProgressiveMediaSource.Factory(factory,
        ExtractorsFactory { return@ExtractorsFactory arrayOf(Mp3Extractor()) })
        .createMediaSource(
            MediaItem.fromUri(
                Uri.EMPTY
            )
        )
}

also this is my recording function which has a function to return byteString/byteArray

suspend fun recordVoice(audioRecord: AudioRecord?) = withContext(Dispatchers.IO) {
    Log.i("LOG", "BUFFER SIZE: $BUFFER_SIZE_RECORDING")
    audioRecord?.startRecording()
    val buf = ByteArray(BUFFER_SIZE_RECORDING)
    try {
        do {
            val byteRead = audioRecord?.read(buf, 0, buf.size) ?: break

            if (byteRead < -1)
                break
            onRecordedByteString.byteString(buf.toByteString(0, byteRead))
        } while (true)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

And buffer

companion object {
    private const val RECORDER_SAMPLE_RATE = 44100
    private const val RECORDER_CHANNELS: Int = AudioFormat.CHANNEL_IN_STEREO
    private const val RECORDER_AUDIO_ENCODING: Int = AudioFormat.ENCODING_PCM_16BIT
    private val BUFFER_SIZE_RECORDING = AudioRecord.getMinBufferSize(
        RECORDER_SAMPLE_RATE,
        RECORDER_CHANNELS,
        RECORDER_AUDIO_ENCODING
    ) * 4

}

after recording and pushing play button this issue happening


问:
I need to convert WSQ base64 format into normal flutter base64 image
I am integrating finger print feature, which return fingerprint WSQ base64 format, I want to return it into normal base64 flutter format.</p>


问:
Why can't Firebase Emulator trigger an Flutter event for EmailVerifiedAction?
I am using Firebase Emulator to test for User Registration of my Flutter app based on the example code: https://github.com/firebase/flutterfire/blob/master/packages/firebase_ui_auth/example/lib/main.dart

The Firebase Auth emulator successfully generated the link, something like this: http://127.0.0.1:9099/emulator/action?mode=verifyEmail&lang=en&oobCode=ZJIl7jQ26ZMqribJt8zSmMvFNjL_KGv9GDK7ApDsqPwetWCkz0_gFR&apiKey=fake-api-key&continueUrl=http%3A%2F%2Flocalhost%3A50707%2F

When I paste this link to browser, the emulator switches the "Verified email?" flag for the user to true, which tells me the link is valid. However, this link redirects to Sign-in screen (/#), instead of profile page (/#/profile) which means the user is logged in and email verified. I think it's something to deal with the url of the ActionCodeSettings but I cannot manage to make it work.

Conversely, it works fine if I connect directly to Firebase server, i.e. it can verify the email and then go to the profile screen after clicking on the "Continue" button. Is this a known issue for Flutter to work with Firebase emulator?


问:
How to know if the msg sent in the firebase db is my msg or others msg
I m making  a chat application in the main activity I am getting a data from a node:"chatnode", in that node all the chats are present and if anyone writes a chat its data is also being stored in that node and later can be seen in a recycler view !, what i want to do is that i want to detect that the data which is being given in the recycler view is 'mychat' (chat sent by me) or 'others chat'(chat sent by someone else), and once i detect that i want to set different views for the recycler view for eg- left side view for 'others chat' right side view for 'mychat'!

```<code>public class Chat_Adapter extends
FirebaseRecyclerAdapter<Chat_Model,Chat_Adapter.myViewHolder> {

public Chat_Adapter(@NonNull FirebaseRecyclerOptions<Chat_Model> options) {
    super(options);
}

@Override
protected void onBindViewHolder(@NonNull myViewHolder holder, int position, @NonNull Chat_Model model) {
    holder.date.setText(model.getDate());
    holder.uname.setText(model.getUname());
    holder.msg.setText(model.getMsg());
}

@NonNull
@Override
public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item, parent, false);

/*i have another view which is View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.mychat_item, parent, false);*/

 return new myViewHolder(view);
}

class myViewHolder extends RecyclerView.ViewHolder {
    TextView uname, date,msg;

    public myViewHolder(@NonNull View itemView) {
        super(itemView);

        uname = itemView.findViewById(R.id.named);
        date = itemView.findViewById(R.id.date);
        msg = itemView.findViewById(R.id.message);
    }
}
</code>```

}

in this adapter class there is an activity in which we can set the views!

what i tried-
i tried to get the 'uname' which is the name of the user who sent the chat, and my own name which i got from the sharedprefs , but i am unable to get the 'uname' in oncreatviewHolder method because the onbindviewholder method runs after the oncreateviewholder method so it crashes!

brief what i want to do !
I want to get the data from a node in my firebase db and detect if that data is sent by me or another user!, if sent my me then it should be on the right side of the recyclerview but if sent by other user then it should be on the left side of the recyler view as it happens in other chat app ! hope u get what i mean to say

Body:
I m making  a chat application in the main activity I am getting a data from a node:"chatnode", in that node all the chats are present and if anyone writes a chat its data is also being stored in that node and later can be seen in a recycler view !, what i want to do is that i want to detect that the data which is being given in the recycler view is 'mychat' (chat sent by me) or 'others chat'(chat sent by someone else), and once i detect that i want to set different views for the recycler view for eg- left side view for 'others chat' right side view for 'mychat'!

public class Chat_Adapter extends
FirebaseRecyclerAdapter<Chat_Model,Chat_Adapter.myViewHolder> {

public Chat_Adapter(@NonNull FirebaseRecyclerOptions<Chat_Model> options) {
    super(options);
}

@Override
protected void onBindViewHolder(@NonNull myViewHolder holder, int position, @NonNull Chat_Model model) {
    holder.date.setText(model.getDate());
    holder.uname.setText(model.getUname());
    holder.msg.setText(model.getMsg());
}

@NonNull
@Override
public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item, parent, false);

/*i have another view which is View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.mychat_item, parent, false);*/

 return new myViewHolder(view);
}

class myViewHolder extends RecyclerView.ViewHolder {
    TextView uname, date,msg;

    public myViewHolder(@NonNull View itemView) {
        super(itemView);

        uname = itemView.findViewById(R.id.named);
        date = itemView.findViewById(R.id.date);
        msg = itemView.findViewById(R.id.message);
    }
}

}

in this adapter class there is an activity in which we can set the views!

what i tried-
i tried to get the 'uname' which is the name of the user who sent the chat, and my own name which i got from the sharedprefs , but i am unable to get the 'uname' in oncreatviewHolder method because the onbindviewholder method runs after the oncreateviewholder method so it crashes!

brief what i want to do !
I want to get the data from a node in my firebase db and detect if that data is sent by me or another user!, if sent my me then it should be on the right side of the recyclerview but if sent by other user then it should be on the left side of the recyler view as it happens in other chat app ! hope u get what i mean to say


问:
Asynchronously load configuration for Sequelize CLI
I am using Sequelize CLI to run migrations against out database and I have the following .sequelizerc file

// .sequelizerc
const path = require('path');

module.exports = {
  "config": path.resolve('src', 'database', 'config.js'),
  "models-path": path.resolve('src', 'models'),
  "seeders-path": path.resolve('src', 'database', 'seeders'),
  "migrations-path": path.resolve('src',  'database', 'migrations'),
};
```
<p>The credentials for our database are kept in a secrets manager so they can be easily rotated and never stored within our repository or someone's computer. Thus, our <code>config.js</code> file looks like:</p>
<pre class="lang-js prettyprint-override"><code>// src/database/config.js
const { AsyncObtainDBCredentials } = require("../utilities");
async function setupDBCreds() {
  const dbConfig = await AsyncObtainDBCredentials();
  return dbConfig;
}
module.export = setupDBCreds(); // exports a promise and does not work
</code>```

Sequelize CLI is expecting a configuration JSON like

const dotenv = require('dotenv')
dotenv.config()

const dbConfig = {
    host: process.env.DB_HOST ?? 'localhost',
    username: process.env.DB_USER ?? 'postgres',
    port: process.env.DB_PORT ?? '5432',
    database: process.env.DB_NAME ?? 'myDBName',
    password: process.env.DB_PASSWORD ?? 'SuperSecretPasswd',
    dialect: "postgres"
};

module.exports = dbConfig;
```

Is there a way to make this work so we can avoid users having write credentials in to an .env file?

Body:
I am using Sequelize CLI to run migrations against out database and I have the following .sequelizerc file

// .sequelizerc
const path = require('path');

module.exports = {
  "config": path.resolve('src', 'database', 'config.js'),
  "models-path": path.resolve('src', 'models'),
  "seeders-path": path.resolve('src', 'database', 'seeders'),
  "migrations-path": path.resolve('src',  'database', 'migrations'),
};

The credentials for our database are kept in a secrets manager so they can be easily rotated and never stored within our repository or someone's computer. Thus, our config.js file looks like:

// src/database/config.js
const { AsyncObtainDBCredentials } = require("../utilities");
async function setupDBCreds() {
  const dbConfig = await AsyncObtainDBCredentials();
  return dbConfig;
}
module.export = setupDBCreds(); // exports a promise and does not work

Sequelize CLI is expecting a configuration JSON like

const dotenv = require('dotenv')
dotenv.config()

const dbConfig = {
    host: process.env.DB_HOST ?? 'localhost',
    username: process.env.DB_USER ?? 'postgres',
    port: process.env.DB_PORT ?? '5432',
    database: process.env.DB_NAME ?? 'myDBName',
    password: process.env.DB_PASSWORD ?? 'SuperSecretPasswd',
    dialect: "postgres"
};

module.exports = dbConfig;

Is there a way to make this work so we can avoid users having write credentials in to an .env file?


问:
How to use pandas.DataFrame.asfreq with multi-level indexing
I have a Pandas dataframe like this:

'type' and 'date' are index columns and 'sum' a time-series. I need to convert the series to a given frequency. If I use asfreq('b') I get the following error:

```<code>df = df.asfreq('b')
</code>```

TypeError: Cannot convert input [('type1', datetime.date(2020, 6, 17))] of type <class 'tuple'> to Timestamp

If I use only the 'date' column with asfrec(), it also gives an error as there are repeated dates:

ValueError: cannot reindex on an axis with duplicate labels

How could I convert the multi-level index df to the desired frequency?

Body:
I have a Pandas dataframe like this:

'type' and 'date' are index columns and 'sum' a time-series. I need to convert the series to a given frequency. If I use asfreq('b') I get the following error:

df = df.asfreq('b')

TypeError: Cannot convert input [('type1', datetime.date(2020, 6, 17))] of type <class 'tuple'> to Timestamp

If I use only the 'date' column with asfrec(), it also gives an error as there are repeated dates:

ValueError: cannot reindex on an axis with duplicate labels

How could I convert the multi-level index df to the desired frequency?


问:
how can i solve flutter: Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct)
i am trying to implement chat app and Here is my Provider class which append New message to message list. the messages are listened from socket io server.

```<code>class MessageProvider with ChangeNotifier {
  List<MessageData> _message = [];
  List<MessageData> get message => [..._message];

  void appendNewMessages(MessageData messageData) {
    _message.insert(0, messageData);
    notifyListeners();
  }
}
</code>```

Below is the chat screen and when a user send message then the message is sent to socket io using "sendMessage" event. after that the sent message is listned using "getMessage" event from the socket io server. then the provider class append the recived message to message list and it will be refelcted to the screen. but my question is when the user navigator.of(context).pop() from the chat screen and then came by to the chat screen and try to send message the error happens.

```<code>import 'package:dating_app/controller/provider/message.dart';
import 'package:dating_app/controller/provider/socket.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../models/message.dart';

// ignore: must_be_immutable
class IndividualChatScreen extends StatefulWidget {
  String conversationID;
  String reciverID;
  String reciverName;
  String reciverImage;
  IndividualChatScreen(
      {required this.conversationID,
      required this.reciverID,
      required this.reciverName,
      required this.reciverImage});
  @override
  State<IndividualChatScreen> createState() => _IndividualChatScreenState();
}

class _IndividualChatScreenState extends State<IndividualChatScreen> {
  final _messageController = TextEditingController();
  bool _isInit = true;
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_isInit) {
      Provider.of<SocketProvider>(context, listen: false)
          .subscribeToEvent("getMessage", (data) {
        print(data);
        Provider.of<MessageProvider>(context, listen: false).appendNewMessages(
            MessageData(
                id: "id",
                conversationId: widget.conversationID,
                receiverID: data["receiverId"],
                text: data["text"],
                senderId: data["senderId"],
                createdAt: DateTime.now(),
                updatedAt: DateTime.now(),
                v: 2));
      });
      _isInit = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(widget.reciverName),
        leading: GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Icon(Icons.arrow_back_ios, size: 28)),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 8.0),
            child: Container(
              height: 40,
              width: 40,
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  image: DecorationImage(
                      image: NetworkImage(widget.reciverImage),
                      fit: BoxFit.cover)),
            ),
          )
        ],
      ),
      body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: ListView.builder(
                  reverse: true,
                  shrinkWrap: true,
                  itemCount:
                      Provider.of<MessageProvider>(context).message.length,
                  scrollDirection: Axis.vertical,
                  itemBuilder: (context, index) {
                    return Container(
                      padding: EdgeInsets.only(
                          left: 12, right: 12, top: 10, bottom: 10),
                      child: Align(
                        alignment: (Provider.of<MessageProvider>(context)
                                    .message[index]
                                    .senderId !=
                                "63aac4f2bbb23a37343daa46"
                            ? Alignment.topLeft
                            : Alignment.topRight),
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(6.0),
                            color: (Provider.of<MessageProvider>(context)
                                        .message[index]
                                        .senderId !=
                                    "63aac4f2bbb23a37343daa46"
                                ? Colors.grey.shade200
                                : Colors.blue[200]),
                          ),
                          padding: EdgeInsets.all(16),
                          child: Text(
                            Provider.of<MessageProvider>(context)
                                .message[index]
                                .text,
                            style: TextStyle(fontSize: 15),
                          ),
                        ),
                      ),
                    );
                  }),
            ),
            //
            //send message textfield
            //
            Container(
              height: 54,
              width: screenSize.width,
              color: Colors.grey.shade200,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(
                          left: 12.0, top: 6.0, bottom: 6.0),
                      child: Container(
                        width: screenSize.width * 0.8,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(6.0),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.only(left: 8.0),
                          child: TextField(
                            controller: _messageController,
                            autocorrect: false,
                            cursorWidth: 1.5,
                            textAlignVertical: TextAlignVertical.center,
                            decoration: InputDecoration(
                              hintText: "Message",
                              border: InputBorder.none,
                            ),
                          ),
                        ),
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        Provider.of<SocketProvider>(context, listen: false)
                            .sendToSocket("sendMessage", {
                          "senderId": "63aac4f2bbb23a37343daa46",
                          "receiverId": widget.reciverID,
                          "text": _messageController.text,
                        });
                        _messageController.clear();
                      },
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Container(
                            height: 40,
                            width: 40,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                shape: BoxShape.circle, color: Colors.pink),
                            child: Icon(
                              Icons.send_outlined,
                              size: 22,
                              color: Colors.white,
                            )),
                      ),
                    )
                  ]),
            ),
          ]),
    );
  }
}
</code>```

Body:
i am trying to implement chat app and Here is my Provider class which append New message to message list. the messages are listened from socket io server.

class MessageProvider with ChangeNotifier {
  List<MessageData> _message = [];
  List<MessageData> get message => [..._message];

  void appendNewMessages(MessageData messageData) {
    _message.insert(0, messageData);
    notifyListeners();
  }
}

Below is the chat screen and when a user send message then the message is sent to socket io using "sendMessage" event. after that the sent message is listned using "getMessage" event from the socket io server. then the provider class append the recived message to message list and it will be refelcted to the screen. but my question is when the user navigator.of(context).pop() from the chat screen and then came by to the chat screen and try to send message the error happens.

import 'package:dating_app/controller/provider/message.dart';
import 'package:dating_app/controller/provider/socket.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../models/message.dart';

// ignore: must_be_immutable
class IndividualChatScreen extends StatefulWidget {
  String conversationID;
  String reciverID;
  String reciverName;
  String reciverImage;
  IndividualChatScreen(
      {required this.conversationID,
      required this.reciverID,
      required this.reciverName,
      required this.reciverImage});
  @override
  State<IndividualChatScreen> createState() => _IndividualChatScreenState();
}

class _IndividualChatScreenState extends State<IndividualChatScreen> {
  final _messageController = TextEditingController();
  bool _isInit = true;
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_isInit) {
      Provider.of<SocketProvider>(context, listen: false)
          .subscribeToEvent("getMessage", (data) {
        print(data);
        Provider.of<MessageProvider>(context, listen: false).appendNewMessages(
            MessageData(
                id: "id",
                conversationId: widget.conversationID,
                receiverID: data["receiverId"],
                text: data["text"],
                senderId: data["senderId"],
                createdAt: DateTime.now(),
                updatedAt: DateTime.now(),
                v: 2));
      });
      _isInit = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(widget.reciverName),
        leading: GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Icon(Icons.arrow_back_ios, size: 28)),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 8.0),
            child: Container(
              height: 40,
              width: 40,
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  image: DecorationImage(
                      image: NetworkImage(widget.reciverImage),
                      fit: BoxFit.cover)),
            ),
          )
        ],
      ),
      body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: ListView.builder(
                  reverse: true,
                  shrinkWrap: true,
                  itemCount:
                      Provider.of<MessageProvider>(context).message.length,
                  scrollDirection: Axis.vertical,
                  itemBuilder: (context, index) {
                    return Container(
                      padding: EdgeInsets.only(
                          left: 12, right: 12, top: 10, bottom: 10),
                      child: Align(
                        alignment: (Provider.of<MessageProvider>(context)
                                    .message[index]
                                    .senderId !=
                                "63aac4f2bbb23a37343daa46"
                            ? Alignment.topLeft
                            : Alignment.topRight),
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(6.0),
                            color: (Provider.of<MessageProvider>(context)
                                        .message[index]
                                        .senderId !=
                                    "63aac4f2bbb23a37343daa46"
                                ? Colors.grey.shade200
                                : Colors.blue[200]),
                          ),
                          padding: EdgeInsets.all(16),
                          child: Text(
                            Provider.of<MessageProvider>(context)
                                .message[index]
                                .text,
                            style: TextStyle(fontSize: 15),
                          ),
                        ),
                      ),
                    );
                  }),
            ),
            //
            //send message textfield
            //
            Container(
              height: 54,
              width: screenSize.width,
              color: Colors.grey.shade200,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(
                          left: 12.0, top: 6.0, bottom: 6.0),
                      child: Container(
                        width: screenSize.width * 0.8,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(6.0),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.only(left: 8.0),
                          child: TextField(
                            controller: _messageController,
                            autocorrect: false,
                            cursorWidth: 1.5,
                            textAlignVertical: TextAlignVertical.center,
                            decoration: InputDecoration(
                              hintText: "Message",
                              border: InputBorder.none,
                            ),
                          ),
                        ),
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        Provider.of<SocketProvider>(context, listen: false)
                            .sendToSocket("sendMessage", {
                          "senderId": "63aac4f2bbb23a37343daa46",
                          "receiverId": widget.reciverID,
                          "text": _messageController.text,
                        });
                        _messageController.clear();
                      },
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Container(
                            height: 40,
                            width: 40,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                shape: BoxShape.circle, color: Colors.pink),
                            child: Icon(
                              Icons.send_outlined,
                              size: 22,
                              color: Colors.white,
                            )),
                      ),
                    )
                  ]),
            ),
          ]),
    );
  }
}


问:
How to pass arguments for multi threading?
I am writing a program that can connect multiple clients to a server. I am creating a new thread for each user but am running into error in the multi threading portion

This is my server side code:

```<code>from socket import*
import threading

server = socket(AF_INET,SOCK_STREAM)
server.bind(('localhost',9000))

def handle_client(conn,addr):
    print(addr)
    while(True):
        info = conn.recv(5000).decode()
        if(len(info)>0):
            print(info[0])
            data = "HTTP/1.1 200 OK\r\n"
            data += "Content-Type: text/html; charset=utf-8\r\n"
            data += "\r\n"
            data += "<html><body>Hello World</body></html>\r\n\r\n"
            conn.sendall(data.encode())
            conn.shutdown(SHUT_WR)

def start():
    server.listen()
    print(f"Server is listening on {server}")
    while(True):
        conn,addr = server.accept()# Waits for a connection to start. Returns tuple of connection_object and server address
        thread = threading.Thread(target=handle_client,args=(conn,addr))
        thread.start()

start()

</code>```

I am passing the arguments as tuple but for some reason i am still running into error

```<code>Server is listening on <socket.socket fd=272, family=2, type=1, proto=0, laddr=('127.0.0.1', 9000)>('127.0.0.1', 50959)
0
Exception in thread Thread-1 (handle_client):
Traceback (most recent call last):
  File "C:\Users\Arun\AppData\Local\Programs\Python\Python311\Lib\threading.py", line
1038, in _bootstrap_inner
    self.run()
  File "C:\Users\Arun\AppData\Local\Programs\Python\Python311\Lib\threading.py", line
975, in run
    self._target(*self._args, **self._kwargs)
  File "e:\Desktop\Django\Django_Basics\Django_Basics\WebSockets\WorldsSimplestServer.py", line 25, in handle_client
    info = conn.recv(5000).decode()
           ^^^^^^^^^^^^^^^
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

</code>```

Edit: I fixed it by terminating the connection

```<code>from socket import*
import threading
server = socket(AF_INET,SOCK_STREAM)
server.bind(('localhost',9000))

def handle_client(conn,addr):
    print(addr)
    connected = True
    while(connected):
        info = conn.recv(5000).decode()
        if(len(info)>0):
            print(info[0])
            data = "HTTP/1.1 200 OK\r\n"
            data += "Content-Type: text/html; charset=utf-8\r\n"
            data += "\r\n"
            data += "<html><body>Hello World</body></html>\r\n\r\n"
            conn.sendall(data.encode())
            conn.shutdown(SHUT_WR)
            connected = False

def start():
    server.listen()
    print(f"Server is listening on {server}")
    while(True):
        conn,addr = server.accept()# Waits for a connection to start. Returns tuple of connection_object and server address
        thread = threading.Thread(target=handle_client,args=(conn,addr))#Tryng to immitate java cause everyone loves java...
        thread.start()

start()
</code>```

Thanks a lot for helping guys!!

Body:
I am writing a program that can connect multiple clients to a server. I am creating a new thread for each user but am running into error in the multi threading portion

This is my server side code:

from socket import*
import threading

server = socket(AF_INET,SOCK_STREAM)
server.bind(('localhost',9000))

def handle_client(conn,addr):
    print(addr)
    while(True):
        info = conn.recv(5000).decode()
        if(len(info)>0):
            print(info[0])
            data = "HTTP/1.1 200 OK\r\n"
            data += "Content-Type: text/html; charset=utf-8\r\n"
            data += "\r\n"
            data += "Hello World\r\n\r\n"
            conn.sendall(data.encode())
            conn.shutdown(SHUT_WR)

def start():
    server.listen()
    print(f"Server is listening on {server}")
    while(True):
        conn,addr = server.accept()# Waits for a connection to start. Returns tuple of connection_object and server address
        thread = threading.Thread(target=handle_client,args=(conn,addr))
        thread.start()

start()

I am passing the arguments as tuple but for some reason i am still running into error

Server is listening on <socket.socket fd=272, family=2, type=1, proto=0, laddr=('127.0.0.1', 9000)>('127.0.0.1', 50959)
0
Exception in thread Thread-1 (handle_client):
Traceback (most recent call last):
  File "C:\Users\Arun\AppData\Local\Programs\Python\Python311\Lib\threading.py", line
1038, in _bootstrap_inner
    self.run()
  File "C:\Users\Arun\AppData\Local\Programs\Python\Python311\Lib\threading.py", line
975, in run
    self._target(*self._args, **self._kwargs)
  File "e:\Desktop\Django\Django_Basics\Django_Basics\WebSockets\WorldsSimplestServer.py", line 25, in handle_client
    info = conn.recv(5000).decode()
           ^^^^^^^^^^^^^^^
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

Edit: I fixed it by terminating the connection

from socket import*
import threading
server = socket(AF_INET,SOCK_STREAM)
server.bind(('localhost',9000))

def handle_client(conn,addr):
    print(addr)
    connected = True
    while(connected):
        info = conn.recv(5000).decode()
        if(len(info)>0):
            print(info[0])
            data = "HTTP/1.1 200 OK\r\n"
            data += "Content-Type: text/html; charset=utf-8\r\n"
            data += "\r\n"
            data += "Hello World\r\n\r\n"
            conn.sendall(data.encode())
            conn.shutdown(SHUT_WR)
            connected = False

def start():
    server.listen()
    print(f"Server is listening on {server}")
    while(True):
        conn,addr = server.accept()# Waits for a connection to start. Returns tuple of connection_object and server address
        thread = threading.Thread(target=handle_client,args=(conn,addr))#Tryng to immitate java cause everyone loves java...
        thread.start()

start()

Thanks a lot for helping guys!!


问:
PHP Strip Base64 images from string
I am using a very simple PHP script to save content from a TinyMCE Text Editor, I have had various issues with this text editor, specifically with image uploads saving images as Base64. I am hoping I have now solved the problem although to cover my back and save me hours of time removing Base64 images from the database, I am trying to strip any Base64 images from the content uploaded to the database - Is this possible and is there a simple method to achieve this?

Here is what I have at the moment, I could remove all images fine, but when looking for Base64 images, the code fails.

```<code>if(isset($_POST['update_content'])){
    $blog_id = $_POST['blog_id'];
    $blogcontent = $_POST['blogcontent'];

    $sql = "UPDATE `blog` SET `blog_content` = ? WHERE `blog_id` = ?;";
    $stmt = mysqli_stmt_init($conn);

    if(!mysqli_stmt_prepare($stmt, $sql)){

    }

    $blogcontent = preg_replace("/<img src=\"data:image/jpeg;base64[^>]+\>/i", "", $blogcontent);
    mysqli_stmt_bind_param($stmt, "ss", $blogcontent, $blog_id);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}
</code>```

What I would like to do is remove any Base64 images from $blogcontent before it is uploaded?

Title: PHP Strip Base64 images from string

Body:
I am using a very simple PHP script to save content from a TinyMCE Text Editor, I have had various issues with this text editor, specifically with image uploads saving images as Base64. I am hoping I have now solved the problem although to cover my back and save me hours of time removing Base64 images from the database, I am trying to strip any Base64 images from the content uploaded to the database - Is this possible and is there a simple method to achieve this?

Here is what I have at the moment, I could remove all images fine, but when looking for Base64 images, the code fails.

if(isset($_POST['update_content'])){
    $blog_id = $_POST['blog_id'];
    $blogcontent = $_POST['blogcontent'];

    $sql = "UPDATE `blog` SET `blog_content` = ? WHERE `blog_id` = ?;";
    $stmt = mysqli_stmt_init($conn);

    if(!mysqli_stmt_prepare($stmt, $sql)){

    }

    $blogcontent = preg_replace("/]+\>/i", "", $blogcontent);
    mysqli_stmt_bind_param($stmt, "ss", $blogcontent, $blog_id);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}

What I would like to do is remove any Base64 images from $blogcontent before it is uploaded?


问:
Flutter Open Whatsapp and Tel External Link or Launch Apps
i've been looking for the solution around the internet and couldn't solve it yet.

Here is the problem:

My apps are running on flutter with webview website which is build with Laravel. The website have button to open the whatsapp link and phone number to call.

So i build webview apps to browse the website and hoping the apps could open the button i mentioned earlier which is Whatsapp and Call button from the laravel website.

But flutter apps won't let me open or launch whatsapp in webview.

For final result, i just want the apps open or launch the Whatsapp and Telephone in the phone.

Thank you for your time


问:
Elasticsearch - No value specified for terms query
Calling all elasticsearch experts:

Environment:

elasticsearch (6.8.3)

rails 5.1.7

Linux

We changed our association from our user model to the person model from a has_one to a has_many.  We did not however remove the person_id column as this can cause other issues (e.g. running code from another branch that still tries to use it)

It seems no matter what we do to the index definitions for ElasticSearch, if any null values exist in person_id (which they do now with all newly added records) we get

```<code>"No value specified for terms query"
</code>```

I have confirmed this by populating that column with an integer value resulting in no error occurring.

I have removed person_id from any indexes I even removed any reference to the peoples table in the ES index declaration but it appears that as soon as ES sees there is an association to a Person model and it sees the person_id column, it tries to use it.

Besides writing an arbitrary value in the person_id column, does anyone else have a better approach?  We DO NEED to search fields in the associated Person model (peoples table) but since it's a has_many, it shouldn't be using the person_id column which is no longer relevant.

We also considered reversing the search from Person to User but that would require a LOT of recoding.

Is it possible a newer version of ES will fix it?  We'd probably have to upgrade the ES server as well if we update the gem right?

Here is the association:

  has_many :people, :class_name => Person.to_s # I believe it's this class name that's causting it to try to use the person_id column

Here is the index definition

```<code>  def as_indexed_json(_options = {})
    as_json(
      :only => %i[id email portal_id],
      :include => {
        :portal => { :only => %i[name slug] },
        :people => { :methods => %i[first last full_name], :only => %i[first last full_name] },
        :events => { :only => [:id] },
        :account_brokerage_firms => { :only => [:id] },
        :brokerage_firms => { :only => [:id] },
        :roles => { :methods => [:role_name], :only => [:role_name] }
      }
    )
  end

  settings AUTOCOMPLETE_SETTINGS do
    mapping :dynamic => 'false' do
      indexes :id, :type => 'long'
      indexes :email, :type => 'text', :analyzer => 'email'
      indexes :portal_id, :type => 'long'

      indexes :people do
        indexes :first, :type => 'text', :analyzer => 'autocomplete'
        indexes :last, :type => 'text', :analyzer => 'autocomplete'
        indexes :full_name, :type => 'text', :analyzer => 'autocomplete'
      end

      indexes :portal do
        indexes :name, :type => 'text', :analyzer => 'autocomplete'
        indexes :slug, :type => 'text', :analyzer => 'autocomplete'
      end

      indexes :events do
        indexes :id, :type => 'long'
      end

      indexes :account_brokerage_firms do
        indexes :id, :type => 'long'
      end

      indexes :brokerage_firms do
        indexes :id, :type => 'long'
      end

      indexes :roles do
        indexes :role_name, :type => 'text', :analyzer => 'autocomplete'
      end
    end
  end
  # end of elastic search settings

  # this function assumes there is only one user role between a user and an account

</code>```

Body:
Calling all elasticsearch experts:

Environment:

elasticsearch (6.8.3)

rails 5.1.7

Linux

We changed our association from our user model to the person model from a has_one to a has_many.  We did not however remove the person_id column as this can cause other issues (e.g. running code from another branch that still tries to use it)

It seems no matter what we do to the index definitions for ElasticSearch, if any null values exist in person_id (which they do now with all newly added records) we get

"No value specified for terms query"

I have confirmed this by populating that column with an integer value resulting in no error occurring.

I have removed person_id from any indexes I even removed any reference to the peoples table in the ES index declaration but it appears that as soon as ES sees there is an association to a Person model and it sees the person_id column, it tries to use it.

Besides writing an arbitrary value in the person_id column, does anyone else have a better approach?  We DO NEED to search fields in the associated Person model (peoples table) but since it's a has_many, it shouldn't be using the person_id column which is no longer relevant.

We also considered reversing the search from Person to User but that would require a LOT of recoding.

Is it possible a newer version of ES will fix it?  We'd probably have to upgrade the ES server as well if we update the gem right?

Here is the association:

  has_many :people, :class_name => Person.to_s # I believe it's this class name that's causting it to try to use the person_id column

Here is the index definition

  def as_indexed_json(_options = {})
    as_json(
      :only => %i[id email portal_id],
      :include => {
        :portal => { :only => %i[name slug] },
        :people => { :methods => %i[first last full_name], :only => %i[first last full_name] },
        :events => { :only => [:id] },
        :account_brokerage_firms => { :only => [:id] },
        :brokerage_firms => { :only => [:id] },
        :roles => { :methods => [:role_name], :only => [:role_name] }
      }
    )
  end

  settings AUTOCOMPLETE_SETTINGS do
    mapping :dynamic => 'false' do
      indexes :id, :type => 'long'
      indexes :email, :type => 'text', :analyzer => 'email'
      indexes :portal_id, :type => 'long'

      indexes :people do
        indexes :first, :type => 'text', :analyzer => 'autocomplete'
        indexes :last, :type => 'text', :analyzer => 'autocomplete'
        indexes :full_name, :type => 'text', :analyzer => 'autocomplete'
      end

      indexes :portal do
        indexes :name, :type => 'text', :analyzer => 'autocomplete'
        indexes :slug, :type => 'text', :analyzer => 'autocomplete'
      end

      indexes :events do
        indexes :id, :type => 'long'
      end

      indexes :account_brokerage_firms do
        indexes :id, :type => 'long'
      end

      indexes :brokerage_firms do
        indexes :id, :type => 'long'
      end

      indexes :roles do
        indexes :role_name, :type => 'text', :analyzer => 'autocomplete'
      end
    end
  end
  # end of elastic search settings

  # this function assumes there is only one user role between a user and an account


问:
make height of colour bar match the height of the main plot in R/ggplot
here is a reprex

```<code>library(ggplot2)
library(reshape2)
dat <- iris[,1:4]
cor <- melt(cor(dat, use="p"))
head(cor)
heat <- ggplot(data=cor, aes(x=Var1, y=Var2, fill=value))
heat + geom_tile() + labs(x = "", y = "") + scale_fill_gradient2(limits=c(-1, 1))
</code>```

how can I make the color bar height match and align with the y-axis?

many thanks!

Body:
here is a reprex

library(ggplot2)
library(reshape2)
dat <- iris[,1:4]
cor <- melt(cor(dat, use="p"))
head(cor)
heat <- ggplot(data=cor, aes(x=Var1, y=Var2, fill=value))
heat + geom_tile() + labs(x = "", y = "") + scale_fill_gradient2(limits=c(-1, 1))

how can I make the color bar height match and align with the y-axis?

many thanks!


问:
Pass data of page1 to page2(on a differnet page when clicked on page1 on page1)
```<code>import React, { useState } from 'react';

function Page1() {
  const [formData, setFormData] = useState({});

  const handleChange = (event) => {
    setFormData({
      ...formData,
      [event.target.name]: event.target.value
    });
  }

  const handleSubmit = (event) => {
    event.preventDefault();
    // update the state of Page2 to show the form data
    window.Page2.setFormData(formData);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" name="name" onChange={handleChange} />
      </label>
      <br />
      <label>
        Email:
        <input type="email" name="email" onChange={handleChange} />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}

function Page2() {
  const [formData, setFormData] = useState({});

  // expose setFormData function to the global scope
  window.Page2 = { setFormData };

  return (
    <div>
      <p>Name: {formData.name}</p>
      <p>Email: {formData.email}</p>
    </div>
  );
}

function App() {
  return (
    <div>
      <Page1 />
      <Page2 />
    </div>
  );
}

export default App;

</code>```

This is my code in this using react-router-dom I want to show data of page2 on the next page when clicked on submit on page1.

How can I do that?

This is my code in this using react-router-dom I want to show data of page2 on the next page when clicked on submit on page1.

How can I do that?

Body:
import React, { useState } from 'react';

function Page1() {
  const [formData, setFormData] = useState({});

  const handleChange = (event) => {
    setFormData({
      ...formData,
      [event.target.name]: event.target.value
    });
  }

  const handleSubmit = (event) => {
    event.preventDefault();
    // update the state of Page2 to show the form data
    window.Page2.setFormData(formData);
  }

  return (
    <form onSubmit={handleSubmit}>

        Name:
        <input type="text" name="name" onChange={handleChange} />

        Email:
        <input type="email" name="email" onChange={handleChange} />

      <button type="submit">Submit</button>
    </form>
  );
}

function Page2() {
  const [formData, setFormData] = useState({});

  // expose setFormData function to the global scope
  window.Page2 = { setFormData };

  return (

Name: {formData.name}

Email: {formData.email}

  );
}

function App() {
  return (

      <Page1 />
      <Page2 />

  );
}

export default App;

This is my code in this using react-router-dom I want to show data of page2 on the next page when clicked on submit on page1.

How can I do that?

This is my code in this using react-router-dom I want to show data of page2 on the next page when clicked on submit on page1.

How can I do that?


问:
Tkinter button appearing when used in a function
Working on a small project and I'm noticing my Tkinter button refuses to work in a def function. def upload_win(): comes up but I'm not able to get the button to appear on the ext1 = Tk() window. I'm new to python but I feel like this should work. I'm using pycharm if that helps at all.

```<code>from tkinter import *

root = Tk()
root.geometry('700x400+100+100')
root.maxsize(700, 400)
root.minsize(700, 400)
root.title("root")

def upload_win():

    root.destroy()

    ext1 = Tk()
    ext1.geometry('700x400+100+100')
    ext1.maxsize(700, 400)
    ext1.minsize(700, 400)
    ext1.title("1")

    btn1_ext1 = Button(ext1, test="back")
    btn1_ext1.place(x=590, y=360, height=30, width=100)
    btn1_ext1.configure(bg="DodgerBlue3", fg="black")

btn1_root = Button(root, text="ext1", command=upload_win)
btn1_root.place(x=590, y= 360, height=30, width=100)
btn1_root.configure(bg="DodgerBlue3", fg="black")

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

I expect a window to appear and have a button. When the button is pressed the first window gets deleted and a new one appears with a back button attached. So far the back button has yet to be attached to anything but I can't get it to show up.

Body:
Working on a small project and I'm noticing my Tkinter button refuses to work in a def function. def upload_win(): comes up but I'm not able to get the button to appear on the ext1 = Tk() window. I'm new to python but I feel like this should work. I'm using pycharm if that helps at all.

from tkinter import *

root = Tk()
root.geometry('700x400+100+100')
root.maxsize(700, 400)
root.minsize(700, 400)
root.title("root")

def upload_win():

    root.destroy()

    ext1 = Tk()
    ext1.geometry('700x400+100+100')
    ext1.maxsize(700, 400)
    ext1.minsize(700, 400)
    ext1.title("1")

    btn1_ext1 = Button(ext1, test="back")
    btn1_ext1.place(x=590, y=360, height=30, width=100)
    btn1_ext1.configure(bg="DodgerBlue3", fg="black")

btn1_root = Button(root, text="ext1", command=upload_win)
btn1_root.place(x=590, y= 360, height=30, width=100)
btn1_root.configure(bg="DodgerBlue3", fg="black")

root.mainloop()

I expect a window to appear and have a button. When the button is pressed the first window gets deleted and a new one appears with a back button attached. So far the back button has yet to be attached to anything but I can't get it to show up.


问:
Expression produces a union type that is too complex to represent. ts(2590) when creating UUID type
I am trying to create a type that represents a UUID in TypeScript. I'm new to TS but found this post that describes how to make a similar solution. However, when I use four (three is fine) of the same type, it causes this error. I can't find any solution because it appears imports or wrong TS versions in VS Code cause most. This is just a simple .ts file and I've already switched my VS Code TS versions from the workspace and vice versa. The code in question is below:

```<code>type uuidChar = 'q' | 'w' | 'e' | 'r' | 't' | 'y' | 'u' | 'i' | 'o' | 'p' | 'a' | 's' | 'd' | 'f' | 'g' | 'h' | 'j' | 'k' | 'l' | 'z' | 'x' | 'c' |
'v' | 'b' | 'n' | 'm' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0';

type uuid = `${uuidChar}-${uuidChar}-${uuidChar}-${uuidChar}`
</code>```

I want to make a type for an object field that represents a UUID from the crypto library and I couldn't find any types already made.

Thank you in advance!

Body:
I am trying to create a type that represents a UUID in TypeScript. I'm new to TS but found this post that describes how to make a similar solution. However, when I use four (three is fine) of the same type, it causes this error. I can't find any solution because it appears imports or wrong TS versions in VS Code cause most. This is just a simple .ts file and I've already switched my VS Code TS versions from the workspace and vice versa. The code in question is below:

type uuidChar = 'q' | 'w' | 'e' | 'r' | 't' | 'y' | 'u' | 'i' | 'o' | 'p' | 'a' | 's' | 'd' | 'f' | 'g' | 'h' | 'j' | 'k' | 'l' | 'z' | 'x' | 'c' |
'v' | 'b' | 'n' | 'm' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0';

type uuid = `${uuidChar}-${uuidChar}-${uuidChar}-${uuidChar}`

I want to make a type for an object field that represents a UUID from the crypto library and I couldn't find any types already made.

Thank you in advance!


问:
How to solve java.lang.module.FindException: Module gson.extras not found?
I have dependencies in build.gradle:

```<code>dependencies {
    implementation 'com.google.code.gson:gson:2.10'
    testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}")
    implementation 'org.danilopianini:gson-extras:1.1.0'
}
</code>```

In module-info.java I have:

```<code>module qu4lizz.taskscheduler {
    requires javafx.controls;
    requires javafx.fxml;
    requires java.desktop;
    requires com.google.gson;
    requires gson.extras;

    opens qu4lizz.taskscheduler.gui to javafx.fxml;
    opens qu4lizz.taskscheduler.my_task to javafx.fxml;
    exports qu4lizz.taskscheduler.gui;
    exports qu4lizz.taskscheduler.my_task;
}
</code>```

When I try to build this project I get error:

```<code>Error occurred during initialization of boot layer
java.lang.module.FindException: Module gson.extras not found, required by qu4lizz.taskscheduler
:GUI.main() (Thread[Execution worker Thread 4,5,main]) completed. Took 0.175 secs.

Execution failed for task ':GUI.main()'.
> Process 'command '/home/qu4lizz/.jdks/corretto-17.0.4.1/bin/java'' finished with non-zero exit value 1
</code>```

I don't have any idea how to solve this.

Body:
I have dependencies in build.gradle:

dependencies {
    implementation 'com.google.code.gson:gson:2.10'
    testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}")
    implementation 'org.danilopianini:gson-extras:1.1.0'
}

In module-info.java I have:

module qu4lizz.taskscheduler {
    requires javafx.controls;
    requires javafx.fxml;
    requires java.desktop;
    requires com.google.gson;
    requires gson.extras;

    opens qu4lizz.taskscheduler.gui to javafx.fxml;
    opens qu4lizz.taskscheduler.my_task to javafx.fxml;
    exports qu4lizz.taskscheduler.gui;
    exports qu4lizz.taskscheduler.my_task;
}

When I try to build this project I get error:

Error occurred during initialization of boot layer
java.lang.module.FindException: Module gson.extras not found, required by qu4lizz.taskscheduler
:GUI.main() (Thread[Execution worker Thread 4,5,main]) completed. Took 0.175 secs.

Execution failed for task ':GUI.main()'.
> Process 'command '/home/qu4lizz/.jdks/corretto-17.0.4.1/bin/java'' finished with non-zero exit value 1

I don't have any idea how to solve this.


问:
appium python - how to dump details of an element?
StackOverflow friends,

I'd like to find a programmatical way to dump a selected element in Appium Python.

The current solution from StackOverflow is to use

```<code>element.get_attribute('outerHTML')
</code>```

but this only works in WebView Context. Nowadays most apps run in NativeApp context, therefore, the 'outerHTML' isn't available.

I saw Appium Inspector can display the selected element's detail,

I'd like to mimic this in Python, and print out to terminal.

I could have dumped the whole page using

```<code>driver.page_source
</code>```

but I'd like to use the element-only dump to assert that I have selected the correct element.

By the way, I am testing on Android 13 device.

Thank you

Body:
StackOverflow friends,

I'd like to find a programmatical way to dump a selected element in Appium Python.

The current solution from StackOverflow is to use

element.get_attribute('outerHTML')

but this only works in WebView Context. Nowadays most apps run in NativeApp context, therefore, the 'outerHTML' isn't available.

I saw Appium Inspector can display the selected element's detail,

I'd like to mimic this in Python, and print out to terminal.

I could have dumped the whole page using

driver.page_source

but I'd like to use the element-only dump to assert that I have selected the correct element.

By the way, I am testing on Android 13 device.

Thank you


问:
Handling faiss-cpu vs. faiss-gpu in python setup script
I am trying write the setup script for my Python package which uses faiss such that an end user can install the CPU version of my package by default or specify a GPU-enabled version using extras_require. The problem is that faiss breaks if both faiss-cpu and faiss-gpu are simultaneously installed in the environment.

My setup script looks something like this:

setup(
    ...
    install_requires=[
        "faiss-cpu==1.7.0",
        ...,
    ],
    extras_require=(
        "gpu": ["faiss-gpu==1.7.0", ...],
        ...,
    ),
)
```

Things work as expected when my package is installed with no extras, but if [gpu] is specified then both faiss-cpu and faiss-gpu are installed. The only way to resolve this is to manually uninstall both faiss-cpu and faiss-gpu, then reinstall faiss-gpu (interestingly, simply uninstalling faiss-cpu does not work).

How can I write or redesign my setup script to avoid this issue?

Body:
I am trying write the setup script for my Python package which uses faiss such that an end user can install the CPU version of my package by default or specify a GPU-enabled version using extras_require. The problem is that faiss breaks if both faiss-cpu and faiss-gpu are simultaneously installed in the environment.

My setup script looks something like this:

setup(
    ...
    install_requires=[
        "faiss-cpu==1.7.0",
        ...,
    ],
    extras_require=(
        "gpu": ["faiss-gpu==1.7.0", ...],
        ...,
    ),
)

Things work as expected when my package is installed with no extras, but if [gpu] is specified then both faiss-cpu and faiss-gpu are installed. The only way to resolve this is to manually uninstall both faiss-cpu and faiss-gpu, then reinstall faiss-gpu (interestingly, simply uninstalling faiss-cpu does not work).

How can I write or redesign my setup script to avoid this issue?


问:
AttributeError While Using PIFuHD
I'm trying to use PIFuHD to create a 3d object from an image.

However, I keep getting this error in cell [14]:

```<code>AttributeError                            Traceback (most recent call last)
<ipython-input-14-736a0682666b> in <module>
      3 load_state(net, checkpoint)
      4
----> 5 get_rect(net.cuda(), [image_path], 512)

<ipython-input-13-1919f42bf24c> in get_rect(net, images, height_size)
     19         rect_path = image.replace('.%s' % (image.split('.')[-1]), '_rect.txt')
     20         img = cv2.imread(image, cv2.IMREAD_COLOR)
---> 21         orig_img = img.copy()
     22         orig_img = img.copy()
     23         heatmaps, pafs, scale, pad = demo.infer_fast(net, img, height_size, stride, upsample_ratio, cpu=False)

AttributeError: 'NoneType' object has no attribute 'copy'
</code>```

I would greatly appreciate it if someone could give me some help/insight on why this error keeps occurring.  Thank you!

These are my steps:

Open Google Colab notebook from https://shunsukesaito.github.io/PIFuHD/

Create a copy of the notebook to my Google Drive

Run cells [1] to [4]

Upload image in cell [5]

Run all cells afterwards

Title: AttributeError While Using PIFuHD

Body:
I'm trying to use PIFuHD to create a 3d object from an image.

However, I keep getting this error in cell [14]:

AttributeError                            Traceback (most recent call last)
<ipython-input-14-736a0682666b> in <module>
      3 load_state(net, checkpoint)
      4
----> 5 get_rect(net.cuda(), [image_path], 512)

<ipython-input-13-1919f42bf24c> in get_rect(net, images, height_size)
     19         rect_path = image.replace('.%s' % (image.split('.')[-1]), '_rect.txt')
     20         img = cv2.imread(image, cv2.IMREAD_COLOR)
---> 21         orig_img = img.copy()
     22         orig_img = img.copy()
     23         heatmaps, pafs, scale, pad = demo.infer_fast(net, img, height_size, stride, upsample_ratio, cpu=False)

AttributeError: 'NoneType' object has no attribute 'copy'

I would greatly appreciate it if someone could give me some help/insight on why this error keeps occurring.  Thank you!

These are my steps:

Open Google Colab notebook from https://shunsukesaito.github.io/PIFuHD/

Create a copy of the notebook to my Google Drive

Run cells [1] to [4]

Upload image in cell [5]

Run all cells afterwards


问:
AttributeError: 'GridSearchCV' object has no attribute 'best_estimator_'
I'm trying to tune my model using the Grid search model in @kaggle notebook. In order to benefit from the GPU, I used this package hummingbird-ml. Thanks in advance

However, I get the following issue:

AttributeError: 'GridSearchCV' object has no attribute 'best_estimator_'

Here is my code:

```<code>
from hummingbird.ml import convert
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVR
from sklearn.metrics import make_scorer, mean_squared_error
from pprint import pprint
# Hyper-tunning for SVM regressor

import numpy as np

base_svr = SVR()

scorer = make_scorer(mean_squared_error, greater_is_better=False)

param_grid_svr = {'C': [0.01, 0.1,1, 10, 100],
              'gamma': [1,0.1, 0.01, 0.001, 0.0001],
              'kernel': ['linear', 'poly', 'rbf', 'sigmoid', 'precomputed'],
              'epsilon': [0.01, 0.1, 0.2 , 0.3, 1]}
pprint(param_grid_svr)

# Create a GridSearchCV object and fit it to the training data

svr_gs = GridSearchCV(base_svr,param_grid_svr, n_jobs = -1 , scoring=scorer, cv=3   ,refit=True,verbose=2)

# Converting scikit-learn model to PyTorch on CPU

svr_gs_pytorch = convert(svr_gs, 'torch')

# Switching PyTorch from CPU to GPU
%%capture
svr_gs_pytorch.to('cuda')

# Train the model in GPU

svr_gs_pytorch.fit(X_train,y_train)

# print best parameter after tuning
svr_gs_pytorch.best_params_

</code>```

Body:
I'm trying to tune my model using the Grid search model in @kaggle notebook. In order to benefit from the GPU, I used this package hummingbird-ml. Thanks in advance

However, I get the following issue:

AttributeError: 'GridSearchCV' object has no attribute 'best_estimator_'

Here is my code:

from hummingbird.ml import convert
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVR
from sklearn.metrics import make_scorer, mean_squared_error
from pprint import pprint
# Hyper-tunning for SVM regressor

import numpy as np

base_svr = SVR()

scorer = make_scorer(mean_squared_error, greater_is_better=False)

param_grid_svr = {'C': [0.01, 0.1,1, 10, 100],
              'gamma': [1,0.1, 0.01, 0.001, 0.0001],
              'kernel': ['linear', 'poly', 'rbf', 'sigmoid', 'precomputed'],
              'epsilon': [0.01, 0.1, 0.2 , 0.3, 1]}
pprint(param_grid_svr)

# Create a GridSearchCV object and fit it to the training data

svr_gs = GridSearchCV(base_svr,param_grid_svr, n_jobs = -1 , scoring=scorer, cv=3   ,refit=True,verbose=2)

# Converting scikit-learn model to PyTorch on CPU

svr_gs_pytorch = convert(svr_gs, 'torch')

# Switching PyTorch from CPU to GPU
%%capture
svr_gs_pytorch.to('cuda')

# Train the model in GPU

svr_gs_pytorch.fit(X_train,y_train)

# print best parameter after tuning
svr_gs_pytorch.best_params_