问:
Error in dir.exists(x) : file name conversion problem -- name too long?
I am trying to import a .py file in RStudio and I am getting the error message:

```<code>Error in dir.exists(x) : file name conversion problem -- name too long?)
</code>```

I have already tried to run it through a path that only contains English letters and it didn't work. Also, the output of list.files() includes the file I'm trying to import.

```<code>library(reticulate)
library(tidyverse)
library(forcats)

setwd("C:/Users/Κατερίνα/Nextcloud/Multipic_Exp.1")

source_python("euler.py") --> Here I get the error message.

The traceback() output:

12: dir.exists(x)
11: utils::file_test("-d", version_dir)
10: read_python_versions_from_registry("HCU", key = "PythonCore")
9: rbind(read_python_versions_from_registry("HCU", key = "PythonCore"),
       read_python_versions_from_registry("HLM", key = "PythonCore"),
       windows_registry_anaconda_versions())
8: py_versions_windows()
7: python_conda_versions()
6: py_discover_config(required_module, use_environment)
5: (function() {
       op <- options(reticulate.python.initializing = TRUE)
       on.exit(options(op), add = TRUE)
       py_discover_config(required_module, use_environment)
   })()
4: initialize_python(required_module, use_environment)
3: ensure_python_initialized()
2: py_run_file(file, local = FALSE, convert = convert)
1: source_python("euler.py")

My sessionInfo():
R version 4.1.0 (2021-05-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=Greek_Greece.1253  LC_CTYPE=Greek_Greece.1253    LC_MONETARY=Greek_Greece.1253
[4] LC_NUMERIC=C                  LC_TIME=Greek_Greece.1253

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] forcats_0.5.1   stringr_1.4.0   dplyr_1.0.7     purrr_0.3.4     readr_1.4.0     tidyr_1.1.3     tibble_3.1.2
 [8] ggplot2_3.3.5   tidyverse_1.3.1 reticulate_1.26

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.9       cellranger_1.1.0 pillar_1.6.1     compiler_4.1.0   dbplyr_2.1.1     tools_4.1.0
 [7] lubridate_1.8.0  jsonlite_1.8.4   lifecycle_1.0.3  gtable_0.3.0     lattice_0.20-44  pkgconfig_2.0.3
[13] png_0.1-7        rlang_1.0.6      reprex_2.0.1     Matrix_1.3-3     cli_3.4.1        DBI_1.1.1
[19] rstudioapi_0.13  haven_2.4.1      xml2_1.3.2       withr_2.4.2      httr_1.4.2       fs_1.5.2
[25] hms_1.1.0        generics_0.1.0   vctrs_0.5.1      rprojroot_2.0.2  grid_4.1.0       tidyselect_1.1.1
[31] here_1.0.1       glue_1.6.2       R6_2.5.1         fansi_0.5.0      readxl_1.3.1     modelr_0.1.8
[37] magrittr_2.0.3   scales_1.1.1     backports_1.2.1  ellipsis_0.3.2   rvest_1.0.2      assertthat_0.2.1
[43] colorspace_2.0-2 utf8_1.2.1       stringi_1.7.6    munsell_0.5.0    broom_0.7.8      crayon_1.4.1
</code>```
```<code></code>```

Body:
I am trying to import a .py file in RStudio and I am getting the error message:

Error in dir.exists(x) : file name conversion problem -- name too long?)

I have already tried to run it through a path that only contains English letters and it didn't work. Also, the output of list.files() includes the file I'm trying to import.

library(reticulate)
library(tidyverse)
library(forcats)

setwd("C:/Users/Κατερίνα/Nextcloud/Multipic_Exp.1")

source_python("euler.py") --> Here I get the error message.

The traceback() output:

12: dir.exists(x)
11: utils::file_test("-d", version_dir)
10: read_python_versions_from_registry("HCU", key = "PythonCore")
9: rbind(read_python_versions_from_registry("HCU", key = "PythonCore"),
       read_python_versions_from_registry("HLM", key = "PythonCore"),
       windows_registry_anaconda_versions())
8: py_versions_windows()
7: python_conda_versions()
6: py_discover_config(required_module, use_environment)
5: (function() {
       op <- options(reticulate.python.initializing = TRUE)
       on.exit(options(op), add = TRUE)
       py_discover_config(required_module, use_environment)
   })()
4: initialize_python(required_module, use_environment)
3: ensure_python_initialized()
2: py_run_file(file, local = FALSE, convert = convert)
1: source_python("euler.py")

My sessionInfo():
R version 4.1.0 (2021-05-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=Greek_Greece.1253  LC_CTYPE=Greek_Greece.1253    LC_MONETARY=Greek_Greece.1253
[4] LC_NUMERIC=C                  LC_TIME=Greek_Greece.1253

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] forcats_0.5.1   stringr_1.4.0   dplyr_1.0.7     purrr_0.3.4     readr_1.4.0     tidyr_1.1.3     tibble_3.1.2
 [8] ggplot2_3.3.5   tidyverse_1.3.1 reticulate_1.26

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.9       cellranger_1.1.0 pillar_1.6.1     compiler_4.1.0   dbplyr_2.1.1     tools_4.1.0
 [7] lubridate_1.8.0  jsonlite_1.8.4   lifecycle_1.0.3  gtable_0.3.0     lattice_0.20-44  pkgconfig_2.0.3
[13] png_0.1-7        rlang_1.0.6      reprex_2.0.1     Matrix_1.3-3     cli_3.4.1        DBI_1.1.1
[19] rstudioapi_0.13  haven_2.4.1      xml2_1.3.2       withr_2.4.2      httr_1.4.2       fs_1.5.2
[25] hms_1.1.0        generics_0.1.0   vctrs_0.5.1      rprojroot_2.0.2  grid_4.1.0       tidyselect_1.1.1
[31] here_1.0.1       glue_1.6.2       R6_2.5.1         fansi_0.5.0      readxl_1.3.1     modelr_0.1.8
[37] magrittr_2.0.3   scales_1.1.1     backports_1.2.1  ellipsis_0.3.2   rvest_1.0.2      assertthat_0.2.1
[43] colorspace_2.0-2 utf8_1.2.1       stringi_1.7.6    munsell_0.5.0    broom_0.7.8      crayon_1.4.1


来源: stackexchange

问:
terraform | aws_launch_template restricts version limits
In AWS, while creating launch_template, there is an option to delete versions. but in terraform, I don't see any attributes that do that.

With each deployment, I see it creates a new aws launch template and doesn't remove the old one.

Is there any option to delete / restrict the number of version to have at one of time?

ContentLicense: CC BY-SA 4.0


问:
Mysql not summing values inputted through php into table
So I've got a strange problem.  I have a sum query in php.  If the values are inserted directly into the table via me through phpmyadmin the query works and it sums the values.  If the value is inserted through php script mysql does not sum the value.

In this example, ID 3 to ID 28 I inserted into the table with the insert function.  ID 29 was inserted through my php script and it is not being summed.  I tested this a few times to make sure that that is the problem.

```<code>SELECT sum(Qty) as LeaveTotal FROM ptrLeave WHERE EmployeeCode = 'PW00' and LeaveType = 1 and Comment != 'Leave Assigned'
</code>```

Hopefully someone can help me please.

Body:
So I've got a strange problem.  I have a sum query in php.  If the values are inserted directly into the table via me through phpmyadmin the query works and it sums the values.  If the value is inserted through php script mysql does not sum the value.

In this example, ID 3 to ID 28 I inserted into the table with the insert function.  ID 29 was inserted through my php script and it is not being summed.  I tested this a few times to make sure that that is the problem.

SELECT sum(Qty) as LeaveTotal FROM ptrLeave WHERE EmployeeCode = 'PW00' and LeaveType = 1 and Comment != 'Leave Assigned'

Hopefully someone can help me please.


问:
How to use same same s3 bucket which triggers AWS lambda to populate staging and production database
Creation events in one of my S3 buckets triggers AWS lambda MyLambda which eventually saves some row in my RDS database (production).
Now I want use (same!) bucket that will trigger MyLambda-Staging (different lambda) or MyLambda:Staging (alias for MyLambda) -whatever approach I choose.

My I get stuck because of this error:

```<code>An error occurred when creating the trigger: Configuration is ambiguously defined. Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type.
</code>```

So I wanted to create new lambda( or alias) which will use same bucket and be trigger my same suffix (because there are huge amount of files and I am interested in only one)

I don't want this solution to involve additional AWS services since I want most simple solution possible.

Body:
Creation events in one of my S3 buckets triggers AWS lambda MyLambda which eventually saves some row in my RDS database (production).
Now I want use (same!) bucket that will trigger MyLambda-Staging (different lambda) or MyLambda:Staging (alias for MyLambda) -whatever approach I choose.

My I get stuck because of this error:

An error occurred when creating the trigger: Configuration is ambiguously defined. Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type.

So I wanted to create new lambda( or alias) which will use same bucket and be trigger my same suffix (because there are huge amount of files and I am interested in only one)

I don't want this solution to involve additional AWS services since I want most simple solution possible.


问:
Is there any way to tap on iconWidget in OpenStreetMap (flutter_osm_plugin)?
I am using flutter_osm_plugin to show my map. And in StaticPositionedGeoPoint i'm giving iconWidget. Which is having inkwell itself. But some how I am not able to tap on marker.

```<code>for (int i = 0; i < latlngList.length; i++) {
  markers.add(StaticPositionGeoPoint(
      i.toString(),
      MarkerIcon(
          iconWidget: InkWell(
        onTap: () {
          print("Marker Tapped");
        },
        child: Container(
          height: 150,
          width: 150,
          decoration: const BoxDecoration(
              shape: BoxShape.circle, color: Colors.pink),
        ),
      )),
      latlngList));
}
</code>```

Anyone know how to achieve this?

Body:
I am using flutter_osm_plugin to show my map. And in StaticPositionedGeoPoint i'm giving iconWidget. Which is having inkwell itself. But some how I am not able to tap on marker.

