问:
How to update object field in nexted array in mongodb with mongotemplate
I write the query and test in mongo command line and it works.
I am unable to convert this request in my java code.
I am trying to write this request in my spring boot application using mongotemplate uncessfully.

my pom.xml look like

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>LibraryManagementSystem</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>LibraryManagementSystem</name>
    <description>LibraryManagementSystem</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

My collection is Adherants and look like this

```<code>[
    {
        "id": "63aff5f050b6ec743a62e56d",
        "nom": "John",
        "prenom": "Doe",
        "email": "johndoea@gmail.com",
        "password": null,
        "dateNaissance": "1999-12-14T00:00:00.000+00:00",
        "adresse": {
            "rue": "123 Fake Street",
            "codePostal": 12546,
            "ville": "Fake city",
            "pays": "Fake country"
        },
        "emprunts": [
            {
                "livreId": "63aea1753063d62d542d832a",
                "detailDesEmprunts": [
                    {
                        "dateEmprunt": "2022-12-29T00:00:00.000+00:00",
                        "dateRetour": "2023-02-28T00:00:00.000+00:00",
                        "statutEmprunt": "ATTENTE"
                    }
                ]
            }
        ]
    },
    {
        "id": "63aeb3e0d9f3096a17de94a2",
        "nom": "Johny",
        "prenom": "Dash",
        "email": "johny@gmail.com",
        "password": null,
        "dateNaissance": "1998-12-14T00:00:00.000+00:00",
        "adresse": {
            "rue": "123 Fake Street",
            "codePostal": 12546,
            "ville": "Fake city 2",
            "pays": "Fake country 3"
        },
        "emprunts": [
            {
                "livreId": "63aea4653063d62d542d832d",
                "detailDesEmprunts": [
                    {
                        "dateEmprunt": "2023-01-15T00:00:00.000+00:00",
                        "dateRetour": "2023-01-22T00:00:00.000+00:00",
                        "statutEmprunt": "VALIDE"
                    },
                    {
                        "dateEmprunt": "2023-01-15T00:00:00.000+00:00",
                        "dateRetour": "2023-01-22T00:00:00.000+00:00",
                        "statutEmprunt": "VALIDE"
                    },
                    {
                        "dateEmprunt": "2023-01-22T00:00:00.000+00:00",
                        "dateRetour": "2023-01-25T00:00:00.000+00:00",
                        "statutEmprunt": "ATTENTE"
                    }
                ]
            },
            {
                "livreId": "63aea4653063d62d542d832e",
                "detailDesEmprunts": [
                    {
                        "dateEmprunt": "2023-01-15T00:00:00.000+00:00",
                        "dateRetour": "2023-01-22T00:00:00.000+00:00",
                        "statutEmprunt": "ATTENTE"
                    }
                ]
            },
            {
                "livreId": "63aea4653063d62d542d832e",
                "detailDesEmprunts": [
                    {
                        "dateEmprunt": "2023-01-15T00:00:00.000+00:00",
                        "dateRetour": "2023-01-22T00:00:00.000+00:00",
                        "statutEmprunt": "ATTENTE"
                    }
                ]
            },
            {
                "livreId": "63aea4653063d62d542d83oo",
                "detailDesEmprunts": [
                    {
                        "dateEmprunt": "2023-01-22T00:00:00.000+00:00",
                        "dateRetour": "2023-01-25T00:00:00.000+00:00",
                        "statutEmprunt": "REFUSE"
                    }
                ]
            }
        ]
    }
]

</code>```

What I want to do is to update statutEmprunt from ATTENTE to VALIDE for Adherant with id : 63aeb3e0d9f3096a17de94a2  and livreId = 63aea4653063d62d542d832d

I write the query in mongosh command line :

```<code>db.Adherants.updateOne(
    {  "_id": ObjectId("63aeb3e0d9f3096a17de94a2")},
    {
        "$set":
        {
            "emprunts.$[list].detailDesEmprunts.$[detailDesEmprunts].statutEmprunt": "VALIDE"
        }
    },
    {
        "multi": false,
        "upsert":false,
        arrayFilters: [
            {
                "list.livreId": {
                    "$eq": "63aea4653063d62d542d832e"
                }
            },
                {
                    "detailDesEmprunts.statutEmprunt": {
                      "$eq": "ATTENTE"
                    }
                  }
        ]
    }
)
</code>```

This is my java code but it doesn't work and i don't know what am missing

```<code>Query query = new Query();
query.addCriteria(Criteria.where("id").is(new ObjectId(adherantId)));

Update update = new Update();
update.set("emprunts.$[list].detailDesEmprunts.$[detailDesEmprunts].statutEmprunt", "VALIDE");

update.filterArray("list.livreId", livreId)
        .filterArray("detailDesEmprunts.statutEmprunt","ATTENTE");
mongoTemplate.findAndModify(query, update, Adherant.class);
</code>```

I try also

```<code>mongoTemplate.findAndModify(query, update, Adherant.class);
</code>```

Body:
I write the query and test in mongo command line and it works.
I am unable to convert this request in my java code.
I am trying to write this request in my spring boot application using mongotemplate uncessfully.

my pom.xml look like

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>LibraryManagementSystem</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>LibraryManagementSystem</name>
    <description>LibraryManagementSystem</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

My collection is Adherants and look like this

[
    {
        "id": "63aff5f050b6ec743a62e56d",
        "nom": "John",
        "prenom": "Doe",
        "email": "johndoea@gmail.com",
        "password": null,
        "dateNaissance": "1999-12-14T00:00:00.000+00:00",
        "adresse": {
            "rue": "123 Fake Street",
            "codePostal": 12546,
            "ville": "Fake city",
            "pays": "Fake country"
        },
        "emprunts": [
            {
                "livreId": "63aea1753063d62d542d832a",
                "detailDesEmprunts": [
                    {
                        "dateEmprunt": "2022-12-29T00:00:00.000+00:00",
                        "dateRetour": "2023-02-28T00:00:00.000+00:00",
                        "statutEmprunt": "ATTENTE"
                    }
                ]
            }
        ]
    },
    {
        "id": "63aeb3e0d9f3096a17de94a2",
        "nom": "Johny",
        "prenom": "Dash",
        "email": "johny@gmail.com",
        "password": null,
        "dateNaissance": "1998-12-14T00:00:00.000+00:00",
        "adresse": {
            "rue": "123 Fake Street",
            "codePostal": 12546,
            "ville": "Fake city 2",
            "pays": "Fake country 3"
        },
        "emprunts": [
            {
                "livreId": "63aea4653063d62d542d832d",
                "detailDesEmprunts": [
                    {
                        "dateEmprunt": "2023-01-15T00:00:00.000+00:00",
                        "dateRetour": "2023-01-22T00:00:00.000+00:00",
                        "statutEmprunt": "VALIDE"
                    },
                    {
                        "dateEmprunt": "2023-01-15T00:00:00.000+00:00",
                        "dateRetour": "2023-01-22T00:00:00.000+00:00",
                        "statutEmprunt": "VALIDE"
                    },
                    {
                        "dateEmprunt": "2023-01-22T00:00:00.000+00:00",
                        "dateRetour": "2023-01-25T00:00:00.000+00:00",
                        "statutEmprunt": "ATTENTE"
                    }
                ]
            },
            {
                "livreId": "63aea4653063d62d542d832e",
                "detailDesEmprunts": [
                    {
                        "dateEmprunt": "2023-01-15T00:00:00.000+00:00",
                        "dateRetour": "2023-01-22T00:00:00.000+00:00",
                        "statutEmprunt": "ATTENTE"
                    }
                ]
            },
            {
                "livreId": "63aea4653063d62d542d832e",
                "detailDesEmprunts": [
                    {
                        "dateEmprunt": "2023-01-15T00:00:00.000+00:00",
                        "dateRetour": "2023-01-22T00:00:00.000+00:00",
                        "statutEmprunt": "ATTENTE"
                    }
                ]
            },
            {
                "livreId": "63aea4653063d62d542d83oo",
                "detailDesEmprunts": [
                    {
                        "dateEmprunt": "2023-01-22T00:00:00.000+00:00",
                        "dateRetour": "2023-01-25T00:00:00.000+00:00",
                        "statutEmprunt": "REFUSE"
                    }
                ]
            }
        ]
    }
]

What I want to do is to update statutEmprunt from ATTENTE to VALIDE for Adherant with id : 63aeb3e0d9f3096a17de94a2  and livreId = 63aea4653063d62d542d832d

I write the query in mongosh command line :

db.Adherants.updateOne(
    {  "_id": ObjectId("63aeb3e0d9f3096a17de94a2")},
    {
        "$set":
        {
            "emprunts.$[list].detailDesEmprunts.$[detailDesEmprunts].statutEmprunt": "VALIDE"
        }
    },
    {
        "multi": false,
        "upsert":false,
        arrayFilters: [
            {
                "list.livreId": {
                    "$eq": "63aea4653063d62d542d832e"
                }
            },
                {
                    "detailDesEmprunts.statutEmprunt": {
                      "$eq": "ATTENTE"
                    }
                  }
        ]
    }
)

This is my java code but it doesn't work and i don't know what am missing

Query query = new Query();
query.addCriteria(Criteria.where("id").is(new ObjectId(adherantId)));

Update update = new Update();
update.set("emprunts.$[list].detailDesEmprunts.$[detailDesEmprunts].statutEmprunt", "VALIDE");

update.filterArray("list.livreId", livreId)
        .filterArray("detailDesEmprunts.statutEmprunt","ATTENTE");
mongoTemplate.findAndModify(query, update, Adherant.class);

I try also

mongoTemplate.findAndModify(query, update, Adherant.class);


来源: stackexchange

问:
I cannot install package spatstat.data. Is it possible to download the zip file and copy and paste in the R folder library?
new error messageI have updated the package spatstat, which is divided into various packages. All of them are updated except one, spatstat.data. I have tried install.packages("spatstat.data") and update.packages("spatstat.data")

Error Message

My question is: is it possible to download the spatstat.data zip file from cran, unzip the folder, copy all the folders and paste them to the right library?