for (int i = 0; i < latlngList.length; i++) {
  markers.add(StaticPositionGeoPoint(
      i.toString(),
      MarkerIcon(
          iconWidget: InkWell(
        onTap: () {
          print("Marker Tapped");
        },
        child: Container(
          height: 150,
          width: 150,
          decoration: const BoxDecoration(
              shape: BoxShape.circle, color: Colors.pink),
        ),
      )),
      latlngList));
}

Anyone know how to achieve this?


问:
Add multiple $data references to require property in JSON Schema
I have an array filters-detail with objects in it. These objects should include the values of the other properties filters-applied and applied-second. I use AJV and tried to use two $data objects but it fails.

{
  "additionalProperties": false,
  "type": "object",
  "properties": {
    "filters-applied": {
      "type": "array",
      "uniqueItems": true,
      "items": {
        "type": "string",
        "maxLength": 255
      }
    },
    "applied-second": {
      "type": "array",
      "uniqueItems": true,
      "items": {
        "type": "string",
        "maxLength": 255
      }
    },
    "filters-detail": {
      "type": "array",
      "items": {
        "type": "object",
        "required": [
          {
            "$data": "2/filters-applied"
          },
          {
            "$data": "2/applied-second"
          }
        ]
      }
    }
  }
}

```
<p>Example data that should be valid:</p>
<pre class="lang-json prettyprint-override"><code>{
  "filters-applied": ["color", "size"],
  "applied-second": ["brand"],
  "filters-detail": [{ color: ["red", "blue"], size: "XS", brand: "Boss" }],
}
</code>```

I managed to get only one requirement working:

"filters-detail": {
  "type": "array",
  "items": {
    "type": "object",
    "required": {
      "$data": "2/filters-applied"
    }
  }
}
```

Noticeable are the missing [], but I don't know how to leave them and add two objects to required without violating against the JSON structure.

I need to depend on two other properties.
How can I achieve this?

Body:
I have an array filters-detail with objects in it. These objects should include the values of the other properties filters-applied and applied-second. I use AJV and tried to use two $data objects but it fails.

{
  "additionalProperties": false,
  "type": "object",
  "properties": {
    "filters-applied": {
      "type": "array",
      "uniqueItems": true,
      "items": {
        "type": "string",
        "maxLength": 255
      }
    },
    "applied-second": {
      "type": "array",
      "uniqueItems": true,
      "items": {
        "type": "string",
        "maxLength": 255
      }
    },
    "filters-detail": {
      "type": "array",
      "items": {
        "type": "object",
        "required": [
          {
            "$data": "2/filters-applied"
          },
          {
            "$data": "2/applied-second"
          }
        ]
      }
    }
  }
}

Example data that should be valid:

{
  "filters-applied": ["color", "size"],
  "applied-second": ["brand"],
  "filters-detail": [{ color: ["red", "blue"], size: "XS", brand: "Boss" }],
}

I managed to get only one requirement working:

"filters-detail": {
  "type": "array",
  "items": {
    "type": "object",
    "required": {
      "$data": "2/filters-applied"
    }
  }
}

Noticeable are the missing [], but I don't know how to leave them and add two objects to required without violating against the JSON structure.

I need to depend on two other properties.
How can I achieve this?


问:
How to deal with dropdown in react table data and pass its value to parent table component
Currently I have a table, wherein table data is a dropdown. Now, On changing the values in the cell, I want to show that value into another column as selected column. Now, For Dropdown I have made a child component and table is my parent component. How can I track the changes from my child component to parent component

```<code>import { SetStateAction, useState } from 'react';
import useSWR from 'swr';
import { DropDown } from './dropdown';
const fetcher = (url: RequestInfo | URL) => fetch(url).then((res) => res.json());

export const Table = () => {
    const [col1, setCol1] = useState("harshil");
    const changeCol1 = (e: { target: { value: SetStateAction<string>; }; }) => {
        setCol1(e.target.value);
    }
    const regex: RegExp = /\${{\w+}}/gm;
    const { data, error }: any = useSWR('/api/template', fetcher);

    if (error) return <div>Failed to load</div>;
    if (!data) return <div>Loading...</div>;

    let variables: Array<string> = data.match(regex).map((d: string) => d.replace(/(\$)|({)|(})/g, ""));

    return (
        <div className='table'>
            <table>
                <thead>
                    <tr>
                        <th>Variables</th>
                        <th>Column Name 1</th>
                        <th>Column Name 2</th>
                        <th>Choice or Name</th>
                        <th>Choosen Column</th>
                        <th>Operation/Formula</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        variables.map((d: string) => (
                            <tr key={d}>
                                <td>{d}</td>
                                <td onChange={() => changeCol1}>
                                    <DropDown id={d}/>
                                </td>
                                <td><DropDown id={d}/></td>
                                <td><input placeholder='You can edit entries here'></input></td>
                                <td>
                                   {col1}
                                </td>
                                <td><input placeholder='apply some sort of formulation'></input></td>
                            </tr>
                        ))
                    }
                </tbody>
            </table>
        </div>
    );

}
</code>```

This was my Table.ts component

and here is my dropdown component. I want to print the selected value from corresponding row into the {col1} value.

```<code>import useSWR from 'swr';
import { flatten } from "flat";
import { SetStateAction, useEffect, useState } from 'react';
const fetcher = (url: RequestInfo | URL) => fetch(url).then((res) => res.json());

export const DropDown = (props: any) => {
    const [col1,setCol1] = useState("harshil");
    const { data, error }: any = useSWR('/api/jsondata', fetcher);
    if (error) return <div>Failed to load</div>;
    if (!data) return <div>Loading...</div>;

    const obj: Object = JSON.parse(data);
    const options: Array<string> = Object.keys(flatten(obj));
    const col1Handler = (e: { target: { value: SetStateAction<string>; }; }) => {
        setCol1(e.target.value);
    }
    console.log(props);
    return (
        <div className='dropdown'>
            <select onChange={col1Handler} value={col1} id={props.id}>
                {
                    options.map((d: string) => (
                        <option key={d}>{d}</option>
                    ))
                }
            </select>
            <h1>{col1}</h1>
        </div>
    );

}
</code>```

onChange doesn't really help me with the changing value of td since it always assumes td to be a dropdown component and thus internal changes are not recorded.

Body:
Currently I have a table, wherein table data is a dropdown. Now, On changing the values in the cell, I want to show that value into another column as selected column. Now, For Dropdown I have made a child component and table is my parent component. How can I track the changes from my child component to parent component

import { SetStateAction, useState } from 'react';
import useSWR from 'swr';
import { DropDown } from './dropdown';
const fetcher = (url: RequestInfo | URL) => fetch(url).then((res) => res.json());

export const Table = () => {
    const [col1, setCol1] = useState("harshil");
    const changeCol1 = (e: { target: { value: SetStateAction<string>; }; }) => {
        setCol1(e.target.value);
    }
    const regex: RegExp = /\${{\w+}}/gm;
    const { data, error }: any = useSWR('/api/template', fetcher);

    if (error) return
Failed to load
;
    if (!data) return
Loading...
;

    let variables: Array<string> = data.match(regex).map((d: string) => d.replace(/(\$)|({)|(})/g, ""));

    return (

                        Variables
                        Column Name 1
                        Column Name 2
                        Choice or Name
                        Choosen Column
                        Operation/Formula

                    {
                        variables.map((d: string) => (

                                {d}
                                 changeCol1}>
                                    <DropDown id={d}/>

                                <DropDown id={d}/>
                                <input placeholder='You can edit entries here'></input>

                                   {col1}

                                <input placeholder='apply some sort of formulation'></input>

                        ))
                    }

    );

}

This was my Table.ts component

and here is my dropdown component. I want to print the selected value from corresponding row into the {col1} value.

import useSWR from 'swr';
import { flatten } from "flat";
import { SetStateAction, useEffect, useState } from 'react';
const fetcher = (url: RequestInfo | URL) => fetch(url).then((res) => res.json());

export const DropDown = (props: any) => {
    const [col1,setCol1] = useState("harshil");
    const { data, error }: any = useSWR('/api/jsondata', fetcher);
    if (error) return
Failed to load
;
    if (!data) return
Loading...
;

    const obj: Object = JSON.parse(data);
    const options: Array<string> = Object.keys(flatten(obj));
    const col1Handler = (e: { target: { value: SetStateAction<string>; }; }) => {
        setCol1(e.target.value);
    }
    console.log(props);
    return (

            <select onChange={col1Handler} value={col1} id={props.id}>
                {
                    options.map((d: string) => (
                        <option key={d}>{d}</option>
                    ))
                }
            </select>

{col1}

    );

}

onChange doesn't really help me with the changing value of td since it always assumes td to be a dropdown component and thus internal changes are not recorded.


问:
Read value of variable in a running Windows application process, also after restart
Is it possible at all to read the value (presumably a variable, since it changes every few seconds and is shown on screen) from a process in Windows? This is some custom, fairly old (10y) Windows GUI application that shows values (part counter) from manufacturing machine connected to it via some proprietary protocol (even using a dedicated PCI commmunications card).

I got the idea when reading about people modifying settings in a game (change high-score, change difficulty level, etc).

On Windows, there is an official API ReadProcessMemory for reading data from a process's memory:

ReadProcessMemory copies the data in the specified address range from the address space of the specified process into the specified buffer of the current process. Any process that has a handle with PROCESS_VM_READ access can call the function.

While I am hopeful that it works once the address/offset of the value in question is known, I am not so sure if this application will allocate memory differently when started the next time.

This is how I would approach it:

continuously, e.g. every second

take a screen shot of the application,

take a process dump (procdump from sysinternals) of the application

analyse the process dump and try to find the location/offset of the value in question

compare process dumps from different startups of the application to see if the value is at the same offset

Is this feasible, or is it completely obvious that memory allocation is very dynamic (between restarts and even during runtime) and using an offset-based approach will be doomed?


问:
VSCODE Live Server https not wanting to start
I want to use an SSL certificate for the liveserver extension. It is self-signed, trusted, and verified to be working (added in apache).

However the extension does not want to start no matter what, unless https is disabled.
I am also using port 8080, but that does not matter. (Certificate is for "localhost")

How can I fix this?

{
    "liveserver.settings.port": 8080,
    "liveServer.settings.https": {
        "enable": true, //set it true to enable the feature.
        "cert": "/home/me/primary.crt", //full path of the certificate
        "key": "/home/me/private.key", //full path of the private key
        "passphrase": "1234"
    }
}
```


问:
PySpark SQL error - ExternalAppendOnlyUnsafeRowArray
I am trying to perform a complex query through Spark. When I try to visualize the results (by calling the .show() method) the application stucks.

I tried to see what was going on by looking at the Spark logs and I noticed that the Spark Job related to the *show * method had a huge number of tasks and seemed to be not running at all.
By looking at the logs, I noticed the following:

```<code>INFO ExternalAppendOnlyUnsafeRowArray: Reached spill threshold of 4096 rows, switching to org.apache.spark.util.collection.unsafe.sort.UnsafeExternalSorter
</code>```

I tried to modify the spill threshold by injecting the following config in the spark session:

```<code>("spark.shuffle.sort.bypassMergeThreshold", "8192")
</code>```

But I got the same log message and outcome.

I am running the application on Spark 3.2.1.

Body:
I am trying to perform a complex query through Spark. When I try to visualize the results (by calling the .show() method) the application stucks.

I tried to see what was going on by looking at the Spark logs and I noticed that the Spark Job related to the *show * method had a huge number of tasks and seemed to be not running at all.
By looking at the logs, I noticed the following:

INFO ExternalAppendOnlyUnsafeRowArray: Reached spill threshold of 4096 rows, switching to org.apache.spark.util.collection.unsafe.sort.UnsafeExternalSorter

I tried to modify the spill threshold by injecting the following config in the spark session:

("spark.shuffle.sort.bypassMergeThreshold", "8192")

But I got the same log message and outcome.

I am running the application on Spark 3.2.1.


问:
Turn off AWB and AE/AF in camera
Is it possible to turn off AWB (Automatic White Balance) or AE/AF during camera recording in Flutter?

I'm recording user face through https://pub.dev/packages/camera plugin, how can I turn off AWB and AE/AF?

Title: Turn off AWB and AE/AF in camera


问:
Django signals calling asynchronous task without celery
I'm doing in signal:

```<code>@receiver(post_save, sender=User)
def send_something(sender, instance, created, **kwargs):
    if created:
        loop = asyncio.get_event_loop()
        async_function = sync_to_async(send_id, thread_sensitive=True)
        loop.create_task(async_function(instance.id))
</code>```

my another function is:

```<code>def send_id(user_id):
    print(user_id)
</code>```

But function is not calling

Body:
I'm doing in signal:

@receiver(post_save, sender=User)
def send_something(sender, instance, created, **kwargs):
    if created:
        loop = asyncio.get_event_loop()
        async_function = sync_to_async(send_id, thread_sensitive=True)
        loop.create_task(async_function(instance.id))

my another function is:

def send_id(user_id):
    print(user_id)

But function is not calling


问:
Python shorthand from yielding from another contextmanager
Suppose I have a generator like

import csv
from typing import List
from contextlib import contextmanager

@contextmanager
def dicts_from_csv(file_path: str) -> List[dict]:
    with open(file_path, "r") as csv_file:
        reader = csv.DictReader(csv_file)
        yield list(reader)
```
<p>Now I want to add more specific generators I could do this:</p>
<pre class="lang-py prettyprint-override"><code>from typing import List
import pytest

@pytest.fixture(scope="session")
def some_reports() -> List[dict]:
    with dicts_from_csv("some_reports.csv") as reports:
        yield reports
</code>```

Is there a way to just directly yield the dicts_from_csv("some_reports.csv") without the with ... as ceremony?

Body:
Suppose I have a generator like

import csv
from typing import List
from contextlib import contextmanager

@contextmanager
def dicts_from_csv(file_path: str) -> List[dict]:
    with open(file_path, "r") as csv_file:
        reader = csv.DictReader(csv_file)
        yield list(reader)

Now I want to add more specific generators I could do this:

from typing import List
import pytest

@pytest.fixture(scope="session")
def some_reports() -> List[dict]:
    with dicts_from_csv("some_reports.csv") as reports:
        yield reports

Is there a way to just directly yield the dicts_from_csv("some_reports.csv") without the with ... as ceremony?


问:
Slack > Applescript/JS on new DM?
I'm trying to do some automation on new slack DM, (I'm using Applescript with some JS code),

I can read the numbers of unread message with this AppleScript

```<code>tell application "Safari"

    set unreadmessage to do JavaScript "document.getElementsByClassName('p-channel_sidebar__badge c-mention_badge c-mention_badge--black')[0].innerHTML;" in tab 2 of window 1

end tell
</code>```

But I can't tell who that message was sent from and how to action it and reply to it

-- Slack API is not an option for me since disabled by my organisation

Title: Slack > Applescript/JS on new DM?

Body:
I'm trying to do some automation on new slack DM, (I'm using Applescript with some JS code),

I can read the numbers of unread message with this AppleScript

tell application "Safari"

    set unreadmessage to do JavaScript "document.getElementsByClassName('p-channel_sidebar__badge c-mention_badge c-mention_badge--black')[0].innerHTML;" in tab 2 of window 1

end tell

But I can't tell who that message was sent from and how to action it and reply to it

-- Slack API is not an option for me since disabled by my organisation


问:
Multiple Redux Stores at the same level?
I am having some dificulties to add multiple redux store at the same level in my application. Basically, I have a component that represents a wrapper for other smaller applocation and I would like a store for each one of them. Is important to note that I don't know how many will be activated. I am also using the redux toolkit for this. Here is my take on it:

The component itself:

```<code>const Widget: React.FC<PropsWithChildren<Props>> = ( props: PropsWithChildren<Props> ) => {
  const { Header, Content } = Layout;
  const { children, className, defaultDependencies } = props;
  const dispatch = useWidgetDispatch();

  useEffect( () => {
    dispatch( init( defaultDependencies || {} ) );
  }, [] );

  return (
    <Layout className={ `widget ${ className }` }>
      <Header className="header">
        <div className="widget-actions start">
          <MenuOutlined className="action" />
          <Divider className="header-divider" type="vertical"></Divider>
        </div>
        <div className="widget-actions end">
          <Divider className="header-divider" type="vertical"></Divider>
          <FullscreenOutlined className="action" />
        </div>
      </Header>
      <Content className="widget-content">
        { children }
      </Content>
    </Layout>
  );
};
</code>```

And now to wrap this into a provider:

```<code>const reduxWidget = ( Root: typeof WrapperApp) => ( props: PropsWithChildren<Props> ) => {

  return (
    <Provider store={ widgetStore }>
      <Root { ...props } />
    </Provider>
  );
};
</code>```

In order to test this, I am placing two instances in App.ts:

```<code>function App () {
  const { Header, Content, Footer } = Layout;
  const {
    token: { colorBgLayout },
  } = theme.useToken();
  return (
    <Layout style={ { height: '100vh' } }>
      <SideMenu items={ sideMenuItems } />
      <Layout style={ { overflow: 'auto' } }>
        <Header style={ { padding: 0, background: colorBgLayout } } />
        <Content style={ { margin: '0 16px' } }>
          <WrapperApp defaultDependencies={ { test: true } } content>
            <div />
          </WrapperApp>
          <WrapperApp defaultDependencies={ { test: false } } content>
            <div />
          </WrapperApp>

        </Content>
        <Footer style={ { textAlign: 'center' } }>Ant Design ©2018 Created by Ant UED</Footer>
      </Layout>

    </Layout>
  );
}
</code>```

The result is that in my redux tab in my console I have only one store and the test property has the value of the last WrapperApp property. Is there a way to add as many store as WrapperApp components are placed in the App.ts?

Body:
I am having some dificulties to add multiple redux store at the same level in my application. Basically, I have a component that represents a wrapper for other smaller applocation and I would like a store for each one of them. Is important to note that I don't know how many will be activated. I am also using the redux toolkit for this. Here is my take on it:

The component itself:

const Widget: React.FC<PropsWithChildren<Props>> = ( props: PropsWithChildren<Props> ) => {
  const { Header, Content } = Layout;
  const { children, className, defaultDependencies } = props;
  const dispatch = useWidgetDispatch();

  useEffect( () => {
    dispatch( init( defaultDependencies || {} ) );
  }, [] );

  return (
    <Layout className={ `widget ${ className }` }>

          <MenuOutlined className="action" />
          <Divider className="header-divider" type="vertical"></Divider>

          <Divider className="header-divider" type="vertical"></Divider>
          <FullscreenOutlined className="action" />

      <Content className="widget-content">
        { children }
      </Content>
    </Layout>
  );
};

And now to wrap this into a provider:

const reduxWidget = ( Root: typeof WrapperApp) => ( props: PropsWithChildren<Props> ) => {

  return (
    <Provider store={ widgetStore }>
      <Root { ...props } />
    </Provider>
  );
};

In order to test this, I am placing two instances in App.ts:

function App () {
  const { Header, Content, Footer } = Layout;
  const {
    token: { colorBgLayout },
  } = theme.useToken();
  return (
    <Layout style={ { height: '100vh' } }>
      <SideMenu items={ sideMenuItems } />
      <Layout style={ { overflow: 'auto' } }>

        <Content style={ { margin: '0 16px' } }>
          <WrapperApp defaultDependencies={ { test: true } } content>

          </WrapperApp>
          <WrapperApp defaultDependencies={ { test: false } } content>

          </WrapperApp>

        </Content>
        Ant Design ©2018 Created by Ant UED
      </Layout>

    </Layout>
  );
}

The result is that in my redux tab in my console I have only one store and the test property has the value of the last WrapperApp property. Is there a way to add as many store as WrapperApp components are placed in the App.ts?


问:
Not able to highlight selected items in custom-ng-select
I created a custom ng-select with reactive form and imagine a list of data passed as dataList.