I have seen this option in another post, which I wonder if will work, install.packages("name of the package.zip", repos = NULL)

I am using windows 10 and R 4.0.3 (updated to 4.2.2). I am using QGIS.

ContentLicense: CC BY-SA 4.0


问:
I keep having this error when i try to read an .xlsx file on jupyter notebook in my Android phone . i am a newbie to both jupyter and stack overflow
Code
#importing pandas and numpy
import pandas as pd
import numpy as np

pwd
'/storage/emulated/0'

df = pd.read_excel("final_allocation2020.xlsx")

FileNotFoundError                         Traceback (most recent call last)

Cell In[21], line 1

----> 1 df = pd.read_excel("final_allocation2020.xlsx")

File /data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/pandas/util/_decorators.py:311, in deprecate_nonkeyword_arguments..decorate..wrapper(*args, **kwargs)

```<code>305 if len(args) > num_allow_args:

306     warnings.warn(

307         msg.format(arguments=arguments),

308         FutureWarning,

309         stacklevel=stacklevel,

310     )
</code>```

--> 311 return func(*args, **kwargs)

File /data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/pandas/io/excel/_base.py:364, in read_excel(io, sheet_name, header, names, index_col, usecols, squeeze, dtype, engine, converters, true_values, false_values, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, parse_dates, date_parser, thousands, comment, skipfooter, convert_float, mangle_dupe_cols, storage_options)

```<code>362 if not isinstance(io, ExcelFile):

363     should_close = True
</code>```

--> 364     io = ExcelFile(io, storage_options=storage_options, engine=engine)

```<code>365 elif engine and engine != io.engine:

366     raise ValueError(

367         "Engine should not be specified when passing "

368         "an ExcelFile - ExcelFile already has the engine set"

369     )
</code>```

File /data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/pandas/io/excel/_base.py:1191, in ExcelFile.init(self, path_or_buffer, engine, storage_options)

1189     ext = "xls"`

```<code>your text`
</code>```

1190 else:

-> 1191     ext = inspect_excel_format(

1192         content_or_path=path_or_buffer, storage_options=storage_options

1193     )

1194     if ext is None:

1195         raise ValueError(

1196             "Excel file format cannot be determined, you must specify "

1197             "an engine manually."

1198         )

File /data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/pandas/io/excel/_base.py:1070, in inspect_excel_format(content_or_path, storage_options)

1067 if isinstance(content_or_path, bytes):

1068     content_or_path = BytesIO(content_or_path)

-> 1070 with get_handle(

1071     content_or_path, "rb", storage_options=storage_options, is_text=False

1072 ) as handle:

1073     stream = handle.handle

1074     stream.seek(0)

File /data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/pandas/io/common.py:711, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)

```<code>702         handle = open(

703             handle,

704             ioargs.mode,
</code>```

(...)

```<code>707             newline="",

708         )

709     else:

710         # Binary mode
</code>```

--> 711         handle = open(handle, ioargs.mode)

```<code>712     handles.append(handle)

714 # Convert BytesIO or file objects passed with an encoding
</code>```

FileNotFoundError: [Errno 2] No such file or directory: 'final_allocation2020.xlsx'

Body:
Code
#importing pandas and numpy
import pandas as pd
import numpy as np

pwd
'/storage/emulated/0'

df = pd.read_excel("final_allocation2020.xlsx")

FileNotFoundError                         Traceback (most recent call last)

Cell In[21], line 1

----> 1 df = pd.read_excel("final_allocation2020.xlsx")

File /data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/pandas/util/_decorators.py:311, in deprecate_nonkeyword_arguments..decorate..wrapper(*args, **kwargs)

305 if len(args) > num_allow_args:

306     warnings.warn(

307         msg.format(arguments=arguments),

308         FutureWarning,

309         stacklevel=stacklevel,

310     )

--> 311 return func(*args, **kwargs)

File /data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/pandas/io/excel/_base.py:364, in read_excel(io, sheet_name, header, names, index_col, usecols, squeeze, dtype, engine, converters, true_values, false_values, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, parse_dates, date_parser, thousands, comment, skipfooter, convert_float, mangle_dupe_cols, storage_options)

362 if not isinstance(io, ExcelFile):

363     should_close = True

--> 364     io = ExcelFile(io, storage_options=storage_options, engine=engine)

365 elif engine and engine != io.engine:

366     raise ValueError(

367         "Engine should not be specified when passing "

368         "an ExcelFile - ExcelFile already has the engine set"

369     )

File /data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/pandas/io/excel/_base.py:1191, in ExcelFile.init(self, path_or_buffer, engine, storage_options)

1189     ext = "xls"`

your text`

1190 else:

-> 1191     ext = inspect_excel_format(

1192         content_or_path=path_or_buffer, storage_options=storage_options

1193     )

1194     if ext is None:

1195         raise ValueError(

1196             "Excel file format cannot be determined, you must specify "

1197             "an engine manually."

1198         )

File /data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/pandas/io/excel/_base.py:1070, in inspect_excel_format(content_or_path, storage_options)

1067 if isinstance(content_or_path, bytes):

1068     content_or_path = BytesIO(content_or_path)

-> 1070 with get_handle(

1071     content_or_path, "rb", storage_options=storage_options, is_text=False

1072 ) as handle:

1073     stream = handle.handle

1074     stream.seek(0)

File /data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/pandas/io/common.py:711, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)

702         handle = open(

703             handle,

704             ioargs.mode,

(...)

707             newline="",

708         )

709     else:

710         # Binary mode

--> 711         handle = open(handle, ioargs.mode)

712     handles.append(handle)

714 # Convert BytesIO or file objects passed with an encoding

FileNotFoundError: [Errno 2] No such file or directory: 'final_allocation2020.xlsx'


问:
Need Help Regarding This Query in django model
```<code>class Post(models.Model):
    post_uuid = models.UUIDField(default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User, related_name='post_model', on_delete=models.CASCADE)
    post_categories = models.ManyToManyField(
        'Categories', through='PostCategories', blank=True)
    created_on = models.DateTimeField(default=timezone.now)
    updated_by = models.DateTimeField(null=True, blank=True)
    updated_on = models.DateTimeField(null=True, blank=True)
    deleted_by = models.DateTimeField(null=True, blank=True)
    deleted_on = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-created_on"]
        indexes = [
                models.Index(fields=['post_uuid',]),
                models.Index(fields=['created_on',]),
            ]

    def __str__(self):
        return '{}'.format(self.id)

</code>```
```<code>class PostInLanguages(models.Model):
    post_in_language_uuid = models.UUIDField(
        default=uuid.uuid4, editable=False)
    post = models.ForeignKey(
        Post, related_name='post_language', null=False, on_delete=models.CASCADE)
    language = models.ForeignKey(
        Languages, default=2, on_delete=models.CASCADE)
    is_post_language = models.BooleanField(default=True)
    parent_post_language_id = models.PositiveIntegerField(null=True)
    description = models.CharField(max_length=400, null=True, blank=True)
    like = models.ManyToManyField(
        'User', through='PostLanguageLike', related_name='post_like', blank=True)
    hash_tag = models.ManyToManyField('HashtagName', through='Hashtag', related_name='hash_tag', blank=True)
    created_on = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return '{}'.format(self.post.id)

    class Meta:
        indexes = [
                models.Index(fields=['post_in_language_uuid', 'parent_post_language_id', 'is_post_language']),
            ]
</code>```
```<code>recouch_obj = PostInLanguages.objects.annotate(Count('parent_post_language_id')).filter(parent_post_language_id__count__gte=minimum_recouch,is_post_language=False).values_list("parent_post_language_id")

</code>```

Can anyone help to figure out what will this query return
I just need postinlanguage object query set with minimum recouch filter

Is_lang_post = True means this is a post
If false means this is post of another post that means recouch

Body:
class Post(models.Model):
    post_uuid = models.UUIDField(default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User, related_name='post_model', on_delete=models.CASCADE)
    post_categories = models.ManyToManyField(
        'Categories', through='PostCategories', blank=True)
    created_on = models.DateTimeField(default=timezone.now)
    updated_by = models.DateTimeField(null=True, blank=True)
    updated_on = models.DateTimeField(null=True, blank=True)
    deleted_by = models.DateTimeField(null=True, blank=True)
    deleted_on = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-created_on"]
        indexes = [
                models.Index(fields=['post_uuid',]),
                models.Index(fields=['created_on',]),
            ]

    def __str__(self):
        return '{}'.format(self.id)

class PostInLanguages(models.Model):
    post_in_language_uuid = models.UUIDField(
        default=uuid.uuid4, editable=False)
    post = models.ForeignKey(
        Post, related_name='post_language', null=False, on_delete=models.CASCADE)
    language = models.ForeignKey(
        Languages, default=2, on_delete=models.CASCADE)
    is_post_language = models.BooleanField(default=True)
    parent_post_language_id = models.PositiveIntegerField(null=True)
    description = models.CharField(max_length=400, null=True, blank=True)
    like = models.ManyToManyField(
        'User', through='PostLanguageLike', related_name='post_like', blank=True)
    hash_tag = models.ManyToManyField('HashtagName', through='Hashtag', related_name='hash_tag', blank=True)
    created_on = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return '{}'.format(self.post.id)

    class Meta:
        indexes = [
                models.Index(fields=['post_in_language_uuid', 'parent_post_language_id', 'is_post_language']),
            ]

recouch_obj = PostInLanguages.objects.annotate(Count('parent_post_language_id')).filter(parent_post_language_id__count__gte=minimum_recouch,is_post_language=False).values_list("parent_post_language_id")

Can anyone help to figure out what will this query return
I just need postinlanguage object query set with minimum recouch filter

Is_lang_post = True means this is a post
If false means this is post of another post that means recouch


问:
Load colors array from external file
I want to load predefined colors into my p5js file.

I tried the following:

let module = require('./colors.js');

// noprotect
function setup() {
  createCanvas(windowWidth, windowHeight);

  // generate background
  colorMode(HSB);
  background(5, 10, 100);

  colorization(module.colors);

}