I have some default values from API to show them as selected but not able to do so. Items get's displayed in the ng-select input field but in the listing it does not make them as selected item.

Issue is not with the styles, everything is correct, because when i select item manually from list it works fine.

custom-select.component.html

```<code><div [formGroup]="componentFormGroup">
  <ng-select
    class="select-dropdown"
    [items]="dataList"
    [bindLabel]="name"
    [bindValue]="id"
    [multiple]="true"
    [placeholder]="placeHolder"
    [formControlName]="componentFormControlName"
    (change)="onSelectChange($event)">
    <ng-template
      ng-label-tmp
      let-item="item"
      let-clear="clear"
      class="template-user">
      <div class="selected-items pr-1">
        <span class="ng-value-label label-name">
          {{ item.name }}
        </span>

        <span
          class="ng-value-icon right cross-icon"
          (click)="clear(item)"
          aria-hidden="true" >
          ×
        </span>
      </div>
    </ng-template>

    <ng-template ng-option-tmp let-item="item" let-index="index" let-item$="item$">
      {{ item.id }} {{ item.name }}
    </ng-template>
  </ng-select>
</div>
</code>```

custom-select.ts

```<code>this.dataList = [
  {id: 17, name: Ahsan Shah}, {id: 28, name: John Doe}, {id: 25, name: Muhammad Yousuf}
]

// wait & get default data from API and assign it to a variable
this.defaultListData = defaultResponse?.resources; // sample [{id: 25, name: Muhammad Yousuf}]

// then assign value to form group
this.componentFormGroup.controls[this.componentFormControlName].setValue(this.defaultListData);

</code>```

What i am doing wrong? Thanks in advance

Body:
I created a custom ng-select with reactive form and imagine a list of data passed as dataList.

I have some default values from API to show them as selected but not able to do so. Items get's displayed in the ng-select input field but in the listing it does not make them as selected item.

Issue is not with the styles, everything is correct, because when i select item manually from list it works fine.

custom-select.component.html

  <ng-select
    class="select-dropdown"
    [items]="dataList"
    [bindLabel]="name"
    [bindValue]="id"
    [multiple]="true"
    [placeholder]="placeHolder"
    [formControlName]="componentFormControlName"
    (change)="onSelectChange($event)">
    <ng-template
      ng-label-tmp
      let-item="item"
      let-clear="clear"
      class="template-user">

          {{ item.name }}

          ×

    </ng-template>

    <ng-template ng-option-tmp let-item="item" let-index="index" let-item$="item$">
      {{ item.id }} {{ item.name }}
    </ng-template>
  </ng-select>

custom-select.ts

this.dataList = [
  {id: 17, name: Ahsan Shah}, {id: 28, name: John Doe}, {id: 25, name: Muhammad Yousuf}
]

// wait & get default data from API and assign it to a variable
this.defaultListData = defaultResponse?.resources; // sample [{id: 25, name: Muhammad Yousuf}]

// then assign value to form group
this.componentFormGroup.controls[this.componentFormControlName].setValue(this.defaultListData);

What i am doing wrong? Thanks in advance


问:
Issue with GA4 tag setup and ads conversions
I am having an issue with Google Ads where none of my ads are showing conversions. When I contacted Google support, they told me that my GA4 tag was set up incorrectly and this was the issue however I copied the tag from the admin of my google account. The only error I can see is this one that shows up in tag assistant:

This is the code that I have installed on my website:

```<code><!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-XXXXXXXXXX');
    </script>
</code>```

I don't understand what the issue is, I copied it straight from the analytics admin. I asked support but they said they weren't trained in this area so couldn't help. Does anyone know why the tag is wrong and what I am missing that will enable me to see conversions in Google Ads?

Body:
I am having an issue with Google Ads where none of my ads are showing conversions. When I contacted Google support, they told me that my GA4 tag was set up incorrectly and this was the issue however I copied the tag from the admin of my google account. The only error I can see is this one that shows up in tag assistant:

This is the code that I have installed on my website:

I don't understand what the issue is, I copied it straight from the analytics admin. I asked support but they said they weren't trained in this area so couldn't help. Does anyone know why the tag is wrong and what I am missing that will enable me to see conversions in Google Ads?


问:
Mql4 I want to plot the data of the previous array
What I want to do is actually very simple. Create an array and pass any data to that array. Then I want to take the previous data of this array and draw it on the screen, but I cannot access the previous data of the array.</p>
```<code>  int start()
  {
   double up[];

   int limit;
   int counted_bars=IndicatorCounted();
   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
   limit=Bars-counted_bars;

   for(int i=0; i<limit; i++)
    {
     up[i] = Close[i]; //I am assigning the closing data to this array as an example.
     Line[i] = up[i+1]; //Line array is the name of the array to be displayed on the screen. I want to           assign the value of the previous up array to this array but it doesn't work.
    }
  }
</code>```

Body:
What I want to do is actually very simple. Create an array and pass any data to that array. Then I want to take the previous data of this array and draw it on the screen, but I cannot access the previous data of the array.

  int start()
  {
   double up[];

   int limit;
   int counted_bars=IndicatorCounted();
   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
   limit=Bars-counted_bars;

   for(int i=0; i<limit; i++)
    {
     up[i] = Close[i]; //I am assigning the closing data to this array as an example.
     Line[i] = up[i+1]; //Line array is the name of the array to be displayed on the screen. I want to           assign the value of the previous up array to this array but it doesn't work.
    }
  }


问:
Oracle command gives error while inserting - C#
I'm executing a regular Oracle insert query, I don't know why this error happens, any clue?

Insert query is a bit complicated, can't paste it here

is ParamInfo893e67a5-d0ab-4489-b8b3-4f5b05dbdb3d mean that the issue is because of Guide?

```<code>System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
   at Oracle.ManagedDataAccess.Client.OracleParameter.set_Size(Int32 value)
   at ParamInfo893e67a5-d0ab-4489-b8b3-4f5b05dbdb3d(IDbCommand , Object )
</code>```

Body:
I'm executing a regular Oracle insert query, I don't know why this error happens, any clue?

Insert query is a bit complicated, can't paste it here

is ParamInfo893e67a5-d0ab-4489-b8b3-4f5b05dbdb3d mean that the issue is because of Guide?

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
   at Oracle.ManagedDataAccess.Client.OracleParameter.set_Size(Int32 value)
   at ParamInfo893e67a5-d0ab-4489-b8b3-4f5b05dbdb3d(IDbCommand , Object )


问:
Tasks are not populated in concourse pipeline (Concourse version 7.8.2)
I am brand new to the concourse and trying to set up a pipeline through the pipeline but why am I getting this error on my very first pipeline, can anyone help out?

'''
jobs:

name: update-library-cache
serial: true
plan:

get: library_cache

get: infra
trigger: true

in_parallel:

{task: update-library-cache, file:infra/ci/tasks/update-preprod-library-cache.yml}

{put: library_cache, params: {file: updated_cache/infra-cache-*.tgz}}

name: build
serial: true
plan:

{get: api, trigger: true}

get: infra

get: library_cache

in_parallel:
-steps:

{task: js, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: js}, attempts:2}

{task: api, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: api}, attempts:2}

{task: worker, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: worker}, attempts:2}

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

When Executing pipeline:

the task: js , api and worker are not populating in the pipeline.

Is the syntax is correct for:

```<code>- in_parallel:
          -steps:
          - {task: js, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: js}, attempts:2}
          - {task: api, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: api}, attempts:2}
          - {task: worker, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: worker}, attempts:2}
</code>```

Body:
I am brand new to the concourse and trying to set up a pipeline through the pipeline but why am I getting this error on my very first pipeline, can anyone help out?

'''
jobs:

name: update-library-cache
serial: true
plan:

get: library_cache

get: infra
trigger: true

in_parallel:

{task: update-library-cache, file:infra/ci/tasks/update-preprod-library-cache.yml}

{put: library_cache, params: {file: updated_cache/infra-cache-*.tgz}}

name: build
serial: true
plan:

{get: api, trigger: true}

get: infra

get: library_cache

in_parallel:
-steps:

{task: js, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: js}, attempts:2}

{task: api, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: api}, attempts:2}

{task: worker, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: worker}, attempts:2}

When Executing pipeline:

the task: js , api and worker are not populating in the pipeline.

Is the syntax is correct for:

- in_parallel:
          -steps:
          - {task: js, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: js}, attempts:2}
          - {task: api, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: api}, attempts:2}
          - {task: worker, file: infra/ci/tasks/build-service.yml, privileged: true, params: {TARGET_CFG: ((alpha)), SERVICE: worker}, attempts:2}


问:
Import new data from a text file based on certain field criteria
I have a little VB knowledge but this one is way beyond my scope. This is a multipart problem I am trying to find a solution.

We have a tab delineated text file with 11 fields that is constantly updated by another program. We would like to copy/import just two fields of that data, let’s say fields #9 & #11 into Excel but only bring in the new data since the previous import. So if initially there are 5 lines of data, that would come in and populate the first 5 rows and 2 columns in a worksheet. Then subsequently it would bring in only anything added after the initial copy/import. I have been able to write a routine that simply copies everything and overwrites what is there but this is not what we want.

The next part of this is that based on certain criteria, the data will be copied/imported into certain columns. The criteria variables will be in fields #2 and #6. So for example, if field #2 = 1, and field #6 = 2, then fields #9 & #11 will go in columns A & B. If field #2 = 2 and field #6 = 1, then fields #9 & #11 will go into columns C&D. There would most likely be 6 possible combinations of those variables (1/1, ½, 1/3, 2/1, 2/2, 2/3) so columns A-L could be populated. Note that field #9 could be blank in which case it would just bring in field #11 or just copy the blank text. These variable numbers could be referenced to cells in the workbook where we select which variables will correspond to which columns. For example if we wanted columns A & B to contain the data with the variables 1 & 2, cells G1 & H1 could have #1 & #2 in their cells if that is helpful. There may be times when we want that variable combo of 2/1 to go into cells A & B.

Here is the text file:

0 1 2 0 0 1 b 1648 1648 9:55:02.61 09:55:03
0 2 5 0 0 1 b 1648 1659 9:57:45.70 09:57:46
0 2 7 0 0 2 b 1649 1649 9:58:09.84 09:58:10
0 3 8 0 0 1 s 9:58:09.87 09:58:10
0 1 9 0 0 1 b 1656 1656 9:58:13.80 09:58:15
0 1 11 0 0 1 b 1657 1657 9:58:19.88 09:58:20
0 3 12 0 0 1 s 9:58:19.93 09:58:20
0 1 13 0 0 1 b 1663 1663 9:58:25.77 09:58:26
0 1 14 0 0 2 s 9:58:25.78 09:58:26
0 1 15 0 0 2 s 9:59:22.40 09:59:23
0 2 16 0 0 1 b 1664 1664 9:59:22.41 09:59:23
0 2 17 0 0 2 s 1671 1671 9:59:26.33 09:59:27
```
<p>This is the text file and what the worksheet should look like</p>
<p><img src="https://i.stack.imgur.com/UOttp.png" alt="enter image description here" /></p>
<p>The last part is ideally this routine would only run when the text file has been updated but I am not sure how possible that is. Otherwise I can just put this on a timer that will run every minute or so.</p>
<p>Being a bit of neophyte with VBA I have found this forum to be an awesome resource so I hope I have explained this correctly. If this info is already posted somewhere please point me in that direction. I am always willing to learn but this one is bit beyond me right now.</p>
<p>As always, many thanks in advance.</p>
<p>I have a little VB knowledge but this one is way beyond my scope. This is a multipart problem I am trying to find a solution.</p>
<p>This is code we use to import the entire text file</p>
<pre class="lang-vb prettyprint-override"><code>Public Sub ImportSRTfile()
     Dim strSpec As String, i As Long, colToRet As Long, lastR As Long
     Dim arrSp As Variant, arrRez() As String, arrInt As Variant, j As Long, K As Long
     Dim FSO As Object, txtStr As Object, strText As String 'no need of any reference

      Set shT = ThisWorkbook.Sheets("srt_data")
      Set FSO = CreateObject("Scripting.FileSystemObject")
      strSpec = "C:\srt_timing\srt_data_acquisition_module\srt_backup_timer_data.txt"
      If Dir(strSpec) <> "" Then 'check if file exists
        Set txtStr = FSO.OpenTextFile(strSpec)
            strText = txtStr.ReadAll
        txtStr.Close
      End If
      arrSp = Split(strText, vbCrLf)

        colToRet = 11 'Number of columns to be returned
        lastR = shT.Range("A" & Rows.Count).End(xlUp).Row 'last row in A:A
        'arrRez is dimensioned from 0 to UBound(arrSp) only for lastR = 1
        ReDim arrRez(IIf(lastR = 1, 0, 1) To UBound(arrSp), colToRet - 1)
        For i = IIf(lastR = 1, 0, 1) To UBound(arrSp) 'Only in case of larR = 1, the
                                                      'head of the table is load in arr
          arrInt = Split(arrSp(i), vbTab)  'each strText line is split in an array
          If UBound(arrInt) > colToRet - 1 Then
              For j = 0 To colToRet - 1
                  arrRez(i, j) = arrInt(j) 'each array element is loaded in the arrRez
              Next j
          End If
        Next i
        'The array is dropped in the dedicated range (calculated using Resize):
        shT.Range("A" & IIf(lastR = 1, lastR, lastR + 1)).Resize(UBound(arrRez, 1), _
                                                    UBound(arrRez, 2) + 1).Value = arrRez

End Sub
</code>```

Body:
I have a little VB knowledge but this one is way beyond my scope. This is a multipart problem I am trying to find a solution.

We have a tab delineated text file with 11 fields that is constantly updated by another program. We would like to copy/import just two fields of that data, let’s say fields #9 & #11 into Excel but only bring in the new data since the previous import. So if initially there are 5 lines of data, that would come in and populate the first 5 rows and 2 columns in a worksheet. Then subsequently it would bring in only anything added after the initial copy/import. I have been able to write a routine that simply copies everything and overwrites what is there but this is not what we want.

The next part of this is that based on certain criteria, the data will be copied/imported into certain columns. The criteria variables will be in fields #2 and #6. So for example, if field #2 = 1, and field #6 = 2, then fields #9 & #11 will go in columns A & B. If field #2 = 2 and field #6 = 1, then fields #9 & #11 will go into columns C&D. There would most likely be 6 possible combinations of those variables (1/1, ½, 1/3, 2/1, 2/2, 2/3) so columns A-L could be populated. Note that field #9 could be blank in which case it would just bring in field #11 or just copy the blank text. These variable numbers could be referenced to cells in the workbook where we select which variables will correspond to which columns. For example if we wanted columns A & B to contain the data with the variables 1 & 2, cells G1 & H1 could have #1 & #2 in their cells if that is helpful. There may be times when we want that variable combo of 2/1 to go into cells A & B.

Here is the text file:

0 1 2 0 0 1 b 1648 1648 9:55:02.61 09:55:03
0 2 5 0 0 1 b 1648 1659 9:57:45.70 09:57:46
0 2 7 0 0 2 b 1649 1649 9:58:09.84 09:58:10
0 3 8 0 0 1 s 9:58:09.87 09:58:10
0 1 9 0 0 1 b 1656 1656 9:58:13.80 09:58:15
0 1 11 0 0 1 b 1657 1657 9:58:19.88 09:58:20
0 3 12 0 0 1 s 9:58:19.93 09:58:20
0 1 13 0 0 1 b 1663 1663 9:58:25.77 09:58:26
0 1 14 0 0 2 s 9:58:25.78 09:58:26
0 1 15 0 0 2 s 9:59:22.40 09:59:23
0 2 16 0 0 1 b 1664 1664 9:59:22.41 09:59:23
0 2 17 0 0 2 s 1671 1671 9:59:26.33 09:59:27

This is the text file and what the worksheet should look like

The last part is ideally this routine would only run when the text file has been updated but I am not sure how possible that is. Otherwise I can just put this on a timer that will run every minute or so.

Being a bit of neophyte with VBA I have found this forum to be an awesome resource so I hope I have explained this correctly. If this info is already posted somewhere please point me in that direction. I am always willing to learn but this one is bit beyond me right now.

As always, many thanks in advance.

I have a little VB knowledge but this one is way beyond my scope. This is a multipart problem I am trying to find a solution.

This is code we use to import the entire text file

Public Sub ImportSRTfile()
     Dim strSpec As String, i As Long, colToRet As Long, lastR As Long
     Dim arrSp As Variant, arrRez() As String, arrInt As Variant, j As Long, K As Long
     Dim FSO As Object, txtStr As Object, strText As String 'no need of any reference

      Set shT = ThisWorkbook.Sheets("srt_data")
      Set FSO = CreateObject("Scripting.FileSystemObject")
      strSpec = "C:\srt_timing\srt_data_acquisition_module\srt_backup_timer_data.txt"
      If Dir(strSpec) <> "" Then 'check if file exists
        Set txtStr = FSO.OpenTextFile(strSpec)
            strText = txtStr.ReadAll
        txtStr.Close
      End If
      arrSp = Split(strText, vbCrLf)

        colToRet = 11 'Number of columns to be returned
        lastR = shT.Range("A" & Rows.Count).End(xlUp).Row 'last row in A:A
        'arrRez is dimensioned from 0 to UBound(arrSp) only for lastR = 1
        ReDim arrRez(IIf(lastR = 1, 0, 1) To UBound(arrSp), colToRet - 1)
        For i = IIf(lastR = 1, 0, 1) To UBound(arrSp) 'Only in case of larR = 1, the
                                                      'head of the table is load in arr
          arrInt = Split(arrSp(i), vbTab)  'each strText line is split in an array
          If UBound(arrInt) > colToRet - 1 Then
              For j = 0 To colToRet - 1
                  arrRez(i, j) = arrInt(j) 'each array element is loaded in the arrRez
              Next j
          End If
        Next i
        'The array is dropped in the dedicated range (calculated using Resize):
        shT.Range("A" & IIf(lastR = 1, lastR, lastR + 1)).Resize(UBound(arrRez, 1), _
                                                    UBound(arrRez, 2) + 1).Value = arrRez

End Sub


问:
Typescript: How to find duplicates in array, (making a slot-machine game)
I am making a slot-machine game, and I have an array of numbers with 5 or 6 positions containing sorted numbers.

Some rules:

0 is the wild symbol. It forms a pay line with any other paying symbol. For example, if the received array was: [1, 2, 0, 2, 3], we have a pay line;

the paying symbols are: [1, 2, 3, 4, 5, 6, 7, 8, 9];

and there are the non-paying symbols, which are: [10, 11, 12, 13, 14, 15].

I need to build a function in Typescript that parses whether:

array contains at least 3 numbers repeated in sequence

if these repeated numbers are between 0 and 9

when negative returns an empty array as in the example "input [1, 2, 6, 7, 6] the expected output is [[1, 2, 6, 7, 6],[]]  as well [[array sorted],[empty array]]"

when positive, return an array as in the example "input [1, 2, 6, 6, 6] the expected output is [6, [2, 3, 4]]] as well [repeated number,[positions of repeated number]] "

```<code>type WinningCombinationsResult = [number, number[]][];

    function call(lines: number[]): WinningCombinationsResult {
      return ;
    }

export const WinningCombinations = { call };

</code>```

Body:
I am making a slot-machine game, and I have an array of numbers with 5 or 6 positions containing sorted numbers.

Some rules:

0 is the wild symbol. It forms a pay line with any other paying symbol. For example, if the received array was: [1, 2, 0, 2, 3], we have a pay line;

the paying symbols are: [1, 2, 3, 4, 5, 6, 7, 8, 9];

and there are the non-paying symbols, which are: [10, 11, 12, 13, 14, 15].

I need to build a function in Typescript that parses whether:

array contains at least 3 numbers repeated in sequence