function colorization() {

  // 2. colors from file
  let colorArr = module.colors;
  console.log(colorArr[1])

  const randomElement = colorArr[Math.floor(Math.random() * colorArr.length)];
  console.log(colorArr[randomElement])

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.sound.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/simple-statistics/7.8.0/simple-statistics.min.js" integrity="sha512-xDFZFTH4OUC3OXrn92+YDyIq7VOQDTSAfcAy2kc9h9Wp/BiGwGVPDCDT2CXy6Aml2j+8AMX98jgdk5gZPcsfbw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  <link rel="stylesheet" type="text/css" href="style.css">
  <meta charset="utf-8" />

</head>

<body>
  <div id="palette"></div>
  <script src="sketch.js"></script>
</body>

</html></code>```

The colors I want to load are in my colors.js file:

```<code>exports.colors = [
  "#c0a8a8",
  "#a8a890",
  "#90a8c0",
  "#d8d8d8",
  "#90c0d8",
  "#f0f0f0",
  "#a8c0c0",
  "#30a8c0",
  "#d89078",
  "#f09000",
  "#009090",
  "#fffff0",
  "#a8d8d8",
];

</code>```

I get the error ReferenceError: require is not defined.

Any suggestions how to load the array of colors into my code?

I appreciate your replies!

Title: Load colors array from external file

Body:
I want to load predefined colors into my p5js file.

I tried the following:

let module = require('./colors.js');

// noprotect
function setup() {
  createCanvas(windowWidth, windowHeight);

  // generate background
  colorMode(HSB);
  background(5, 10, 100);

  colorization(module.colors);

}

function colorization() {

  // 2. colors from file
  let colorArr = module.colors;
  console.log(colorArr[1])

  const randomElement = colorArr[Math.floor(Math.random() * colorArr.length)];
  console.log(colorArr[randomElement])

}

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="style.css">
  <meta charset="utf-8" />

The colors I want to load are in my colors.js file:

exports.colors = [
  "#c0a8a8",
  "#a8a890",
  "#90a8c0",
  "#d8d8d8",
  "#90c0d8",
  "#f0f0f0",
  "#a8c0c0",
  "#30a8c0",
  "#d89078",
  "#f09000",
  "#009090",
  "#fffff0",
  "#a8d8d8",
];

I get the error ReferenceError: require is not defined.

Any suggestions how to load the array of colors into my code?

I appreciate your replies!


问:
sklearn KMeans attributes and methods
What is the difference between using the kmeans.labels_ upon kmeans.fit(x) and using labels = kmeans.predict(x)?
It generates different results sometimes and I don't understand why.

from scipy.spatial.distance import squareform
from sklearn.cluster import KMeans
import numpy as np

epsilon = 10**-16
a, b = 1 + epsilon, 1 - epsilon
d1 = np.array([[0, 1, a, 5, 5],[1, 0, 3, 5, 5],[a, 3, 0, 3, b],[5, 5, 3, 0, 1],[5, 5, b, 1, 0]])

clustering = KMeans(n_clusters=4, random_state=9)
clustering.fit(squareform(d1).reshape(-1,1))
print(clustering.labels_)
print(clustering.predict(squareform(d1).reshape(-1,1)))
print("####################################################")
clustering = KMeans(n_clusters=4, random_state=9)
clustering.fit(squareform(d1*5).reshape(-1,1))
print(clustering.labels_)
print(clustering.predict(squareform(d1).reshape(-1,1)))
```
<p>Output:</p>
```[1 1 0 0 2 0 0 2 1 1]
[1 1 0 0 2 0 0 2 1 1]
####################################################
[1 1 0 0 2 0 0 2 1 1]
[1 1 1 1 1 1 1 1 1 1]
```

Title: sklearn KMeans attributes and methods

Body:
What is the difference between using the kmeans.labels_ upon kmeans.fit(x) and using labels = kmeans.predict(x)?
It generates different results sometimes and I don't understand why.

from scipy.spatial.distance import squareform
from sklearn.cluster import KMeans
import numpy as np

epsilon = 10**-16
a, b = 1 + epsilon, 1 - epsilon
d1 = np.array([[0, 1, a, 5, 5],[1, 0, 3, 5, 5],[a, 3, 0, 3, b],[5, 5, 3, 0, 1],[5, 5, b, 1, 0]])

clustering = KMeans(n_clusters=4, random_state=9)
clustering.fit(squareform(d1).reshape(-1,1))
print(clustering.labels_)
print(clustering.predict(squareform(d1).reshape(-1,1)))
print("####################################################")
clustering = KMeans(n_clusters=4, random_state=9)
clustering.fit(squareform(d1*5).reshape(-1,1))
print(clustering.labels_)
print(clustering.predict(squareform(d1).reshape(-1,1)))

Output:

[1 1 0 0 2 0 0 2 1 1]
[1 1 0 0 2 0 0 2 1 1]
####################################################
[1 1 0 0 2 0 0 2 1 1]
[1 1 1 1 1 1 1 1 1 1]


问:
Android Hilt Tests failing caused by ClassCastException
I am facing below issue when I am using hilt android test in my application.

java.lang.ClassCastException: android.app.Application cannot be cast to com.dubaiculture.infrastructure.ApplicationEntry
at com.dubaiculture.ui.base.BaseActivity.onCreate(BaseActivity.kt:175)
at com.dubaiculture.ui.preLogin.PreLoginActivity.onCreate(PreLoginActivity.kt:26)
at android.app.Activity.performCreate(Activity.java:8051)
at android.app.Activity.performCreate(Activity.java:8031)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at androidx.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:730)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

I am casting this (applicationEntry = application as ApplicationEntry) in BaseActivity.kt.this is the cause of issue.
Here is My BaseActivity.kt class.

```<code>package com.dubaiculture.ui.base

import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import android.widget.CheckBox
import androidx.annotation.IdRes
import androidx.core.content.res.ResourcesCompat
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.akexorcist.localizationactivity.ui.LocalizationActivity
import com.dubaiculture.BuildConfig
import com.dubaiculture.R
import com.dubaiculture.infrastructure.ApplicationEntry
import com.dubaiculture.ui.preLogin.login.LoginFragment
import com.dubaiculture.utils.Constants
import com.dubaiculture.utils.ProgressDialog
import com.dubaiculture.utils.event.EventUtilFunctions
import com.dubaiculture.utils.event.EventUtilFunctions.showAlert
import com.dubaiculture.utils.event.EventUtilFunctions.showLoader
import com.dubaiculture.utils.event.EventUtilFunctions.showSnackbar
import com.dubaiculture.utils.event.EventUtilFunctions.showToast
import com.dubaiculture.utils.event.UiEvent
import com.squareup.otto.Bus
import com.facebook.appevents.AppEventsLogger
import com.github.javiersantos.appupdater.AppUpdater

abstract class BaseActivity : LocalizationActivity() {
    lateinit var applicationEntry: ApplicationEntry
    protected lateinit var bus: Bus
    protected var isBusRegistered: Boolean = false
    private var customProgressDialog: ProgressDialog? = null
    protected lateinit var navController: NavController

    lateinit var checkBox: CheckBox
    protected var mPrevConfig: Configuration? = null

    override fun onResume() {
        super.onResume()
        if (BuildConfig.BUILD_TYPE == "release") {
            val appUpdater = AppUpdater(this)
                .setCancelable(true)
                .setButtonDismiss("")
                .setButtonDoNotShowAgain("")
            appUpdater.start()
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        configurationChanged(newConfig)
        mPrevConfig = Configuration(newConfig)

    }

    open fun logSentFriendRequestEvent() {
        val fbLogger = AppEventsLogger.newLogger(baseContext)
        fbLogger.logEvent("sentFriendRequest")
    }

    protected fun configurationChanged(newConfig: Configuration?) {
        newConfig?.let {
            if (isNightConfigChanged(it)) { // night mode has changed
                applicationEntry.preferenceRepository.isDarkTheme = isOnDarkMode(it)
                recreate()
                // do your thing
            }
        }

    }

    protected fun isNightConfigChanged(newConfig: Configuration): Boolean {
        return newConfig.diff(mPrevConfig) and ActivityInfo.CONFIG_UI_MODE != 0 && isOnDarkMode(
            newConfig
        ) != isOnDarkMode(mPrevConfig!!)
    }

    fun isOnDarkMode(configuration: Configuration): Boolean {
        return configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
    }

    protected fun getDrawableFromId(resId: Int?): Drawable? {
        resId?.let {
            return if (it == 0) null
            else ResourcesCompat.getDrawable(resources, it, null)
        }
        return null
    }

    fun showAlert(
        message: String = "",
        title: String = Constants.Alert.DEFAULT_TITLE,
        textPositive: String = Constants.Alert.DEFAULT_TEXT_POSITIVE,
        textNegative: String? = null,
        actionNegative: (() -> Unit)? = null,
        actionPositive: (() -> Unit)? = null,
        isInternet: Boolean = false,
        application: ApplicationEntry? = null
    ) {
        showAlert(
            message = message,
            context = this,
            title = title,
            textPositive = textPositive,
            textNegative = textNegative,
            actionPositive = actionPositive,
            isInternet = isInternet,
            application = application

        )
    }

    fun openEmailbox(email: String) {
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "plain/text"
        intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
        startActivity(Intent.createChooser(intent, ""))
    }

    fun openDiallerBox(number: String? = null) {
        val intent = Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", number, null))
        startActivity(intent)
    }

    open fun adjustFontScale(configuration: Configuration) {
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
        if (configuration.fontScale > 1.30) {
            configuration.fontScale = 1.30f
            val metrics = resources.displayMetrics
            val wm = getSystemService(WINDOW_SERVICE) as WindowManager?
            wm!!.defaultDisplay.getMetrics(metrics)
            metrics.scaledDensity = configuration.fontScale * metrics.density
            resources.updateConfiguration(configuration, metrics)
        }
    }

    fun isDark(configuration: Configuration) {
        val preferenceRepository = applicationEntry.preferenceRepository
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val nightMode = configuration.uiMode.and(Configuration.UI_MODE_NIGHT_MASK)
            when (nightMode) {
                Configuration.UI_MODE_NIGHT_YES -> {
                    // Night mode is active, we're using dark theme
                    preferenceRepository.isDarkTheme = true
                }
                Configuration.UI_MODE_NIGHT_NO -> {
                    // Night mode is not active, we're using the light theme
                    preferenceRepository.isDarkTheme = false
                }
                else -> {
                    preferenceRepository.isDarkTheme = false
//                   preferenceRepository.isDarkTheme = isNightModeActive(this)
                }
            }
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        applicationEntry = application as ApplicationEntry
        applicationEntry.preferenceRepository.isDarkTheme = isOnDarkMode(resources.configuration)
        mPrevConfig = Configuration(resources.configuration)
//        isDark(mPrevConfig!!)

        darkModeAccess()
        bus = applicationEntry.bus
        applicationEntry.auth.locale = getCurrentLanguage().language
        bus.register(this)
        isBusRegistered = true
        customProgressDialog = ProgressDialog(this)

    }

    fun subscribeUiEvents(baseViewModel: BaseViewModel) {
        baseViewModel.uiEvents.observe(this, {
            it.getContentIfNotHandled()
                ?.let { event ->
                    when (event) {
                        is UiEvent.ShowAlert -> {
                            showAlert(event.message, this)

                        }
                        is UiEvent.ShowToast -> {
                            showToast(event.message, this)
                        }
                        is UiEvent.ShowLoader -> {
                            showLoader(event.show, customProgressDialog)
                        }
                        is UiEvent.ShowSnackbar -> {
                            showSnackbar(
                                findViewById(android.R.id.content),
                                event.message,
                                event.action
                            )
                        }
                        is UiEvent.ShowErrorDialog -> {
                            EventUtilFunctions.showErrorDialog(
                                event.message,
                                colorBg = event.colorBg,
                                context = this
                            )
                        }
                    }
                }
        })
    }

    override fun onDestroy() {
        super.onDestroy()

        if (customProgressDialog != null) {
            if (customProgressDialog!!.isShowing) {
                customProgressDialog!!.dismiss()
            }
            customProgressDialog = null
        }

        if (isBusRegistered) {
            bus.unregister(this)
            isBusRegistered = false
        }

    }

    override fun finish() {
        super.finish()
        if (customProgressDialog != null) {
            customProgressDialog = null
        }
        if (isBusRegistered) {
            bus.unregister(this)
            isBusRegistered = false
        }
    }

    fun navigate(@IdRes resId: Int, bundle: Bundle? = null) {
        navController.navigate(resId, bundle)
    }

    protected fun getNavControllerFun(int: Int): NavController {
        val navHostFragment =
            supportFragmentManager.findFragmentById(int) as NavHostFragment
        navController = navHostFragment.navController
        return navController
    }

    fun darkModeAccess() {
        (application as ApplicationEntry).preferenceRepository
            .nightModeLive.observe(this) { nightMode ->
                nightMode?.let { delegate.localNightMode = it }
            }
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        LoginFragment().apply {
            handleIntent(intent)
        }
    }

}
</code>```

I have tried to make a custom test runner for hilt testing that have mentioned in this link
Hilt Testing

Body:
I am facing below issue when I am using hilt android test in my application.

java.lang.ClassCastException: android.app.Application cannot be cast to com.dubaiculture.infrastructure.ApplicationEntry
at com.dubaiculture.ui.base.BaseActivity.onCreate(BaseActivity.kt:175)
at com.dubaiculture.ui.preLogin.PreLoginActivity.onCreate(PreLoginActivity.kt:26)
at android.app.Activity.performCreate(Activity.java:8051)
at android.app.Activity.performCreate(Activity.java:8031)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at androidx.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:730)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

I am casting this (applicationEntry = application as ApplicationEntry) in BaseActivity.kt.this is the cause of issue.
Here is My BaseActivity.kt class.

package com.dubaiculture.ui.base

import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import android.widget.CheckBox
import androidx.annotation.IdRes
import androidx.core.content.res.ResourcesCompat
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.akexorcist.localizationactivity.ui.LocalizationActivity
import com.dubaiculture.BuildConfig
import com.dubaiculture.R
import com.dubaiculture.infrastructure.ApplicationEntry
import com.dubaiculture.ui.preLogin.login.LoginFragment
import com.dubaiculture.utils.Constants
import com.dubaiculture.utils.ProgressDialog
import com.dubaiculture.utils.event.EventUtilFunctions
import com.dubaiculture.utils.event.EventUtilFunctions.showAlert
import com.dubaiculture.utils.event.EventUtilFunctions.showLoader
import com.dubaiculture.utils.event.EventUtilFunctions.showSnackbar
import com.dubaiculture.utils.event.EventUtilFunctions.showToast
import com.dubaiculture.utils.event.UiEvent
import com.squareup.otto.Bus
import com.facebook.appevents.AppEventsLogger
import com.github.javiersantos.appupdater.AppUpdater

abstract class BaseActivity : LocalizationActivity() {
    lateinit var applicationEntry: ApplicationEntry
    protected lateinit var bus: Bus
    protected var isBusRegistered: Boolean = false
    private var customProgressDialog: ProgressDialog? = null
    protected lateinit var navController: NavController

    lateinit var checkBox: CheckBox
    protected var mPrevConfig: Configuration? = null

    override fun onResume() {
        super.onResume()
        if (BuildConfig.BUILD_TYPE == "release") {
            val appUpdater = AppUpdater(this)
                .setCancelable(true)
                .setButtonDismiss("")
                .setButtonDoNotShowAgain("")
            appUpdater.start()
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        configurationChanged(newConfig)
        mPrevConfig = Configuration(newConfig)

    }

    open fun logSentFriendRequestEvent() {
        val fbLogger = AppEventsLogger.newLogger(baseContext)
        fbLogger.logEvent("sentFriendRequest")
    }

    protected fun configurationChanged(newConfig: Configuration?) {
        newConfig?.let {
            if (isNightConfigChanged(it)) { // night mode has changed
                applicationEntry.preferenceRepository.isDarkTheme = isOnDarkMode(it)
                recreate()
                // do your thing
            }
        }

    }

    protected fun isNightConfigChanged(newConfig: Configuration): Boolean {
        return newConfig.diff(mPrevConfig) and ActivityInfo.CONFIG_UI_MODE != 0 && isOnDarkMode(
            newConfig
        ) != isOnDarkMode(mPrevConfig!!)
    }

    fun isOnDarkMode(configuration: Configuration): Boolean {
        return configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
    }

    protected fun getDrawableFromId(resId: Int?): Drawable? {
        resId?.let {
            return if (it == 0) null
            else ResourcesCompat.getDrawable(resources, it, null)
        }
        return null
    }

    fun showAlert(
        message: String = "",
        title: String = Constants.Alert.DEFAULT_TITLE,
        textPositive: String = Constants.Alert.DEFAULT_TEXT_POSITIVE,
        textNegative: String? = null,
        actionNegative: (() -> Unit)? = null,
        actionPositive: (() -> Unit)? = null,
        isInternet: Boolean = false,
        application: ApplicationEntry? = null
    ) {
        showAlert(
            message = message,
            context = this,
            title = title,
            textPositive = textPositive,
            textNegative = textNegative,
            actionPositive = actionPositive,
            isInternet = isInternet,
            application = application

        )
    }

    fun openEmailbox(email: String) {
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "plain/text"
        intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
        startActivity(Intent.createChooser(intent, ""))
    }

    fun openDiallerBox(number: String? = null) {
        val intent = Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", number, null))
        startActivity(intent)
    }

    open fun adjustFontScale(configuration: Configuration) {
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
        if (configuration.fontScale > 1.30) {
            configuration.fontScale = 1.30f
            val metrics = resources.displayMetrics
            val wm = getSystemService(WINDOW_SERVICE) as WindowManager?
            wm!!.defaultDisplay.getMetrics(metrics)
            metrics.scaledDensity = configuration.fontScale * metrics.density
            resources.updateConfiguration(configuration, metrics)
        }
    }

    fun isDark(configuration: Configuration) {
        val preferenceRepository = applicationEntry.preferenceRepository
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val nightMode = configuration.uiMode.and(Configuration.UI_MODE_NIGHT_MASK)
            when (nightMode) {
                Configuration.UI_MODE_NIGHT_YES -> {
                    // Night mode is active, we're using dark theme
                    preferenceRepository.isDarkTheme = true
                }
                Configuration.UI_MODE_NIGHT_NO -> {
                    // Night mode is not active, we're using the light theme
                    preferenceRepository.isDarkTheme = false
                }
                else -> {
                    preferenceRepository.isDarkTheme = false
//                   preferenceRepository.isDarkTheme = isNightModeActive(this)
                }
            }
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        applicationEntry = application as ApplicationEntry
        applicationEntry.preferenceRepository.isDarkTheme = isOnDarkMode(resources.configuration)
        mPrevConfig = Configuration(resources.configuration)
//        isDark(mPrevConfig!!)

        darkModeAccess()
        bus = applicationEntry.bus
        applicationEntry.auth.locale = getCurrentLanguage().language
        bus.register(this)
        isBusRegistered = true
        customProgressDialog = ProgressDialog(this)

    }

    fun subscribeUiEvents(baseViewModel: BaseViewModel) {
        baseViewModel.uiEvents.observe(this, {
            it.getContentIfNotHandled()
                ?.let { event ->
                    when (event) {
                        is UiEvent.ShowAlert -> {
                            showAlert(event.message, this)

                        }
                        is UiEvent.ShowToast -> {
                            showToast(event.message, this)
                        }
                        is UiEvent.ShowLoader -> {
                            showLoader(event.show, customProgressDialog)
                        }
                        is UiEvent.ShowSnackbar -> {
                            showSnackbar(
                                findViewById(android.R.id.content),
                                event.message,
                                event.action
                            )
                        }
                        is UiEvent.ShowErrorDialog -> {
                            EventUtilFunctions.showErrorDialog(
                                event.message,
                                colorBg = event.colorBg,
                                context = this
                            )
                        }
                    }
                }
        })
    }

    override fun onDestroy() {
        super.onDestroy()

        if (customProgressDialog != null) {
            if (customProgressDialog!!.isShowing) {
                customProgressDialog!!.dismiss()
            }
            customProgressDialog = null
        }

        if (isBusRegistered) {
            bus.unregister(this)
            isBusRegistered = false
        }

    }

    override fun finish() {
        super.finish()
        if (customProgressDialog != null) {
            customProgressDialog = null
        }
        if (isBusRegistered) {
            bus.unregister(this)
            isBusRegistered = false
        }
    }

    fun navigate(@IdRes resId: Int, bundle: Bundle? = null) {
        navController.navigate(resId, bundle)
    }

    protected fun getNavControllerFun(int: Int): NavController {
        val navHostFragment =
            supportFragmentManager.findFragmentById(int) as NavHostFragment
        navController = navHostFragment.navController
        return navController
    }

    fun darkModeAccess() {
        (application as ApplicationEntry).preferenceRepository
            .nightModeLive.observe(this) { nightMode ->
                nightMode?.let { delegate.localNightMode = it }
            }
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        LoginFragment().apply {
            handleIntent(intent)
        }
    }

}

I have tried to make a custom test runner for hilt testing that have mentioned in this link
Hilt Testing


问:
Problems loading caret in RStudio on AWS
I followed the instructions to run R on AWS to solve local memory issues in computing. I would like to run caret but I am running into this error when I try to load the package using library(caret).

Error: package or namespace load failed for ‘caret’ in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]):
namespace ‘rlang’ 0.4.7 is already loaded, but >= 1.0.3 is required