if these repeated numbers are between 0 and 9

when negative returns an empty array as in the example "input [1, 2, 6, 7, 6] the expected output is [[1, 2, 6, 7, 6],[]]  as well [[array sorted],[empty array]]"

when positive, return an array as in the example "input [1, 2, 6, 6, 6] the expected output is [6, [2, 3, 4]]] as well [repeated number,[positions of repeated number]] "

type WinningCombinationsResult = [number, number[]][];

    function call(lines: number[]): WinningCombinationsResult {
      return ;
    }

export const WinningCombinations = { call };


问:
Could not connect to SMTP host: smtp.gmail.com, port: 587 in android
gave so many trails to send an attachment over mail but getting this error "javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is: java.net.NoRouteToHostException: Host unreachable"

Not getting what went wrong please find the below coding details

On button click calling the JavaMailAPI and passing the mailing details f=of both sender the receiver

JavaMailAPI.java

```<code>    public class JavaMailAPI extends javax.mail.Authenticator {
    private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;
    private Multipart _multipart = new MimeMultipart();
    static {
        Security.addProvider(new com.example.sendmail.JSSEProvider());
    }
    public JavaMailAPI(String user, String password) {
        this.user = user;
        this.password = password;
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.socketFactory.port", "587");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");
        session = Session.getDefaultInstance(props, this);
    }
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }
    public synchronized void sendMail(String subject, String body,
                                      String sender, String recipients) throws Exception {
        try {
            MimeMessage message = new MimeMessage(session);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(
                    body.getBytes(), "text/plain"));
            message.setSender(new InternetAddress(sender));
            message.setSubject(subject);
            message.setDataHandler(handler);
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            _multipart.addBodyPart(messageBodyPart);
            // Put parts in message
            message.setContent(_multipart);
            if (recipients.indexOf(',') > 0)
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(recipients));
            else
                message.setRecipient(Message.RecipientType.TO,
                        new InternetAddress(recipients));
            Transport.send(message);
        } catch (Exception e) {
        e.printStackTrace();
        }
    }
    public void addAttachment(String filename) throws Exception {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("download image");
        _multipart.addBodyPart(messageBodyPart);
    }
    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;
        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }
        public ByteArrayDataSource(byte[] data) {
            super();
            this.data = data;
        }
        public void setType(String type) {
            this.type = type;
        }
        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }
        public String getName() {
            return "ByteArrayDataSource";
        }
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }
    }
</code>```

JSSEProvider.java

```<code> public final class JSSEProvider extends Provider {
    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController
                .doPrivileged(new java.security.PrivilegedAction<Void>() {
                    public Void run() {
                        put("SSLContext.TLS",
                                "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                        put("Alg.Alias.SSLContext.TLSv1", "TLS");
                        put("KeyManagerFactory.X509",

"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                        put("TrustManagerFactory.X509",
                                "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                        return null;
                    }
                });
    }
    }
</code>```

Add added the below jars in gradle

```<code>implementation files('libs/activation.jar')
implementation files('libs/additionnal.jar')
implementation files('libs/mail.jar')
</code>```

And added Internet permission in manifest

Not getting what went wrong, please help me out to get it solved. Thank u

Body:
gave so many trails to send an attachment over mail but getting this error "javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is: java.net.NoRouteToHostException: Host unreachable"

Not getting what went wrong please find the below coding details

On button click calling the JavaMailAPI and passing the mailing details f=of both sender the receiver

JavaMailAPI.java

    public class JavaMailAPI extends javax.mail.Authenticator {
    private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;
    private Multipart _multipart = new MimeMultipart();
    static {
        Security.addProvider(new com.example.sendmail.JSSEProvider());
    }
    public JavaMailAPI(String user, String password) {
        this.user = user;
        this.password = password;
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.socketFactory.port", "587");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");
        session = Session.getDefaultInstance(props, this);
    }
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }
    public synchronized void sendMail(String subject, String body,
                                      String sender, String recipients) throws Exception {
        try {
            MimeMessage message = new MimeMessage(session);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(
                    body.getBytes(), "text/plain"));
            message.setSender(new InternetAddress(sender));
            message.setSubject(subject);
            message.setDataHandler(handler);
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            _multipart.addBodyPart(messageBodyPart);
            // Put parts in message
            message.setContent(_multipart);
            if (recipients.indexOf(',') > 0)
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(recipients));
            else
                message.setRecipient(Message.RecipientType.TO,
                        new InternetAddress(recipients));
            Transport.send(message);
        } catch (Exception e) {
        e.printStackTrace();
        }
    }
    public void addAttachment(String filename) throws Exception {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("download image");
        _multipart.addBodyPart(messageBodyPart);
    }
    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;
        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }
        public ByteArrayDataSource(byte[] data) {
            super();
            this.data = data;
        }
        public void setType(String type) {
            this.type = type;
        }
        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }
        public String getName() {
            return "ByteArrayDataSource";
        }
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }
    }