I've restarted my Rstudio session and have uninstalled/re-install rlang but the issue persists. I am suspecting the issue is an outdated version of R because
> sessionInfo() provides:

R version 4.0.2 (2020-06-22)

Platform: x86_64-pc-linux-gnu (64-bit)

Running under: Ubuntu 18.04.5 LTS

Does anyone have any ideas on how to fix the issue?

A similar problem was raised here, but the solution provided did not help.


问:
How to cancel GitHub Action job only for pull request, but not after merging?
I have a GitHub Action which runs when create the pull request (pull_request), and also after merging to the main branch (push):

```<code>name: CodeQL
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true
jobs:
  codeql:
    name: CodeQL
    runs-on: ubuntu-22.04
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Initialize CodeQL
        uses: github/codeql-action/init@v2
        with:
          languages: go
      - name: Autobuild
        uses: github/codeql-action/autobuild@v2
      - name: CodeQL
        uses: github/codeql-action/analyze@v2

</code>```

Inside I am using concurrency:

```<code>concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true
</code>```

Case pull_request

When I update the pull request, it will cancel the previous job, which is great. In the GitHub Actions Summary -> Annotations, it shows

```<code>Canceling since a higher priority waiting request for 'CodeQL-refs/pull/6530/merge' exists
The operation was canceled.
</code>```

Case push

However, sometimes when two pull requests merge in very close time, the new merging to main branch's CodeQL will cancel the previous one too. It shows

```<code>Canceling since a higher priority waiting request for 'CodeQL-refs/heads/main' exists
The operation was canceled.
</code>```

You can see now ${{ github.ref }} will be always same refs/heads/main.

One workaround in my mind is duplicate this GitHub Action and have one for pull_request with concurrency, another one for push without concurrency.

Is there a way to only have one GitHub Action to avoid cancelling after merging to the main branch (only cancel for pull request)? Thanks!

Body:
I have a GitHub Action which runs when create the pull request (pull_request), and also after merging to the main branch (push):

name: CodeQL
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true
jobs:
  codeql:
    name: CodeQL
    runs-on: ubuntu-22.04
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Initialize CodeQL
        uses: github/codeql-action/init@v2
        with:
          languages: go
      - name: Autobuild
        uses: github/codeql-action/autobuild@v2
      - name: CodeQL
        uses: github/codeql-action/analyze@v2

Inside I am using concurrency:

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

Case pull_request

When I update the pull request, it will cancel the previous job, which is great. In the GitHub Actions Summary -> Annotations, it shows

Canceling since a higher priority waiting request for 'CodeQL-refs/pull/6530/merge' exists
The operation was canceled.

Case push

However, sometimes when two pull requests merge in very close time, the new merging to main branch's CodeQL will cancel the previous one too. It shows

Canceling since a higher priority waiting request for 'CodeQL-refs/heads/main' exists
The operation was canceled.

You can see now ${{ github.ref }} will be always same refs/heads/main.

One workaround in my mind is duplicate this GitHub Action and have one for pull_request with concurrency, another one for push without concurrency.

Is there a way to only have one GitHub Action to avoid cancelling after merging to the main branch (only cancel for pull request)? Thanks!


问:
Add custom Meta Data to Woocommerce Filter
I have created Custom fields for WooCommerce product using ACF PRO. I want to filter my products using custom fields but i could not find a way to do it manually.

_custom_field_1
_custom_field_2
_custom_field_3

I find some plugins to achieve this but they have conflict with my theme so i want to do it manually.


问:
Problem in playing video stored in google drive in unity video player
I was working on a project where I need to play a video stored in my google drive storage. I shared the video and made it available for anyone with a link and copied the link and created a direct link for the video. Direct links are required if we want to play the video from drive in unity video player. Everything works fine until it didn't. The video played in unity for about 4-5 times then suddenly it started throwing access denied error. Then after sometime maybe 20-30 mins it starts to work again. I can't understand why its is behaving like this is there a limit to access google drive files or something else.

Yes I can download the video and play it that way but I wanted to just play the video without downloading it.


问:
I am trying to code a hedging EA on mql5 but some function is not working
`//so I am coding this EA on MQL5 and everything works fine until its time to to hedge. look at the //code

```<code>void onTick{
   safetyBuy()
}

void safetyBuy(){
   double openPrice;
   int PositionDirection;
   string TP;
   string sl;
   string volume;
   double secondaryVolume = ReturnVolume("buy");

   ObjectGetString(_Symbol,"TP points",OBJPROP_TEXT,0,TP);
   ObjectGetString(_Symbol,"stopLoss",OBJPROP_TEXT,0,sl);
   ObjectGetString(_Symbol,"volume", OBJPROP_TEXT,0,volume);
    for(int i = PositionsTotal() - 1; i>=0; i--){
      if(PositionsTotal()>0){
         ulong PositionTicket = PositionGetTicket(i);
         PositionDirection =(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
         if(PositionDirection == POSITION_TYPE_BUY){
            openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
         }
      }
   }
   if(ReturnVolume("sell") > ReturnVolume("Buy") && OrdersTotal() == 0){
      trade.BuyLimit(secondaryVolume, openPrice, _Symbol, 0,0,ORDER_TIME_GTC,0,NULL);
   }
}

double ReturnVolume(string postype){
   double TradeVolume;
   int PositionDirection;
   ulong PositionTicket;
   for(int i = PositionsTotal() - 1; i>=0; i--){
      PositionTicket = PositionGetTicket(i);
      PositionDirection =(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
      if(postype == "buy" && PositionDirection == POSITION_TYPE_BUY){
         TradeVolume += PositionGetDouble(POSITION_VOLUME);
      }
      if(postype == "sell" && PositionDirection == POSITION_TYPE_SELL){
         TradeVolume += PositionGetDouble(POSITION_VOLUME);
      }
   }

   return TradeVolume;

}
</code>```

the problem is when I am testing my EA when the buy limit order is supposed to open nothing happens and I checked the journal to see for runtime errors but there are none its as if the program doesnt see my instructions, any help would be appreciated. Thanks in advance. (ps the ReturnVolume function works as intended just included it for more clarity)
`

Body:
`//so I am coding this EA on MQL5 and everything works fine until its time to to hedge. look at the //code

void onTick{
   safetyBuy()
}

void safetyBuy(){
   double openPrice;
   int PositionDirection;
   string TP;
   string sl;
   string volume;
   double secondaryVolume = ReturnVolume("buy");

   ObjectGetString(_Symbol,"TP points",OBJPROP_TEXT,0,TP);
   ObjectGetString(_Symbol,"stopLoss",OBJPROP_TEXT,0,sl);
   ObjectGetString(_Symbol,"volume", OBJPROP_TEXT,0,volume);
    for(int i = PositionsTotal() - 1; i>=0; i--){
      if(PositionsTotal()>0){
         ulong PositionTicket = PositionGetTicket(i);
         PositionDirection =(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
         if(PositionDirection == POSITION_TYPE_BUY){
            openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
         }
      }
   }
   if(ReturnVolume("sell") > ReturnVolume("Buy") && OrdersTotal() == 0){
      trade.BuyLimit(secondaryVolume, openPrice, _Symbol, 0,0,ORDER_TIME_GTC,0,NULL);
   }
}

double ReturnVolume(string postype){
   double TradeVolume;
   int PositionDirection;
   ulong PositionTicket;
   for(int i = PositionsTotal() - 1; i>=0; i--){
      PositionTicket = PositionGetTicket(i);
      PositionDirection =(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
      if(postype == "buy" && PositionDirection == POSITION_TYPE_BUY){
         TradeVolume += PositionGetDouble(POSITION_VOLUME);
      }
      if(postype == "sell" && PositionDirection == POSITION_TYPE_SELL){
         TradeVolume += PositionGetDouble(POSITION_VOLUME);
      }
   }

   return TradeVolume;

}

the problem is when I am testing my EA when the buy limit order is supposed to open nothing happens and I checked the journal to see for runtime errors but there are none its as if the program doesnt see my instructions, any help would be appreciated. Thanks in advance. (ps the ReturnVolume function works as intended just included it for more clarity)
`


问:
PERMANOVA - small and unequal sample sizes
I am comparing fish communities at 2 sites (upstream vs downstream) with data collected in two seasons (wet and dry) over several years (2017-2022), with data from the first pair of wet and dry seasons representing the period before a treatment and subsequent data representing periods after the treatment. During each season I sampled each site four times, and recorded abundance of each fish species from each site. I did not conduct sampling during the last dry season due to resource constraints. The community compositions of the two sites over different seasons and periods are visualised in the NMDS biplots.

I am trying to do further analysis using PERMANOVA to look for any spatial-temporal changes in the fish commnities, mainly if the two groups are becoming more similar in the years following the treatment. As there are samples with no fishes recorded I have to remove those samples from the dataset, which means I have only three instead of four replicates in some of the site x season x year groups.

My question is, does it still make sense to use PERMANOVA if I have unequal sample size among groups, given the number of replicates from each are small (3-4)? I am planning to run the test separately for wet and dry seasons, but that means I still need to do two-way (site x year) PERMANOVAs for each of the seasons.

I learned from some of the online discussions that unequal sample size would be a problem for two (or more)-way PERMANOVAs and the problem of unequal sample size would be more prominent when the sample sizes are small. Would be grateful for any comments or insight on this. Thanks a tonne!


问:
How to make own custom Markdown editor with Javascript
I'm working with Laravel 9 to make a forum (like Stackoverflow) and I need to add a custom Markdown editor that can make changes on textarea (bold, italic, inserting code, images, ...)

So I wonder if I have this on my html as the view of the Markdown-editor:

```<code><div class="create__section create__textarea">
    <label class="create__label BMehrBold" for="description">Describe Problem:</label>
    <div class="create__textarea-head">
        <span><i class="icon-Quote"></i></span>
        <span><i class="icon-Bold"></i></span>
        <span><i class="icon-Italic"></i></span>
        <div class="create__textarea-separate"></div>
        <span><i class="icon-Share_Topic"></i></span>
        <span><i class="icon-BlockQuote"></i></span>
        <span><i class="icon-Performatted"></i></span>
        <span><i class="icon-Upload_Files"></i></span>
        <span class="create__textarea-separate"></span>
        <span><i class="icon-Bullet_List"></i></span>
        <span><i class="icon-heading"></i></span>
        <span><i class="icon-Horizontal_Line"></i></span>
        <span><i class="icon-Emoticon"></i></span>
        <span><i class="icon-Settings"></i></span>
        <span><i class="icon-Color_Picker"></i></span>
        <div class="create__textarea-btn">

            <a href="#" class="btn BJadidBold">Preview</a>
        </div>
    </div>
    <textarea class="form-control BKoodakBold" id="description"></textarea>
</div>
</code>```

Then how can I make changes to the <textarea> value when user press on a particular button (for example if he clicks on icon-bold, the Bold event must be applied)...

So if you have any idea about this, please let me know.

Body:
I'm working with Laravel 9 to make a forum (like Stackoverflow) and I need to add a custom Markdown editor that can make changes on textarea (bold, italic, inserting code, images, ...)

So I wonder if I have this on my html as the view of the Markdown-editor:

    Describe Problem:

            Preview

    <textarea class="form-control BKoodakBold" id="description"></textarea>

Then how can I make changes to the <textarea> value when user press on a particular button (for example if he clicks on icon-bold, the Bold event must be applied)...

So if you have any idea about this, please let me know.


问:
if else condition in MongoDB while aggregating
So I have a collection look like this:
interference table

Here I want to search by either AP Name or BSSID, or both (BSSID is in prior).

Here is my code to query AP Name:

```<code>db.Int_Localization.aggregate([
{"$sort":{"ts":-1}},
{"$match": { "essid":"$int","floor":"$Floor","ts":{ "$gte" : "$from", "$lt":"$to"}}},
{"$project": {"_id":0, "AP Name":"$essid","Floor":"$floor","x location 1":"$xloc","y location 1":"$yloc","ts":"$ts"}}
            ])
</code>```

Similarly, here is to query BSSID:

```<code>db.Int_Localization.aggregate([
{"$sort":{"ts":-1}},
{"$match": { "bssid":"$int2","floor":"$Floor","ts":{ "$gte" : "$from", "$lt":"$to"}}},
{"$project": {"_id":0, "AP Name":"$essid","Floor":"$floor","x location 1":"$xloc","y location 1":"$yloc","ts":"$ts"}}
            ])

</code>```

So I want to combine these two codes and make an if condition, in which:

If I type an AP Name to $int, it will show all documents with this AP Name

If I type a BSSID to $int2, it will show all documents with this BSSID

If I type both AP Name and BSSID to $int and $int2, it will show the exact AP Name and BSSID

If I leave $int and $int2 blank, it will show all the documents

Is there any possible solution for this case? Thanks in advance

I tried to develop an application, which queries data from MongoDB server.

Body:
So I have a collection look like this:
interference table

Here I want to search by either AP Name or BSSID, or both (BSSID is in prior).

Here is my code to query AP Name:

db.Int_Localization.aggregate([
{"$sort":{"ts":-1}},
{"$match": { "essid":"$int","floor":"$Floor","ts":{ "$gte" : "$from", "$lt":"$to"}}},
{"$project": {"_id":0, "AP Name":"$essid","Floor":"$floor","x location 1":"$xloc","y location 1":"$yloc","ts":"$ts"}}
            ])

Similarly, here is to query BSSID:

db.Int_Localization.aggregate([
{"$sort":{"ts":-1}},
{"$match": { "bssid":"$int2","floor":"$Floor","ts":{ "$gte" : "$from", "$lt":"$to"}}},
{"$project": {"_id":0, "AP Name":"$essid","Floor":"$floor","x location 1":"$xloc","y location 1":"$yloc","ts":"$ts"}}
            ])

So I want to combine these two codes and make an if condition, in which:

If I type an AP Name to $int, it will show all documents with this AP Name

If I type a BSSID to $int2, it will show all documents with this BSSID

If I type both AP Name and BSSID to $int and $int2, it will show the exact AP Name and BSSID

If I leave $int and $int2 blank, it will show all the documents

Is there any possible solution for this case? Thanks in advance

I tried to develop an application, which queries data from MongoDB server.


问:
Range slider Plotly : How not to add a line
I have the code below, that produce a subplot with a unique range slider. Except i want the range slider to be on row 2, not to create a replicated row2, is there a way to do it?</p>
```<code>import pandas as pd
import plotly.express as px
import plotly.subplots as sp
from datetime import datetime

data1 = [
    [1, datetime(2022, 11, 26)],
    [7, datetime(2022, 11, 29)],
    [4, datetime(2022, 11, 30)],
]
df1 = pd.DataFrame(data1, columns=["value", "date"])

data2 = [
    ["unique_row","a", datetime(2022, 11, 26),datetime(2022, 11, 27)],
    ["unique_row","b", datetime(2022, 11, 27),datetime(2022, 11, 30)],
    ["unique_row","c", datetime(2022, 11, 30),datetime(2022, 12, 2)],
]
df2 = pd.DataFrame(data2, columns=["unique_row","value", "dates_begin","date_end"])

fig1= px.line(df1, x="date", y="value")
fig2 = px.timeline(df2, x_start="dates_begin", x_end="date_end", y="unique_row",         color="value")

fig_sub = sp.make_subplots(rows=2,
                          shared_xaxes=True)

fig_sub.append_trace(fig1['data'][0], row=1, col=1)
fig_sub.append_trace(fig2['data'][0], row=2, col=1)

fig_sub.update_layout(xaxis2_rangeslider_visible=True)
</code>```

Body:
I have the code below, that produce a subplot with a unique range slider. Except i want the range slider to be on row 2, not to create a replicated row2, is there a way to do it?

import pandas as pd
import plotly.express as px
import plotly.subplots as sp
from datetime import datetime

data1 = [
    [1, datetime(2022, 11, 26)],
    [7, datetime(2022, 11, 29)],
    [4, datetime(2022, 11, 30)],
]
df1 = pd.DataFrame(data1, columns=["value", "date"])

data2 = [
    ["unique_row","a", datetime(2022, 11, 26),datetime(2022, 11, 27)],
    ["unique_row","b", datetime(2022, 11, 27),datetime(2022, 11, 30)],
    ["unique_row","c", datetime(2022, 11, 30),datetime(2022, 12, 2)],
]
df2 = pd.DataFrame(data2, columns=["unique_row","value", "dates_begin","date_end"])

fig1= px.line(df1, x="date", y="value")
fig2 = px.timeline(df2, x_start="dates_begin", x_end="date_end", y="unique_row",         color="value")

fig_sub = sp.make_subplots(rows=2,
                          shared_xaxes=True)

fig_sub.append_trace(fig1['data'][0], row=1, col=1)
fig_sub.append_trace(fig2['data'][0], row=2, col=1)

fig_sub.update_layout(xaxis2_rangeslider_visible=True)


问:
Need help for managing functions of a Tkinter GUI in a separate file
So I am new here and this may be very basic but I need your help. I am new to tkinter and was building a calculator as my first project. I wanted the functions of the calculator in a separate file, but when I import them in the main file they don't seem to work. I think it's a problem with global variables but don't know how to fix it.

Here's the error and the code snippets:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\AKHIL\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "c:\Users\AKHIL\OneDrive\Documents\GitHub\CS-project\calc.py", line 83, in <lambda>
    button_6 = Button(calc, text="6", padx=40, pady=20, command=lambda: button_click(6))
  File "c:\Users\AKHIL\OneDrive\Documents\GitHub\CS-project\function.py", line 8, in button_click
    current = display.get()
NameError: name 'display' is not defined
```
<p>this is calc.py</p>
<pre class="lang-py prettyprint-override"><code>from tkinter import *
from function import *

calc = Tk()
calc.title("Calculator")
calc.iconbitmap("calc.ico")

button_1 = Button(calc, text="1", padx=40, pady=20, command=lambda: button_click(1))
button_2 = Button(calc, text="2", padx=40, pady=20, command=lambda: button_click(2))
button_3 = Button(calc, text="3", padx=40, pady=20, command=lambda: button_click(3))
button_4 = Button(calc, text="4", padx=40, pady=20, command=lambda: button_click(4))
button_5 = Button(calc, text="5", padx=40, pady=20, command=lambda: button_click(5))
button_6 = Button(calc, text="6", padx=40, pady=20, command=lambda: button_click(6))
button_7 = Button(calc, text="7", padx=40, pady=20, command=lambda: button_click(7))
button_8 = Button(calc, text="8", padx=40, pady=20, command=lambda: button_click(8))
button_9 = Button(calc, text="9", padx=40, pady=20, command=lambda: button_click(9))
button_0 = Button(calc, text="0", padx=40, pady=20, command=lambda: button_click(0))

button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
</code>```

And this is  function.py

from tkinter import *

def button_click(number):
    global display
    current = display.get()
    display.delete(0, END)
    display.insert(0, str(current) + str(number))
```

Body:
So I am new here and this may be very basic but I need your help. I am new to tkinter and was building a calculator as my first project. I wanted the functions of the calculator in a separate file, but when I import them in the main file they don't seem to work. I think it's a problem with global variables but don't know how to fix it.

Here's the error and the code snippets:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\AKHIL\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "c:\Users\AKHIL\OneDrive\Documents\GitHub\CS-project\calc.py", line 83, in <lambda>
    button_6 = Button(calc, text="6", padx=40, pady=20, command=lambda: button_click(6))
  File "c:\Users\AKHIL\OneDrive\Documents\GitHub\CS-project\function.py", line 8, in button_click
    current = display.get()
NameError: name 'display' is not defined

this is calc.py

from tkinter import *
from function import *

calc = Tk()
calc.title("Calculator")
calc.iconbitmap("calc.ico")

button_1 = Button(calc, text="1", padx=40, pady=20, command=lambda: button_click(1))
button_2 = Button(calc, text="2", padx=40, pady=20, command=lambda: button_click(2))
button_3 = Button(calc, text="3", padx=40, pady=20, command=lambda: button_click(3))
button_4 = Button(calc, text="4", padx=40, pady=20, command=lambda: button_click(4))
button_5 = Button(calc, text="5", padx=40, pady=20, command=lambda: button_click(5))
button_6 = Button(calc, text="6", padx=40, pady=20, command=lambda: button_click(6))
button_7 = Button(calc, text="7", padx=40, pady=20, command=lambda: button_click(7))
button_8 = Button(calc, text="8", padx=40, pady=20, command=lambda: button_click(8))
button_9 = Button(calc, text="9", padx=40, pady=20, command=lambda: button_click(9))
button_0 = Button(calc, text="0", padx=40, pady=20, command=lambda: button_click(0))

button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)

And this is  function.py

from tkinter import *

def button_click(number):
    global display
    current = display.get()
    display.delete(0, END)
    display.insert(0, str(current) + str(number))


问:
How to change the index of the columns and row to start by 1 not zero and display the correct index on the image?
I have written the below code using matplolib in python to graph the below figure my question is that the index of the x axis and y axis if the array and figure start by 0, i want it to start by 1 not zero in both of the array and the figure because and how to display the start and the end of the correct index on the image?</p>
```<code>import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.set_title('Satellite 1')
grid = np.array(
    [
        [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, ],
        [9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, ],
        [17, 17, 18, 18, 19, 19, 20, 0, 21, 21, 22, 0, 23, 23, 24, 24, ],
        [25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, ],
        [33, 33, 34, 0, 35, 35, 36, 36, 37, 37, 0, 38, 39, 39, 40, 40, ],
        [41, 41, 41, 42, 42, 42, 43, 43, 43, 44, 44, 44, 45, 45, 45, 0, ],
    ]
)

# ax.imshow(grid)
im = plt.imshow(grid, cmap='PuBuGn')

# Move left and bottom spines outward by 10 points
ax.spines['left'].set_position(('outward', 10))
ax.spines['bottom'].set_position(('outward', 10))

# Hide the right and top spines
ax.spines['right'].set_visible(True)
ax.spines['top'].set_visible(True)

# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
im.axes.get_xaxis().set_visible(True)
im.axes.get_yaxis().set_visible(True)
ax.set_frame_on(True)

ax.set_aspect('equal')

plt.colorbar(orientation='horizontal')

plt.show()
</code>```

Body:
I have written the below code using matplolib in python to graph the below figure my question is that the index of the x axis and y axis if the array and figure start by 0, i want it to start by 1 not zero in both of the array and the figure because and how to display the start and the end of the correct index on the image?

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.set_title('Satellite 1')
grid = np.array(
    [
        [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, ],
        [9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, ],
        [17, 17, 18, 18, 19, 19, 20, 0, 21, 21, 22, 0, 23, 23, 24, 24, ],
        [25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, ],
        [33, 33, 34, 0, 35, 35, 36, 36, 37, 37, 0, 38, 39, 39, 40, 40, ],
        [41, 41, 41, 42, 42, 42, 43, 43, 43, 44, 44, 44, 45, 45, 45, 0, ],
    ]
)

# ax.imshow(grid)
im = plt.imshow(grid, cmap='PuBuGn')

# Move left and bottom spines outward by 10 points
ax.spines['left'].set_position(('outward', 10))
ax.spines['bottom'].set_position(('outward', 10))

# Hide the right and top spines
ax.spines['right'].set_visible(True)
ax.spines['top'].set_visible(True)

# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
im.axes.get_xaxis().set_visible(True)
im.axes.get_yaxis().set_visible(True)
ax.set_frame_on(True)

ax.set_aspect('equal')

plt.colorbar(orientation='horizontal')

plt.show()


问:
function find_smallest_subarray_with_sum(arr: List[int], target_sum: int)
function find_smallest_subarray_with_sum(arr: List[int], target_sum: int) -> Tuple[int, int] that takes in a list arr of integers and a target sum target_sum, and returns the start and end indices of the smallest subarray in arr that has a sum of at least target_sum. If no such subarray exists, return (-1, -1).

You can assume that the input list arr will have at least one element.

Given a list of integers and a target sum, the goal is to find the start and end indices of the smallest subarray in the list that has a sum of at least the target sum. If no such subarray exists, the function should return (-1, -1). The function should return the indices as a tuple.


问:
Using Sktime Regressor
I am trying to use any regressor model from sktime but but I couldn't figure out how to create the data type and format I need to use. Assume I want to use 2 columns as input and 1 column as target.

```<code>from sktime.regression.interval_based import TimeSeriesForestRegressor

rand = np.random.random((200, 3))
X = pd.DataFrame(rand)[[0, 1]]
y = pd.DataFrame(rand)[2]

forecaster = TimeSeriesForestRegressor()
forecaster.fit(X=X, y=pd.Series(y))
</code>```

Code block above this error: "X is not of a supported input data type.X must be in a supported mtype format for Panel, found <class 'pandas.core.frame.DataFrame'>Use datatypes.check_is_mtype to check conformance with specifications."

How can I solve that problem?

Title: Using Sktime Regressor

Body:
I am trying to use any regressor model from sktime but but I couldn't figure out how to create the data type and format I need to use. Assume I want to use 2 columns as input and 1 column as target.

from sktime.regression.interval_based import TimeSeriesForestRegressor

rand = np.random.random((200, 3))
X = pd.DataFrame(rand)[[0, 1]]
y = pd.DataFrame(rand)[2]

forecaster = TimeSeriesForestRegressor()
forecaster.fit(X=X, y=pd.Series(y))

Code block above this error: "X is not of a supported input data type.X must be in a supported mtype format for Panel, found <class 'pandas.core.frame.DataFrame'>Use datatypes.check_is_mtype to check conformance with specifications."

How can I solve that problem?


问:
Flutter run external App after selection?
Is it possible to include an selection of all apps on the device, that the user can select the app? Also the same with Bluetooth connection. The user can select an Bluetooth device and when the device is accessible the selceted app starts? Give it packages for flutter, which can handle this?</p>


问:
how to make the modules name generated by typedoc as the example provided by them
geeks, I was doing some documentation for my code so I used type doc because I use Nextjs but I faced some problems
after doing some documentation this is what type doc generated

enter image description here

but what is was looking for is the example page they provide

enter image description here

I looked at the way the write comments
I will show you mine

/**
 * fileType enum
 * ```
 * enum fileType {
 * audio = 0,
 * video = 1,
 * }
 * export default fileType;
 * ```
 * @enm fileType
 */
enum fileType {
  /**
   * 0 for audio file
   */
  audio = 0,
  /**
   * 1 for video file
   */
  video = 1,
}
export default fileType;
```
<p>and did not define it as a enum in the generated document
it generated as a module
enter image description here</p>
<p>and this is the way they write the comments to be generated as a enum</p>
```/**
 * Since TypeScript's `enum` can be inconvenient to work with, some packages define their own enum-like objects:
 *
 * ```
 * export const EnumLikeObjectNumValues = {
 *     Pending: 1,
 *     InProgress: 2,
 *     Completed: 3
 * } as const
 * ```
 *
 * Use the `@enum` tag to make TypeDoc document this object as an enum.
 *
 * @enum
 */
export const EnumLikeObjectNumValues = {
    Pending: 1,

    /** Indicates that a courier is en route delivering this order. */
    InProgress: 2,

    Completed: 3,
} as const;
```
<p>so what is the solution to make my documentation looks like their documentation</p>
<p>/**</p>
<ul>
<li>fileType enum</li>
<li>
``````
</li>
<li>enum fileType {</li>
<li>audio = 0,</li>
<li>video = 1,</li>
<li>}</li>
<li>export default fileType;</li>
<li>
``````

@enm fileType
*/

/**

fileType enum

@enm
*/

Body:
geeks, I was doing some documentation for my code so I used type doc because I use Nextjs but I faced some problems
after doing some documentation this is what type doc generated

enter image description here

but what is was looking for is the example page they provide

enter image description here

I looked at the way the write comments
I will show you mine

/**
 * fileType enum
 * ```
 * enum fileType {
 * audio = 0,
 * video = 1,
 * }
 * export default fileType;
 * ```
 * @enm fileType
 */
enum fileType {
  /**
   * 0 for audio file
   */
  audio = 0,
  /**
   * 1 for video file
   */
  video = 1,
}
export default fileType;

and did not define it as a enum in the generated document
it generated as a module
enter image description here

and this is the way they write the comments to be generated as a enum

/**
 * Since TypeScript's `enum` can be inconvenient to work with, some packages define their own enum-like objects:
 *
 * ```
 * export const EnumLikeObjectNumValues = {
 *     Pending: 1,
 *     InProgress: 2,
 *     Completed: 3
 * } as const
 * ```
 *
 * Use the `@enum` tag to make TypeDoc document this object as an enum.
 *
 * @enum
 */
export const EnumLikeObjectNumValues = {
    Pending: 1,

    /** Indicates that a courier is en route delivering this order. */
    InProgress: 2,

    Completed: 3,
} as const;

so what is the solution to make my documentation looks like their documentation

/**

fileType enum

enum fileType {

audio = 0,

video = 1,

}

export default fileType;

@enm fileType
*/

/**

fileType enum

@enm
*/


问:
How to properly send a broadcast message using python socket?
This is the configuration I am using.

Now I want the nodes to send packets in broadcast, but only to nodes directly connected.

sender.py:

import socket
import time

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
server.settimeout(0.2)

message = b"mymessage"
while True:
    server.sendto(message, ('<broadcast>', 37020))
    print("message sent!")
    time.sleep(1)
```
<p><code>receiver.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>import socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # UDP
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

client.bind(("", 37020))
while True:

    data, addr = client.recvfrom(1024)
    print(f"received: {data}, from: {addr}\n")
</code>```

Let's say this is the configuration:

If I run receiver.py on r1,r2,r3, and I run sender.py on r4, i would expect to receive the messages only on the directly connected machines, since I set TTL=1. Instead I receive the message in ALL machines. The output of the receiving machines is received b"mymessage" from 172.17.0.4 (which is the interface I use to manage the virtual nodes, as seen in the picture. Since I don't want the nodes to use that interface, I tried to replace the <broadcast> parameter in sender.py with a more specific one. I first replaced it with 10.255.255.255, but I couldn't receive anything. 0.0.0.0 is not working either. I have a similar issue using multicast, but that would go out of topic. I am probably doing something very wrong here but i can't figure out what.

The final aim, as partially stated above, is to give each nodes the ability to connect ONLY to the adjacent ones, skipping anything that requires more than 1 hop.

Thank you for your time.

Body:
This is the configuration I am using.

Now I want the nodes to send packets in broadcast, but only to nodes directly connected.

sender.py:

import socket
import time

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
server.settimeout(0.2)

message = b"mymessage"
while True:
    server.sendto(message, ('<broadcast>', 37020))
    print("message sent!")
    time.sleep(1)

receiver.py:

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # UDP
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

client.bind(("", 37020))
while True:

    data, addr = client.recvfrom(1024)
    print(f"received: {data}, from: {addr}\n")

Let's say this is the configuration:

If I run receiver.py on r1,r2,r3, and I run sender.py on r4, i would expect to receive the messages only on the directly connected machines, since I set TTL=1. Instead I receive the message in ALL machines. The output of the receiving machines is received b"mymessage" from 172.17.0.4 (which is the interface I use to manage the virtual nodes, as seen in the picture. Since I don't want the nodes to use that interface, I tried to replace the <broadcast> parameter in sender.py with a more specific one. I first replaced it with 10.255.255.255, but I couldn't receive anything. 0.0.0.0 is not working either. I have a similar issue using multicast, but that would go out of topic. I am probably doing something very wrong here but i can't figure out what.

The final aim, as partially stated above, is to give each nodes the ability to connect ONLY to the adjacent ones, skipping anything that requires more than 1 hop.

Thank you for your time.


问:
WebSocket connection fail with Angular/NestJS configuration using SSL and ngrok
I am currently developping a client server with a websocket where the server(NestJS) updates the client(Angular) through socket.io. I also use a self signed SSL as I need camera access when the client is on smarthone.

Read until the end, there is a weird workaround which could help to find the cause.

The issue

The socket worked well when I was doing everything in localhost. Now that I am using ngrok, the following happens

In my Chrome console I got the following error:

Code

I run my Angular with
npm run proxy-config && ng serve --disable-host-check --ssl true --ssl-key ./src/assets/ssl/localhost-key.pem --ssl-cert ./src/assets/ssl/localhost.pem --host $IP "my actual PC IP"

It runs on port 4200

On NestJS I created app.gateway.ts
`

```<code>@WebSocketGateway({ cors: true })
export class AppGateway implements OnGatewayInit, OnGatewayDisconnect, OnGatewayConnection {

  ...
  private server: Server;

  afterInit(server: Server) {
    this.logger.log('Initialized!');
    this.server = server;
  }

  @SubscribeMessage('msgToServer')
  handleMessage(client: Socket, text: string): WsResponse<string> {
    ...
  }

  handleConnection(client: any, ...args: any[]) {
  ...
  }
  handleDisconnect(client: any) {
    ...
  }
}

</code>```

It runs on port 3000

Angular code for the socket is

```<code> this.socket = io("this.backendURL",
      { reconnection: true,
        rejectUnauthorized: false,
        transports: ['websocket'],
        autoConnect: true
      });
</code>```

And my Angular project uses the following proxy
`

```<code>import { environment } from "./environment";

const PROXY_CONFIG = [
    {
        target: environment.backend_url,
        api: "/api/*",
        secure: false,
        logLevel: "debug",
        changeOrigin: true

    }
]
module.exports = PROXY_CONFIG;

</code>```

`
Finally, I launch ngrok HTTP 3000 for the back-end.

I tried every fix i could found related to CORS, changing  transports: ['websocket'] in the client with no result.

BUT : if I open in the browser the address
https://my_ngrok_url/socket.io/?EIO=4&transport=websocket

then I can start my client again and the WebSocket will work perfectly.
When I do so, it displays the following in ngrok console.

```<code>GET /socket.io/                101 Switching Protocols
</code>```

Why does everything works ONLY after I reach first this URL on my browser ??

(PS: I know that what I am doing won't be production-ready)

Body:
I am currently developping a client server with a websocket where the server(NestJS) updates the client(Angular) through socket.io. I also use a self signed SSL as I need camera access when the client is on smarthone.

Read until the end, there is a weird workaround which could help to find the cause.

The issue

The socket worked well when I was doing everything in localhost. Now that I am using ngrok, the following happens

In my Chrome console I got the following error:

Code

I run my Angular with
npm run proxy-config && ng serve --disable-host-check --ssl true --ssl-key ./src/assets/ssl/localhost-key.pem --ssl-cert ./src/assets/ssl/localhost.pem --host $IP "my actual PC IP"

It runs on port 4200

On NestJS I created app.gateway.ts
`

@WebSocketGateway({ cors: true })
export class AppGateway implements OnGatewayInit, OnGatewayDisconnect, OnGatewayConnection {

  ...
  private server: Server;

  afterInit(server: Server) {
    this.logger.log('Initialized!');
    this.server = server;
  }

  @SubscribeMessage('msgToServer')
  handleMessage(client: Socket, text: string): WsResponse<string> {
    ...
  }

  handleConnection(client: any, ...args: any[]) {
  ...
  }
  handleDisconnect(client: any) {
    ...
  }
}

It runs on port 3000

Angular code for the socket is

 this.socket = io("this.backendURL",
      { reconnection: true,
        rejectUnauthorized: false,
        transports: ['websocket'],
        autoConnect: true
      });

And my Angular project uses the following proxy
`

import { environment } from "./environment";

const PROXY_CONFIG = [
    {
        target: environment.backend_url,
        api: "/api/*",
        secure: false,
        logLevel: "debug",
        changeOrigin: true

    }
]
module.exports = PROXY_CONFIG;

`
Finally, I launch ngrok HTTP 3000 for the back-end.

I tried every fix i could found related to CORS, changing  transports: ['websocket'] in the client with no result.

BUT : if I open in the browser the address
https://my_ngrok_url/socket.io/?EIO=4&transport=websocket

then I can start my client again and the WebSocket will work perfectly.
When I do so, it displays the following in ngrok console.

GET /socket.io/                101 Switching Protocols

Why does everything works ONLY after I reach first this URL on my browser ??

(PS: I know that what I am doing won't be production-ready)


问:
I want to make scheduled chat with laravel - Cron task
There is an Api called sendMessage and the uri is chat/sendMessage and the body of this uri is :

```<code>{
   'Message': " Hello ",
   'targetUser: "SomeOne"
}
</code>```

so what the code does after calling this uri it goes to MessageController and use the Send() function and will send the message to the targetUser, But What I want to do is to make this to Scheduled Chat , meaning that I want to Change the Body of uri to This :

```<code>{
    'Message': " Hello ",
    'targetUser: "SomeOne",
    'Date' : " 4 5 30 3 6"  // which means : 04:05 on 30/march on Saturday.This is Cron type date in laravel
}
</code>```

and After calling the uri this will do the job on that Date for me.

So I created the ChatCron.php file in App/Console/Command Directory then I have to handle the function in handle() and then Call it from Kernel.php.

The problem is :

I actually can't figure it out how to Connect ChatCron.php to MessageController .

I don't know how to tell Laravel that : After calling the uri go to ChatCron.php and set the timer for calling the Send() function in MessageController.

What I know right now is that I can call the handle function of ChatCron.php  in Kernel.php in a specific date with:

```<code>$schedule->command('cron:chat')
         ->cron(' 4 5 30 3 6 ')
         ->background();

</code>```

Body:
There is an Api called sendMessage and the uri is chat/sendMessage and the body of this uri is :

{
   'Message': " Hello ",
   'targetUser: "SomeOne"
}

so what the code does after calling this uri it goes to MessageController and use the Send() function and will send the message to the targetUser, But What I want to do is to make this to Scheduled Chat , meaning that I want to Change the Body of uri to This :

{
    'Message': " Hello ",
    'targetUser: "SomeOne",
    'Date' : " 4 5 30 3 6"  // which means : 04:05 on 30/march on Saturday.This is Cron type date in laravel
}

and After calling the uri this will do the job on that Date for me.

So I created the ChatCron.php file in App/Console/Command Directory then I have to handle the function in handle() and then Call it from Kernel.php.

The problem is :

I actually can't figure it out how to Connect ChatCron.php to MessageController .

I don't know how to tell Laravel that : After calling the uri go to ChatCron.php and set the timer for calling the Send() function in MessageController.

What I know right now is that I can call the handle function of ChatCron.php  in Kernel.php in a specific date with:

$schedule->command('cron:chat')
         ->cron(' 4 5 30 3 6 ')
         ->background();