JSSEProvider.java

 public final class JSSEProvider extends Provider {
    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController
                .doPrivileged(new java.security.PrivilegedAction<Void>() {
                    public Void run() {
                        put("SSLContext.TLS",
                                "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                        put("Alg.Alias.SSLContext.TLSv1", "TLS");
                        put("KeyManagerFactory.X509",

"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                        put("TrustManagerFactory.X509",
                                "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                        return null;
                    }
                });
    }
    }

Add added the below jars in gradle

implementation files('libs/activation.jar')
implementation files('libs/additionnal.jar')
implementation files('libs/mail.jar')

And added Internet permission in manifest

Not getting what went wrong, please help me out to get it solved. Thank u


问:
How to show only Next three dates in date pciker in material ui
```<code>  <DesktopDatePicker
                          disablePast={true}
                          className={Styles.datewidth}
                          label="Select Date"
                          inputFormat="DD/MM/YYYY"
                          value={datesel}
                          onChange={setDatesel}
                          renderInput={(params) => <TextField {...params} />}
                        />
</code>```

I need to show only the next three days in date how should do that in material ui.

Body:
  <DesktopDatePicker
                          disablePast={true}
                          className={Styles.datewidth}
                          label="Select Date"
                          inputFormat="DD/MM/YYYY"
                          value={datesel}
                          onChange={setDatesel}
                          renderInput={(params) => <TextField {...params} />}
                        />

I need to show only the next three days in date how should do that in material ui.


问:
ggplot shape codes to hexadecimal
I have few data on a ggplot and on a table (type of kable) and I want to add a column on the kable with the same shapes I have on the ggplot, like the table below,

```<code>some_symbols <- c('\u25A0', '\u25B3','\u25CF','\u2605')
</code>```

(I found the hex codes here)

```<code>data.frame(
  Symbol =some_symbols,
  Description = rep("bla bla bla", 4),
  Result = rep("bla bla", 4)
) %>%
  mutate(
    Symbol = cell_spec(Symbol, escape = F)
  ) %>%
  kable(escape = F, align = c("c", "l", "l")) %>%
  kable_styling(full_width = F)
</code>```

However, I want to use the same symbols I have on my ggplot and avoid setting shapes on my own

```<code>p_trial <- mtcars[1:5, ] %>%
  ggplot(aes(x = cyl, y = hp, shape = interaction(vs, am), colour = interaction(vs, am))) +
  geom_point(size = 7)
</code>```

From the function ggplot_build(p_trial)$data[[1]] I can get the shape code but I cannot use it as input in my table as it's not a hexadecimal code.

At the same time, the colour from the above output is in convenient format and I can use it directly to modify the colour by doing

```<code>    data.frame(
      Symbol =some_symbols,
      Description = rep("bla bla bla", 4),
      Result = rep("bla bla", 4)
    ) %>%
      mutate(
        Symbol = cell_spec(Symbol,
     color = ggplot_build(p_trial )$data[[1]] %>% pull(colour),
 escape = F)
      )
</code>```

My question is, how can I turn ggplot shape codes to hexadecimal code or
how can I put in a table(type of kable) a column  with the same shapes used in ggplot?

Thanks

Title: ggplot shape codes to hexadecimal

Body:
I have few data on a ggplot and on a table (type of kable) and I want to add a column on the kable with the same shapes I have on the ggplot, like the table below,

some_symbols <- c('\u25A0', '\u25B3','\u25CF','\u2605')

(I found the hex codes here)

data.frame(
  Symbol =some_symbols,
  Description = rep("bla bla bla", 4),
  Result = rep("bla bla", 4)
) %>%
  mutate(
    Symbol = cell_spec(Symbol, escape = F)
  ) %>%
  kable(escape = F, align = c("c", "l", "l")) %>%
  kable_styling(full_width = F)

However, I want to use the same symbols I have on my ggplot and avoid setting shapes on my own

p_trial <- mtcars[1:5, ] %>%
  ggplot(aes(x = cyl, y = hp, shape = interaction(vs, am), colour = interaction(vs, am))) +
  geom_point(size = 7)

From the function ggplot_build(p_trial)$data[[1]] I can get the shape code but I cannot use it as input in my table as it's not a hexadecimal code.

At the same time, the colour from the above output is in convenient format and I can use it directly to modify the colour by doing

    data.frame(
      Symbol =some_symbols,
      Description = rep("bla bla bla", 4),
      Result = rep("bla bla", 4)
    ) %>%
      mutate(
        Symbol = cell_spec(Symbol,
     color = ggplot_build(p_trial )$data[[1]] %>% pull(colour),
 escape = F)
      )

My question is, how can I turn ggplot shape codes to hexadecimal code or
how can I put in a table(type of kable) a column  with the same shapes used in ggplot?

Thanks


问:
How to adjust cell height according to WebView in CollectionView?
i am making app with CollectionView and data loaded from my WordPress website. I have two cells in my collection view one for posts and second for AdMob ads. I have implemented WebView to fetch posts from Website in cell but the problem is i don't know how to set cell height according to the data , i mean if post height is 100 then cell height should be 100 and if if post height is 200 then cell height should be 200.. this is my code in CollectionViewCell

```<code>@IBOutlet weak var heightWeb: NSLayoutConstraint!

@IBOutlet weak var webView: WKWebView!

func setup(with hukam: Post) {

    let htmlString:String = "<html><head><style type=\"text/css\"> body {font-family: \"SFUIText-Regular\"; text-align: center; font-size: 38; line-height:55px; } img { max-width: 100%; width: auto; height: auto; } iframe { max-width: auto; width: auto; height: auto; }</style> </head><body>"+hukam.content.rendered+"</body></html>"

          self.webView.loadHTMLString(htmlString, baseURL: nil)
    }

func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    print("Start loading")
    }

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("End loading")
   DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        self.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
            if complete != nil {
                self.webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
                   self.heightWeb.constant = webView.scrollView.contentSize.height

                })
            }
        })

    }
</code>```

and when i print it in ViewController like this .

```<code> let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postcell", for: indexPath) as! StatusViewCell

        print (cell.webView.scrollView.contentSize.height)

        cell.setup(with: newsData[indexPath.row-(indexPath.row/5)])

        heightcell = Int(cell.webView.scrollView.contentSize.height)
        print ("Height cell is" , heightcell)

        return cell
</code>```

i get the right size of webView but how can i implement it in sizeForItemAt ?

this is my code..

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    var returnValue = CGSize()

    if UIScreen.main.bounds.size.height > 960{ //Write iPhone or iPad size. If iPad :
            returnValue = CGSize(width: (((view.frame.width) - 40) / 2), height: 180)
        } else { //if iPhone
            returnValue = CGSize(width: view.frame.width-20 , height: 180)
        }

    return returnValue
</code>```

this is output screenshot

please help..

Body:
i am making app with CollectionView and data loaded from my WordPress website. I have two cells in my collection view one for posts and second for AdMob ads. I have implemented WebView to fetch posts from Website in cell but the problem is i don't know how to set cell height according to the data , i mean if post height is 100 then cell height should be 100 and if if post height is 200 then cell height should be 200.. this is my code in CollectionViewCell

@IBOutlet weak var heightWeb: NSLayoutConstraint!

@IBOutlet weak var webView: WKWebView!

func setup(with hukam: Post) {

    let htmlString:String = " "+hukam.content.rendered+""

          self.webView.loadHTMLString(htmlString, baseURL: nil)
    }

func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    print("Start loading")
    }

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("End loading")
   DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        self.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
            if complete != nil {
                self.webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
                   self.heightWeb.constant = webView.scrollView.contentSize.height

                })
            }
        })

    }

and when i print it in ViewController like this .

 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postcell", for: indexPath) as! StatusViewCell

        print (cell.webView.scrollView.contentSize.height)

        cell.setup(with: newsData[indexPath.row-(indexPath.row/5)])

        heightcell = Int(cell.webView.scrollView.contentSize.height)
        print ("Height cell is" , heightcell)

        return cell

i get the right size of webView but how can i implement it in sizeForItemAt ?

this is my code..

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    var returnValue = CGSize()

    if UIScreen.main.bounds.size.height > 960{ //Write iPhone or iPad size. If iPad :
            returnValue = CGSize(width: (((view.frame.width) - 40) / 2), height: 180)
        } else { //if iPhone
            returnValue = CGSize(width: view.frame.width-20 , height: 180)
        }

    return returnValue

this is output screenshot

please help..


问:
Duplicate Class Error while Include library Solona
Build Gradle

ext.kotlin_version = '1.7.21'

 classpath 'com.android.tools.build:gradle:7.2.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4' classpath 'com.google.gms:google-services:4.3.10' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.5.2' classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.5.3"

implementation 'com.solana:solana:2.0'

Error

Duplicate class com.google.protobuf.AbstractMessageLite found in modules jetified-protobuf-java-3.6.1 (com.google.protobuf:protobuf-java:3.6.1) and jetified-protobuf-javalite-3.14.0 (com.google.protobuf:protobuf-javalite:3.14.0)      Duplicate class com.google.protobuf.AbstractMessageLite$Builder found in modules jetified-protobuf-java-3.6.1 (com.google.protobuf:protobuf-java:3.6.1) and jetified-protobuf-javalite-3.14.0 (com.google.protobuf:protobuf-javalite:3.14.0)      Duplicate class com.google.protobuf.AbstractMessageLite$Builder$LimitedInputStream found in modules jetified-protobuf-java-3.6.1 (com.google.protobuf:protobuf-java:3.6.1) and jetified-protobuf-javalite-3.14.0 (com.google.protobuf:protobuf-javalite:3.14.0)      Duplicate class com.google.protobuf.AbstractParser found in modules ` `


问:
Accessing anonymous types returned via a dynamic link query
I have been trying to access the data returned from a dynamic linq query as an anonymous type. The advice I have found suggests that I should create a custom type and use it in the Select clause with the new keyword. I was directed to the followed Question for a code example:

System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>)

This was indeed an excellent example which I incorporated into my code (which is VB so I had to do some translation).

My code compiles fine but When I run it , I get the error following error:

"Value cannot be null. Parameter name: member"  at the following line from the example:
bindings[i] = Expression.Bind(type.GetProperty(properties[i].Name), expressions[i]);

This seems to be linked to expressions(i), which correctly contains two items as I am returning two fields from the database table. properties(i) holds the name of those two fields correctly. Any ideas as to what the value for member is supposed to be and where it should be found? Is it something from the database?

The where clause of this query works and when I run it as an anonymous type it brings back records (or rather two fields from records).  The returned fields contain data not nulls.

Here is my VB version of the code from the example provided in the earlier Question. I have bolded or ** the line where the error occurs. Any ideas as to what is causing this?

Much appreciated.

Function ParseNew() As Expression
        NextToken()
        ValidateToken(TokenId.OpenParen, Res.OpenParenExpected)
        NextToken()
        Dim properties As New List(Of DynamicProperty)()
        Dim expressions As New List(Of Expression)()
        Do
            Dim exprPos = tokenVal.pos
            Dim expr = ParseExpression()
            Dim propName As String
            If TokenIdentifierIs("as") Then
                NextToken()
                propName = GetIdentifier()
                NextToken()
            Else
                Dim [me] As MemberExpression = TryCast(expr, MemberExpression)
                If [me] Is Nothing Then Throw ParseError(exprPos, Res.MissingAsClause)
                propName = [me].Member.Name
            End If
            expressions.Add(expr)
            properties.Add(New DynamicProperty(propName, expr.Type))
            If tokenVal.id <> TokenId.Comma Then Exit Do
            NextToken()
        Loop
        ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected)
        NextToken()
        'CODE added to support strongly-typed returns
        Dim type As Type = If(newResultType, DynamicExpression.CreateClass(properties))
        Dim bindings(properties.Count - 1) As MemberBinding
        For i As Integer = 0 To bindings.Length - 1
            **bindings(i) = Expression.Bind(type.GetProperty(properties(i).Name), expressions(i))**
        Next
        Return Expression.MemberInit(Expression.[New](type), bindings)
    End Function
```

ContentLicense: CC BY-SA 3.0


问:
StoreKit 2 Sandbox use can't buy the same subscription again
My StoreKit 2 tests flow looks like this:

Buy subscription lvl 1

Buy subscription lvl 2

Buy subscription lvl 1

The problem is that when trying to buy the same subscription again with Sandbox user - the iOS dialogs to confirm Payment are not shown. Product.PurchaseResult in .success but if checking in Settings - the subscription is not changed.

What's also interesting: it works if changes directly from System Settings.

Any ideas of what is going on would be appreciated.


问:
ERR_EMPTY_RESPONSE when trying to access Scotty Application which runs in WSL2
I am building a web application using Scotty and have installed GHC and Cabal using GHCup inside of WSL2 (Windows Subsystem for Linux 2). The application worked when I ran it natively on Windows. I am running the application on port 3000 and I am certain that the port is free. When I try to access the application through a browser from Windows, I receive an ERR_EMPTY_RESPONSE error. I have tried using both localhost:3000 and 127.0.1.1:3000, which is the output of wsl hostname -i, but I still get the same error. Even when I try to curl the application from inside WSL2, I get the same output. However, when I spin up an nginx server inside WSL2, it works as expected and I can access it from both WSL2 and Windows.

The interesting thing is that Scotty can see the requests and even thinks that it is successfully replying to them (as indicated by the 200 response codes):

```<code>Setting phasers to stun... (port 3000) (ctrl-c to quit)
GET /
  Accept: */*
  Status: 200 OK 0.000570011s
GET /
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
  Status: 200 OK 0.000548668s
GET /
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
  Status: 200 OK 0.000659229s
</code>```

Body:
I am building a web application using Scotty and have installed GHC and Cabal using GHCup inside of WSL2 (Windows Subsystem for Linux 2). The application worked when I ran it natively on Windows. I am running the application on port 3000 and I am certain that the port is free. When I try to access the application through a browser from Windows, I receive an ERR_EMPTY_RESPONSE error. I have tried using both localhost:3000 and 127.0.1.1:3000, which is the output of wsl hostname -i, but I still get the same error. Even when I try to curl the application from inside WSL2, I get the same output. However, when I spin up an nginx server inside WSL2, it works as expected and I can access it from both WSL2 and Windows.

The interesting thing is that Scotty can see the requests and even thinks that it is successfully replying to them (as indicated by the 200 response codes):

Setting phasers to stun... (port 3000) (ctrl-c to quit)
GET /
  Accept: */*
  Status: 200 OK 0.000570011s
GET /
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
  Status: 200 OK 0.000548668s
GET /
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
  Status: 200 OK 0.000659229s


问:
App doesn't reconnect to a Bluetooth device when it is in the background
I have an app that uses Bluetooth (BLE). All BLE communication works fine. State restoration is also implemented and works well. The app has automatic re-connection implementation: whenever the CBError.peripheralDisconnected error occurs, the app tries to reconnect to the peripheral by calling cbCentralManager.connect(cbPeripheral).

Since iOS 15/16 there is a problem. Let's assume that the app is connected to a specific BLE device. I turn off the device (at this moment the automatic re-connection started) and move the app to the background. After several hours (e.g. over the night) I turn on the BLE device and the connection isn't established. I can see this on my Bluetooth device and in the iOS Bluetooth settings. Only when I open the app again, the connection is established immediately. Nothing happens in between. Only the connect call of the CBCentralManager after the Bluetooth device is turned off. The whole thing works when the app is in the background for 3 - 5 hours. If it is over approx. 5 hours, the connection is no longer established as soon as the app is in the background.

At first I thought that the app or the BLE connection is simply killed by the system after a long time. However, the state restoration for Bluetooth is implemented and works (I tested it).

Does anyone have any idea what this could be? Are there perhaps any new settings for state restoration or Bluetooth background mode since iOS 15/16?

Many thanks in advance.


问:
TypeScript passing a function as a parameter: bind vs anonymous
In TypeScript I have a code snippet like this:

private async predicate(some_parameter: string): Promise<boolean> {
           output = await api_call(some_parameter);
           return output !== undefined;
}
```
<p>Now I can call it in two ways:</p>
<pre class="lang-js prettyprint-override"><code>await RepeaterUtil.monitor(this.predicate.bind(this, some_parameter));
</code>```

await RepeaterUtil.monitor(() => this.predicate(some_parameter));
```

Basically it will monitor till the time the predicate is not undefined (some value).

The question I have:

Although both are functionally working - which one is preferred (bind or calling anonymously) and why?

Purpose of the question:
Best possible way to write code following TypeScript rules (bestpractices).

Body:
In TypeScript I have a code snippet like this:

private async predicate(some_parameter: string): Promise<boolean> {
           output = await api_call(some_parameter);
           return output !== undefined;
}

Now I can call it in two ways:

await RepeaterUtil.monitor(this.predicate.bind(this, some_parameter));

await RepeaterUtil.monitor(() => this.predicate(some_parameter));

Basically it will monitor till the time the predicate is not undefined (some value).

The question I have:

Although both are functionally working - which one is preferred (bind or calling anonymously) and why?

Purpose of the question:
Best possible way to write code following TypeScript rules (bestpractices).


问:
To get a null value if data is not present in the table
```<code>select number2, number3
from table3
where acc_num3 = 1234
union
select number2, null as number3
from table2
where acc_num2 = 1234
</code>```

I have a query as above, I need an output as null if the number mentioned (in where condition)is not present in either of the tables

I am getting the o/p for the above query correctly, but when i try a number that is not present in either of tables I need to get an o/p as null, null... but i am getting only column names and no data

Body:
select number2, number3
from table3
where acc_num3 = 1234
union
select number2, null as number3
from table2
where acc_num2 = 1234

I have a query as above, I need an output as null if the number mentioned (in where condition)is not present in either of the tables

I am getting the o/p for the above query correctly, but when i try a number that is not present in either of tables I need to get an o/p as null, null... but i am getting only column names and no data


问:
OneSignal setNotificationOpenedHandler Navigation not working when app is fully closer
```<code> OneSignal.shared.setNotificationOpenedHandler(
            (OSNotificationOpenedResult result) {
              // This prints the entire notification payload.
              print(
                  "OneSignal Notification: ${result.notification.jsonRepresentation().replaceAll('\\n', '\n')}");
              SharedPreferences.getInstance().then(
                (prefs) {
                  prefs.setString(
                      'energyEntry',
                      result.notification.additionalData!['energyEntry'] ??
                          'null');
                  prefs.setString(
                      'energyType',
                      result.notification.additionalData!['energyType'] ??
                          'null');
                  prefs.setString(
                      'entryDate',
                      result.notification.additionalData!['entryDate'] ??
                          '0000-00-00');
                },
              );
              if (result.notification.additionalData!['energyEntry'] ==
                  'true') {

                navigatorKey.currentState!
                    .pushReplacement(
                      MaterialPageRoute(
                          builder: (context) =>
                              const DrawerScreenConsumptionInput()),
                    )
                    .onError((error, stackTrace) =>
                        print('error: $error, stackTrace: $stackTrace'));
              }
            },
          );
</code>```

This is my code when app is on background the notification open handler works fine when app is fully closed it triggers again but the navigator is not called

Body:
 OneSignal.shared.setNotificationOpenedHandler(
            (OSNotificationOpenedResult result) {
              // This prints the entire notification payload.
              print(
                  "OneSignal Notification: ${result.notification.jsonRepresentation().replaceAll('\\n', '\n')}");
              SharedPreferences.getInstance().then(
                (prefs) {
                  prefs.setString(
                      'energyEntry',
                      result.notification.additionalData!['energyEntry'] ??
                          'null');
                  prefs.setString(
                      'energyType',
                      result.notification.additionalData!['energyType'] ??
                          'null');
                  prefs.setString(
                      'entryDate',
                      result.notification.additionalData!['entryDate'] ??
                          '0000-00-00');
                },
              );
              if (result.notification.additionalData!['energyEntry'] ==
                  'true') {

                navigatorKey.currentState!
                    .pushReplacement(
                      MaterialPageRoute(
                          builder: (context) =>
                              const DrawerScreenConsumptionInput()),
                    )
                    .onError((error, stackTrace) =>
                        print('error: $error, stackTrace: $stackTrace'));
              }
            },
          );

This is my code when app is on background the notification open handler works fine when app is fully closed it triggers again but the navigator is not called


问:
Github API: two_factor_requirement_enabled is nil

Steps to reproduce

I'm using Github api with Github apps:

I am logged in with owner org user

and provide next permissions:

Read access to actions,

administration,

deployments,

environments,

issues,

metadata,

pull requests.

Then

I get org info with next endpoint: https://docs.github.com/en/rest/orgs/orgs?apiVersion=2022-11-28#get-an-organization

I retrieve some data

Problem

The problem is that two_factor_requirement_enabled field is always nil

What I tried

I tried to configure it in Github settings with the following instruction, but the problem persists:

https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa/configuring-two-factor-authentication

Relevant documentation

Does this API endpoint works with Github App like it mentioned in documentation?

```<code>1.configure MFA in organization settings
2. run next endpoint: https://docs.github.com/en/rest/orgs/orgs?apiVersion=2022-11-28#get-an-organization
3. check the result in two_factor_requirement_enabled field.
im expecting to see here true or false value, but receive nil
</code>```

Body:
Steps to reproduce

I'm using Github api with Github apps:

I am logged in with owner org user

and provide next permissions:

Read access to actions,

administration,

deployments,

environments,

issues,

metadata,

pull requests.

Then

I get org info with next endpoint: https://docs.github.com/en/rest/orgs/orgs?apiVersion=2022-11-28#get-an-organization

I retrieve some data

Problem

The problem is that two_factor_requirement_enabled field is always nil

What I tried

I tried to configure it in Github settings with the following instruction, but the problem persists:

https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa/configuring-two-factor-authentication

Relevant documentation

Does this API endpoint works with Github App like it mentioned in documentation?

1.configure MFA in organization settings
2. run next endpoint: https://docs.github.com/en/rest/orgs/orgs?apiVersion=2022-11-28#get-an-organization
3. check the result in two_factor_requirement_enabled field.
im expecting to see here true or false value, but receive nil


问:
Open file in active WSL window from Windows Explorer VS Code
Whenever I double click to open a file from Windows Explorer VS Code loads up a new Window to open up the file. I want the file to open up in the current active window (which in this case WSL Window).</p>


问:
Jwt Token Problems
ı want to do authorize in my mvc app ı have swagger api and ı m using api method Auth/Login and ı have JWT token key but ı can authorize  what ı miss.

```<code>[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel loginViewModel)
        {

            var response = await _client.PostAsJsonAsync("Auth/Login",loginViewModel);

            if (response.IsSuccessStatusCode)
            {
                //var body =await response.Content.ReadFromJsonAsync<LoginResponse>();
                var body=await response.Content.ReadAsStringAsync();

                LoginResponse loginResponse=JsonConvert.DeserializeObject<LoginResponse>(body);
                var token = loginResponse.Token;

 var tokenHandler = new JwtSecurityTokenHandler();

                return RedirectToAction("Index", "Dashboard");

            }
            return View("Index",loginViewModel);

        }
</code>```

here is my mvc login code and my Dashboar auth code

```<code>[Authorize]
    public class DashboardController : Controller
    {

        public IActionResult Index()
        {
            return View();
        }
        }
</code>```

thaks for helping

Title: Jwt Token Problems

Body:
ı want to do authorize in my mvc app ı have swagger api and ı m using api method Auth/Login and ı have JWT token key but ı can authorize  what ı miss.

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel loginViewModel)
        {

            var response = await _client.PostAsJsonAsync("Auth/Login",loginViewModel);

            if (response.IsSuccessStatusCode)
            {
                //var body =await response.Content.ReadFromJsonAsync<LoginResponse>();
                var body=await response.Content.ReadAsStringAsync();

                LoginResponse loginResponse=JsonConvert.DeserializeObject<LoginResponse>(body);
                var token = loginResponse.Token;

 var tokenHandler = new JwtSecurityTokenHandler();

                return RedirectToAction("Index", "Dashboard");

            }
            return View("Index",loginViewModel);

        }

here is my mvc login code and my Dashboar auth code

[Authorize]
    public class DashboardController : Controller
    {

        public IActionResult Index()
        {
            return View();
        }
        }

thaks for helping


问:
Company Binding Issue in NetSuiet via SuiteScript
In SuiteScript 2.0, I'm getting Partner's internal ID in Saved Search.For that Internal ID, there is One Customer also. But when I tried to set it in Contact's Company field it is always choose Customer over Partner. But I should bind Partner only. Any help would be appreciated.

I tried to try record.attach from Contact record to Partner Record. But it didn't work.


问:
Mask text input while typing in forms forms.office.com
Is there a way to mask input text like Phone number in display when user enters it in forms in forms.office.com.

What alternative we have apart from creating web application or coding some other SharePoint or way to quick create forms to get survey or user data that masks input text in display.

Any help Appreciated.