问:
How to calculate Maximum number of days where rainfall is less than 1mm in excel
Please I'm trying to calculate the maximum consecutive days without rainfall within a 1 year block of data in excel.

Here is the code I used:

```<code>=MAX(FREQUENCY(IF($D$2:$D$367<0.1, ROW($D$2:$D$367)), IF($D$3:$D$367>=0.1, ROW($D$3:$D$367))))
</code>```

where cell D2:D367 is my block of data for daily rainfall amount in a year. It worked earlier, but now I re-opened the document to run the same code for another set of data. However, I keep getting the "#Value!" error in excel. Can anyone help please?

Body:
Please I'm trying to calculate the maximum consecutive days without rainfall within a 1 year block of data in excel.

Here is the code I used:

=MAX(FREQUENCY(IF($D$2:$D$367<0.1, ROW($D$2:$D$367)), IF($D$3:$D$367>=0.1, ROW($D$3:$D$367))))

where cell D2:D367 is my block of data for daily rainfall amount in a year. It worked earlier, but now I re-opened the document to run the same code for another set of data. However, I keep getting the "#Value!" error in excel. Can anyone help please?


来源: stackexchange

问:
Run command in windows vm in azure using python sdk
I'm able to execute the run command using python for Linux Azure VM's as mention in this link

For Windows, it works for a basic print out such below.

```<code>run_command_parameters = {
    'command_id': 'RunPowerShellScript',
    'script': [
        '$arg1 = "hello world"',
        'echo $arg1'
    ]
}
</code>```

However, I'm not able to pass parameters. Anyone experienced this and know a solution?

```<code>run_command_parameters = {
    'command_id': 'RunPowerShellScript',
    'script': [
        'echo $arg1'
    ],
    'parameters':[
        {'name':"arg1", 'value':"hello world"}
    ]
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm able to execute the run command using python for Linux Azure VM's as mention in this link

For Windows, it works for a basic print out such below.

run_command_parameters = {
    'command_id': 'RunPowerShellScript',
    'script': [
        '$arg1 = "hello world"',
        'echo $arg1'
    ]
}

However, I'm not able to pass parameters. Anyone experienced this and know a solution?

run_command_parameters = {
    'command_id': 'RunPowerShellScript',
    'script': [
        'echo $arg1'
    ],
    'parameters':[
        {'name':"arg1", 'value':"hello world"}
    ]
}


问:
Debugging python code using Snowflake connector with authenticator:externalbrowser in Visual Studio Code
im trying to debug an app that is using the connector using the authenticator:externalbrowser configuration. It works running python from the command prompt, but when I try to debug it using Visual Studio code it doesnt open the browser window and it hangs. What could be that?

im using visual studio code 1.74, and python 3.10 with snowflake connector.

ran the program in command prompt and it worked. Ran in Visual Studio code and it hangs.


问:
.NET Core + Angular project, how to change npm build configuration depending on dotnet build configuration
Im building a .netcore + angular application. I have a dockerfile that will build the app with -c Debug and one that will build the app with -c release. I notice in both cases npm is building the angular project using 'npm run build -- --configuration production'. Is there a way I can build the angular part in development configuration when I build the app using the -c Debug flag?

I found the npm build command in the csproj file:

```<code>  <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
<!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build -- --configuration production" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr -- --configuration production" Condition=" '$(BuildServerSideRenderer)' == 'true' " />

<!-- Include the newly-built files in the publish output -->
<ItemGroup>
  <DistFiles Include="$(SpaRoot)dist\**; $(SpaRoot)dist-server\**" />
  <DistFiles Include="$(SpaRoot)node_modules\**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
  <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
    <RelativePath>%(DistFiles.Identity)</RelativePath>
    <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
  </ResolvedFileToPublish>
</ItemGroup>
</code>```

Command used by dockerfile:

```<code>    WORKDIR /src/CMS
RUN dotnet build 000000.csproj -c Debug -o /app

FROM build AS publish
RUN dotnet publish 000000.csproj -c Debug -o /app
</code>```

I also tried setting the following environment variables in the container but no change

```<code>  - ASPNETCORE_ENVIRONMENT=Production
  - ASPNETCORE_ENVIRONMENT=Development
</code>```

Is there a  way to change the --configuration production|development depending on the dotnet -C Release|Debug flag?

Body:
Im building a .netcore + angular application. I have a dockerfile that will build the app with -c Debug and one that will build the app with -c release. I notice in both cases npm is building the angular project using 'npm run build -- --configuration production'. Is there a way I can build the angular part in development configuration when I build the app using the -c Debug flag?

I found the npm build command in the csproj file:

  <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">

<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build -- --configuration production" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr -- --configuration production" Condition=" '$(BuildServerSideRenderer)' == 'true' " />

<ItemGroup>
  <DistFiles Include="$(SpaRoot)dist\**; $(SpaRoot)dist-server\**" />
  <DistFiles Include="$(SpaRoot)node_modules\**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
  <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
    <RelativePath>%(DistFiles.Identity)</RelativePath>
    <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
  </ResolvedFileToPublish>
</ItemGroup>

Command used by dockerfile:

    WORKDIR /src/CMS
RUN dotnet build 000000.csproj -c Debug -o /app

FROM build AS publish
RUN dotnet publish 000000.csproj -c Debug -o /app

I also tried setting the following environment variables in the container but no change

  - ASPNETCORE_ENVIRONMENT=Production
  - ASPNETCORE_ENVIRONMENT=Development

Is there a  way to change the --configuration production|development depending on the dotnet -C Release|Debug flag?


问:
Clang cross compilation in C
I would like to cross compile my C code to other platforms, is there a way to cross compile it on everything ("everything" in here being everything that could support C), If my code is only using standard library headers?

(preferably I would like to not have to include any platform specific includes)

I tried compiling normal code using clang from linux to windows, but there were some problems
(
fatal error: 'stdlib.h' file not found
#include <stdlib.h>
)

Title: Clang cross compilation in C


问:
Is there something preventing the Banno plugins from populating?
We have a plugin turned on for providing credit score. When logging in via app or desktop the card will not populate any information. Attaching screenshots as it looks like it is timing out but it is not providing an error. Tested multiple devices and profiles.

Logging into online banking and the plugin card does not work properly.


问:
Omitting NAs from Data
First time posting. Apologies if I'm not as clear as I intend.

I have an excel (xlxs) spreadsheet of data; it's sequencing data if that helps. Generally indexed as follows:
column 1 = organism families (hundreds of organisms down this column)
columns 2-x = specific samples

Many of the boxes scattered throughout the data are zero values, or too low, which I want to omit. I set my data such that anything under 5 is set to an NA. Since different samples will have many more, less, or different species omitted by that threshold, I want to separate by samples. Code so far is:

```<code>#Files work, I just omitted my directories to place online
`my_counts <- read_excel("...Family_120821.xlsx" , sheet = "family_Counts")
my_perc <- read_excel("...Family_120821.xlsx" , sheet = "family_Percentages")
my_counts[my_counts < 5] <- NA
my_counts
my_perc[my_perc < 0.05] <- NA
my_perc

S13 <- my_counts$family , my_counts$Sample.13
S13A <- na.omit(S13)
S13A

S14 <- my_counts$Sample.14
S14A <- na.omit(S14)
S14A

S15 <- my_counts$Sample.15
S15A <- na.omit(S15)
S15A

...
</code>```

First question, there a better way I can go about this such that I can replicate it in different data without typing out each individual sample?
Most important question: When I do this, I get what I want, which is the values I want, no NAs. But they are values, when I want another dataframe so I can write it back to an xlxs. As I have it, I lose the association to the organism.

Ex: Before

All samples by associated organisms

Ex: After

Single sample, no NAs, but also no association to organism index

Essentially the following image, but broken into individual samples. With only the organisms that met my threshold of 5 for counts, 0.05 for percents.

enter image description here

Title: Omitting NAs from Data

Body:
First time posting. Apologies if I'm not as clear as I intend.

I have an excel (xlxs) spreadsheet of data; it's sequencing data if that helps. Generally indexed as follows:
column 1 = organism families (hundreds of organisms down this column)
columns 2-x = specific samples

Many of the boxes scattered throughout the data are zero values, or too low, which I want to omit. I set my data such that anything under 5 is set to an NA. Since different samples will have many more, less, or different species omitted by that threshold, I want to separate by samples. Code so far is:

#Files work, I just omitted my directories to place online
`my_counts <- read_excel("...Family_120821.xlsx" , sheet = "family_Counts")
my_perc <- read_excel("...Family_120821.xlsx" , sheet = "family_Percentages")
my_counts[my_counts < 5] <- NA
my_counts
my_perc[my_perc < 0.05] <- NA
my_perc

S13 <- my_counts$family , my_counts$Sample.13
S13A <- na.omit(S13)
S13A

S14 <- my_counts$Sample.14
S14A <- na.omit(S14)
S14A

S15 <- my_counts$Sample.15
S15A <- na.omit(S15)
S15A

...

First question, there a better way I can go about this such that I can replicate it in different data without typing out each individual sample?
Most important question: When I do this, I get what I want, which is the values I want, no NAs. But they are values, when I want another dataframe so I can write it back to an xlxs. As I have it, I lose the association to the organism.

Ex: Before

All samples by associated organisms

Ex: After

Single sample, no NAs, but also no association to organism index

Essentially the following image, but broken into individual samples. With only the organisms that met my threshold of 5 for counts, 0.05 for percents.

enter image description here


问:
Not able to mount multiple targets (subnets) to a EFS file share
I am trying to create multiple mount targets using 3 subnet ids to a single file system through terraform. While running the code it is creating 2 file shares (the second one without a mount target) and then failing giving me the below error.

Error: putting EFS file system (fs-0c479ab4b699829d1) lifecycle configuration: InvalidParameter: 1 validation error(s) found.
│ - missing required field, PutLifecycleConfigurationInput.LifecyclePolicies.

Here's my EFS code.

```<code>resource "aws_efs_file_system" "efs" {
  creation_token   = var.efs_token
  performance_mode = var.efs_performance_mode
  encrypted        = true

  lifecycle_policy {
    transition_to_ia = "AFTER_30_DAYS"
  }

  tags = local.mandatory_tags

}

resource "aws_efs_mount_target" "efs_mount" {
  count = length(data.aws_subnets.private.*.id)
  depends_on = [aws_efs_file_system.efs]
  file_system_id  = "${aws_efs_file_system.efs.id}"
  subnet_id       = "${element(data.aws_subnets.private.*.id, count.index)}"
}

resource "aws_efs_backup_policy" "efs_backup_policy" {
  file_system_id = "${aws_efs_file_system.efs.id}"

  backup_policy {
    status = "ENABLED"
  }
}
</code>```

This is the EFS lifecycle policy

```<code>resource "aws_efs_file_system_policy" "policy" {
  file_system_id = aws_efs_file_system.efs.id

  bypass_policy_lockout_safety_check = true

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Id": "ExamplePolicy01",
    "Statement": [
        {
            "Sid": "ExampleStatement01",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Resource": "${aws_efs_file_system.efs.arn}",
            "Action": [
                "elasticfilesystem:ClientMount",
                "elasticfilesystem:ClientWrite"
            ],
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "true"
                }
            }
        }
    ]
}
POLICY
}
</code>```
```<code>data.tf

data "aws_vpc" "this" {
  filter {
    name   = "tag:Name"
    values = ["${local.name_prefix}-vpc"]
  }
}

data "aws_subnets" "private" {

  count    = length(data.aws_availability_zones.azs.names)
  filter {
    name   = "tag:Name"
    values = ["${local.name_prefix}-vpc-private*"]
  }
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.this.id]
  }
}

data "aws_availability_zones" "azs" {}
</code>```
```<code>tfvars

efs_token                        = "dev-load-test"
efs_performance_mode             = "maxIO"
</code>```

Body:
I am trying to create multiple mount targets using 3 subnet ids to a single file system through terraform. While running the code it is creating 2 file shares (the second one without a mount target) and then failing giving me the below error.

Error: putting EFS file system (fs-0c479ab4b699829d1) lifecycle configuration: InvalidParameter: 1 validation error(s) found.
│ - missing required field, PutLifecycleConfigurationInput.LifecyclePolicies.

Here's my EFS code.

resource "aws_efs_file_system" "efs" {
  creation_token   = var.efs_token
  performance_mode = var.efs_performance_mode
  encrypted        = true

  lifecycle_policy {
    transition_to_ia = "AFTER_30_DAYS"
  }

  tags = local.mandatory_tags

}

resource "aws_efs_mount_target" "efs_mount" {
  count = length(data.aws_subnets.private.*.id)
  depends_on = [aws_efs_file_system.efs]
  file_system_id  = "${aws_efs_file_system.efs.id}"
  subnet_id       = "${element(data.aws_subnets.private.*.id, count.index)}"
}

resource "aws_efs_backup_policy" "efs_backup_policy" {
  file_system_id = "${aws_efs_file_system.efs.id}"

  backup_policy {
    status = "ENABLED"
  }
}

This is the EFS lifecycle policy

resource "aws_efs_file_system_policy" "policy" {
  file_system_id = aws_efs_file_system.efs.id

  bypass_policy_lockout_safety_check = true

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Id": "ExamplePolicy01",
    "Statement": [
        {
            "Sid": "ExampleStatement01",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Resource": "${aws_efs_file_system.efs.arn}",
            "Action": [
                "elasticfilesystem:ClientMount",
                "elasticfilesystem:ClientWrite"
            ],
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "true"
                }
            }
        }
    ]
}
POLICY
}

data.tf

data "aws_vpc" "this" {
  filter {
    name   = "tag:Name"
    values = ["${local.name_prefix}-vpc"]
  }
}

data "aws_subnets" "private" {

  count    = length(data.aws_availability_zones.azs.names)
  filter {
    name   = "tag:Name"
    values = ["${local.name_prefix}-vpc-private*"]
  }
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.this.id]
  }
}

data "aws_availability_zones" "azs" {}

tfvars

efs_token                        = "dev-load-test"
efs_performance_mode             = "maxIO"


问:
Athena read-only request under the role with full access
We have .Net Core app that is actively using aws services and therefore has almost all permissions. It interacts with Athena via aws .net sdk and running pre-defined queries mostly, but there is one place in it where user can run his own query against Athena database and there is a theoretical possibility that he can run some malicious request like Drop Database and it will get executed, since the app has full access.

So the question is if there is a way to send read-only request from the app that has full access so that any request other than Select will automatically fail?

In sdk, there is an option to specify workgroup for request, and my idea was to create readonly workgroup with readonly permissions and send user request under it, but the problem here is that there is no way to assign Glue permissions bound to Athena workgroup, and therefore Alter Table requests for example are being executed just fine because app has a full access to Glue.

Parsing request with regexes sounds too complicated because it's rather hard to anticipate all sql injections possibilities, it's actually a separate big complicated task of implementing parsing engine and I  have neither the time nor the wish to work on that.

Another idea was to create lambda just for this particular task, that solves the issue, but I don't like this solution, it's a really hacky and inconvenient way of doing this.

So I'm wondering if there is an adequate way of doing what I described? Thanks in advance.


问:
How do I compile to arm64-v8a .so using Android NDK?
I'm trying to compile a C++ file to a .so file using the Android NDK. I need help because I'm unsure of how to do this through Android Studio.

I looked online and I couldn't find anything regarding this issue. Can someone please give me instructions on how I can compile my C++ file to a arm64-v8a .so file?


问:
Saslauthd with pam mysql not working - size read failed
I am trying build new server Fedora 37 but when I trying to use PamMysql /because logins from postfix are stored in DB/ it is not working

very strange is, that only one ask to saslauthd will stop and broke saslauthd

I am using standard PamMysql and Saslauthd

smtp.postfix in pam.d

auth        required    pam_mysql.so user=postfix passwd=xxxx host=127.0.0.1 db=postfix table=mailbox usercolumn=username passwdcolumn=password crypt=1

account     sufficient  pam_mysql.so user=postfix passwd=xxxx host=127.0.0.1 db=postfix table=mailbox usercolumn=username passwdcolumn=password crypt=1

when I try only "testsaslauthd -u "yyy" -p "xxx" -s smtp"

It fails, stops Saslauthd and write me "size read failed"

Have anybody this error ?? on Fedora 37 ??

BTW: When I change SMTP.POSTFIX in PAM.D -> crypt=0 and write password to DB manually in cleartext - all works fine - but unusable, because of second one of mail - Dovecot is not able to authenticate cleartext passwords ;-)
I think, that problem will be in crypting of SASLAUTHD...because in Dovecot same logins are not problem...and on my older server is not problem too

BTW: I have built maybe 10 mailservers, same situation with no problems. but this is first on Fedora37


问:
Kafka stream consumer skipping a few offset no log compaction enabled
kafka server version: 3.2.0

kstreams version : 2.7.2

I have a producer, which is producing to topic foo, I can see the offset from the producer in the logs.
We have kafka stream application reading from the same topic foo. What I am observing is that the consumer skips reading offset. Sometime the skip is over 30 to 40 offsets. I am printing the offset in process method using ProcessorContext.offset() method.
Skipping of offset seems to be very common, will using ProcessorContext.offset() result in every offset being printed ?.

Some points

No kafka rebalance has occurred.

No restarts of the container

We have 3 state store defined in the streams application, and the change log topic has replication factor of 1.

We have kafka broker outage where few broker were down some extend period of time, about 3 weeks back. I dont know how things impact the message i should consumer today.

We have NOT set processing.guarantee, so default should be AT_LEAST_ONCE. We do not have transactions enabled, so it cant be transactional messages. which are skipped

The log to print offset if the first line in the process method.

Question:

What internal kafka stream logs can I see to see if messages are consumed.

Any reason why the messages could be skipped


问:
Access table content from a return table function
I have a probleme where a user have to lookup a trajectory to go from point A to point B.

What i have to do is look up a way to go from point A to B via other points, like maybe A>C>B.
To do this i basically take the first point which is A and then check all the available point to go towards from this point.
Ex : maybee from point A, i can go to C, D and E
Then i look if one of the result is equal to B. If not, i then call this function again from the next points, in this case :  C then D then E and this recursively until i find a way to go from A to B

I first made a recursive function function(A, B) that returns a table od points i've been too like explained above but the problem was, the point A could go to C and C could go to A so it was recursively looping from A to C and then C to A over and over again. So now i have to find a way to check if a point have alreay been travelled to.
so my function returns table(start, finish). If i to the trajectory A>C>D>E>B for example, then in the table i'll have the lines :
START FINISH

```<code>A    >   C
C    >   D
D    >   E
E    >   B
</code>```

now I have NO IDEA how to check in this table that i'm returning to see if a value is in this table or not example : to check on the third iteration if i've already been in point C so that i don't go from D to C.
I'm really sorry if this is not clear enough, it's not super clear in  my head also.

```<code>create or replace function findConnection(starting, ending) RETURNS TABLE (v_starting, v_ending)
as $$
declare
temp record;
begin
for temp in select start, end from trip where start = starting
loop
if temp.end = ending then
v_starting := temp.start;
v_ending := temp.end;
else
/* here i should check if i've already been threw this point
something like : if select * from table where v_starting = temp.end != null then */
v_starting := temp.start;
v_ending := temp.end;
return next;
findConnection(temp.end, ending); /*recursive call for the next points*/
end if;
end loop;
end;
language plpgsql;
</code>```

Body:
I have a probleme where a user have to lookup a trajectory to go from point A to point B.

What i have to do is look up a way to go from point A to B via other points, like maybe A>C>B.
To do this i basically take the first point which is A and then check all the available point to go towards from this point.
Ex : maybee from point A, i can go to C, D and E
Then i look if one of the result is equal to B. If not, i then call this function again from the next points, in this case :  C then D then E and this recursively until i find a way to go from A to B

I first made a recursive function function(A, B) that returns a table od points i've been too like explained above but the problem was, the point A could go to C and C could go to A so it was recursively looping from A to C and then C to A over and over again. So now i have to find a way to check if a point have alreay been travelled to.
so my function returns table(start, finish). If i to the trajectory A>C>D>E>B for example, then in the table i'll have the lines :
START FINISH

A    >   C
C    >   D
D    >   E
E    >   B

now I have NO IDEA how to check in this table that i'm returning to see if a value is in this table or not example : to check on the third iteration if i've already been in point C so that i don't go from D to C.
I'm really sorry if this is not clear enough, it's not super clear in  my head also.

create or replace function findConnection(starting, ending) RETURNS TABLE (v_starting, v_ending)
as $$
declare
temp record;
begin
for temp in select start, end from trip where start = starting
loop
if temp.end = ending then
v_starting := temp.start;
v_ending := temp.end;
else
/* here i should check if i've already been threw this point
something like : if select * from table where v_starting = temp.end != null then */
v_starting := temp.start;
v_ending := temp.end;
return next;
findConnection(temp.end, ending); /*recursive call for the next points*/
end if;
end loop;
end;
language plpgsql;


问:
Invalidating a cached query conditionally in React with useQueryClient hook
I am quite new to react and am struggling with a subtle problem with data fetching/re-fetching.

We have a data source with its own UI, which lets you create multiple discussion topics and is open to users. These topics can be updated with comments and other activities(deletion of comments/attachments/links) etc from the UI. This data source also exposes endpoints that list all topics currently in the system and the details of user activities on each of them.

Our UI, which is a React app talks to these end points and:

lists out the topics.

upon clicking on one of the items shows the activity counts on the item.(in a separate panel with two tabs - one for comment and one for other user activities)

I am responsible for number 2 above.

I wrote a custom hook to achieve this goal which is called by the panel and used the useQueryClient to invalidate my query inside the hook, but unfortunately, every time the component(panel) re-renders or I switch between the tabs a new call is made to fetch the count which is deemed unnecessary. Instead we want the call to fetch the counts to go out only when the user clicks on the item and the panel opens up. But I am unable to achieve this without violating the rules of hooks(calling it inside conditionals/ calling it outside of a react component).

```<code>export const useTopicActivityCounts = (
  topicId: string | undefined,
): ITopicActivityCounts | undefined => {
useQueryClient().invalidateQueries(['TopicActivitytCounts', { topicId }]);
const { data } = useQuery(
    ['TopicActivityCounts', { topicId }],
    () =>
      fetchAsync<IResult<ITopicActivityCount>>(endpointUrl, {
        method: 'GET',
        params: {
          id,
        },
      }).then(resp => resp?.value),
    {
      enabled: !!topicId,
      staleTime: Infinity,
    },
  );
  return data;
</code>```

this hook is called from here:

```<code>export const TopicDetails = memo(({ item, setItem }: ITopicDetails): JSX.Element => {
  const counts = useTopicActivityCounts(item?.id);

  const headerContent = (
    <Stack>
      /* page content */
    </Stack>
  );

  const items = [
    /* page content */,
  ];

  const pivotItems = [
    {
      itemKey: 'Tab1',
      headerText: localize('Resx.Comms', { count: counts?.commentsCount ?? '0' }),
    },
    {
      itemKey: 'Tab2',
      headerText: localize('Resx.Activities', { count: counts?.activitiesCount ?? '0' }),
    },
  ];

  return (
    /*
       page content
    */
  );
});
</code>```

I have tried placing it inside an onSuccess inside the hook and that did not work.

Body:
I am quite new to react and am struggling with a subtle problem with data fetching/re-fetching.

We have a data source with its own UI, which lets you create multiple discussion topics and is open to users. These topics can be updated with comments and other activities(deletion of comments/attachments/links) etc from the UI. This data source also exposes endpoints that list all topics currently in the system and the details of user activities on each of them.

Our UI, which is a React app talks to these end points and:

lists out the topics.

upon clicking on one of the items shows the activity counts on the item.(in a separate panel with two tabs - one for comment and one for other user activities)

I am responsible for number 2 above.

I wrote a custom hook to achieve this goal which is called by the panel and used the useQueryClient to invalidate my query inside the hook, but unfortunately, every time the component(panel) re-renders or I switch between the tabs a new call is made to fetch the count which is deemed unnecessary. Instead we want the call to fetch the counts to go out only when the user clicks on the item and the panel opens up. But I am unable to achieve this without violating the rules of hooks(calling it inside conditionals/ calling it outside of a react component).

export const useTopicActivityCounts = (
  topicId: string | undefined,
): ITopicActivityCounts | undefined => {
useQueryClient().invalidateQueries(['TopicActivitytCounts', { topicId }]);
const { data } = useQuery(
    ['TopicActivityCounts', { topicId }],
    () =>
      fetchAsync<IResult<ITopicActivityCount>>(endpointUrl, {
        method: 'GET',
        params: {
          id,
        },
      }).then(resp => resp?.value),
    {
      enabled: !!topicId,
      staleTime: Infinity,
    },
  );
  return data;

this hook is called from here:

export const TopicDetails = memo(({ item, setItem }: ITopicDetails): JSX.Element => {
  const counts = useTopicActivityCounts(item?.id);

  const headerContent = (
    <Stack>
      /* page content */
    </Stack>
  );

  const items = [
    /* page content */,
  ];

  const pivotItems = [
    {
      itemKey: 'Tab1',
      headerText: localize('Resx.Comms', { count: counts?.commentsCount ?? '0' }),
    },
    {
      itemKey: 'Tab2',
      headerText: localize('Resx.Activities', { count: counts?.activitiesCount ?? '0' }),
    },
  ];

  return (
    /*
       page content
    */
  );
});

I have tried placing it inside an onSuccess inside the hook and that did not work.


问:
Is there a way that I can get multiple comments from different cells to display within the same cell in an Excel spreadsheet?
I only have a pretty basic knowledge of Excel and no prior coding experience.

I've been given a task to update multiple (very large) spreadsheets where comments have been left in multiple cells and have been asked to collate those comments into a new, separate column so they are more readily visible and gives an overall snapshot rather than bits and pieces in each comment referring to different bits of information.

I'm hoping that I can use a formula/code to pull all comments from multiple cells into one cell i.e. all comments from A1, B1 and C1 displayed in D1, one under the other

I've been researching on the internet and trying different things in Excel but have hit a brick wall.

Was able to use the following function to display one comment in a cell but not sure how to (or if it's even possible) to get it to show more than one comment. Was trying basic commands and a few other things to no avail (, and &) and believe it's a limitation of the formula below but can't figure what to change.

```<code>Function CommentText(cell As Range) As String
    On Error Resume Next
    CommentText = cell.CommentThreaded.Text
End Function
</code>```

Any help and support would be much appreciated and thanks.

Body:
I only have a pretty basic knowledge of Excel and no prior coding experience.

I've been given a task to update multiple (very large) spreadsheets where comments have been left in multiple cells and have been asked to collate those comments into a new, separate column so they are more readily visible and gives an overall snapshot rather than bits and pieces in each comment referring to different bits of information.

I'm hoping that I can use a formula/code to pull all comments from multiple cells into one cell i.e. all comments from A1, B1 and C1 displayed in D1, one under the other

I've been researching on the internet and trying different things in Excel but have hit a brick wall.

Was able to use the following function to display one comment in a cell but not sure how to (or if it's even possible) to get it to show more than one comment. Was trying basic commands and a few other things to no avail (, and &) and believe it's a limitation of the formula below but can't figure what to change.

Function CommentText(cell As Range) As String
    On Error Resume Next
    CommentText = cell.CommentThreaded.Text
End Function

Any help and support would be much appreciated and thanks.


问:
torchserve with celery / redis
I need to do a long lasting image inferencing, and for some reason, I have to use a torchserve version that has a response timeout limited to 120s.
As inferencing will exceed this limit, does it make sense to let a celery/redis task send an inference request to torchserve (version with timeout bug) custom handler, and wait for a callback, telling that the detection is done now, before the task finishes and proceeds with the next one?
I want furthermore avoid HTTP "too many requests", so just retry N times seems inefficient..

Title: torchserve with celery / redis


问:
How to change active directory before `npm pack` creates tarball
I have a pipeline which I cannot modify and it just executes a single script npm pack in the root.

My package is built inside the dist folder, so I would like to change the active directory before tarball is created.
I've tried to

add "prepack": "cd dist" in package.json, it displayed as executed during logs but still it's executed on the root level, eg all the source code is placed into the tarball.

add "prepack": "node chdir.js", where chdir.js is

const process = require('process');
process.chdir('./dist');
```

Node v16.17.0
npm 8.15.0

Body:
I have a pipeline which I cannot modify and it just executes a single script npm pack in the root.

My package is built inside the dist folder, so I would like to change the active directory before tarball is created.
I've tried to

add "prepack": "cd dist" in package.json, it displayed as executed during logs but still it's executed on the root level, eg all the source code is placed into the tarball.

add "prepack": "node chdir.js", where chdir.js is

const process = require('process');
process.chdir('./dist');

Node v16.17.0
npm 8.15.0


问:
How .net Core EF knows during DB update dynamically built DB string
I am curious about EF behaviour and cannot figure out what is going on under the hood.

In Program.cs of a Blazor project, I have the following way to create the connection string:

```<code>var connectionString = $"Data Source=tcp:{dbHost},{dbPort};Initial Catalog={dbname};User ID={dbuser};Password={dbPassword};Encrypt=False";

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
</code>```

In appsettings.json, I have another piece:

```<code>"Default": "Server=tcp:localhost,5532;Initial Catalog=.....etc
</code>```

I am using Docker, environment variables and therefore the Program.cs is necessary, I cannot use the static one from appsettings.json.

Interesting things happen as I install EF, prepare migrations and when I run

```<code>dotnet ef database update
</code>```

It somehow uses the Program.cs variant, which is correct but which lead to nowhere because at that time, my Docker machines are not running (one of them is providing SQL Server database).

Rather I need to use e.g. the static one.

If I do so, for example by adding manual line

```<code>connectionString = builder.Configuration.GetConnectionString("Default") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
</code>```

or if I use parameter

```<code>dotnet ef database update --connection "Server=tcp:...
</code>```

all works fine, the database gets updated, I the comment out the line, let the program run, docker containers run and all works like a charm.

But I do not understand at all HOW EF does this?

This means he has to have some way how to "interpret" or "run" at least Program.cs because I can imagine many way how the connectionString variable can be combined, concatenated, .Format-ted etc...

I am frustrated I do not understand the mechanism. Because you run

```<code>dotnet ef database update
</code>```

at the time, your program is stopped or is NOT running.

Everywhere, all people repeat that it is appsettings.json which is used, but apparently according to my own experience, this is not true, rather some result of program run is used.

But even after program finishes, variable content is not kept, or?

What place or method in EF is used to get the non-trivially built connection string? Can it use C# interpreter to somehow "track" all the variables in Program.cs? This seems over-complicated.

As described above, I have no barrier in my project, I just want to understand the principle.

Body:
I am curious about EF behaviour and cannot figure out what is going on under the hood.

In Program.cs of a Blazor project, I have the following way to create the connection string:

var connectionString = $"Data Source=tcp:{dbHost},{dbPort};Initial Catalog={dbname};User ID={dbuser};Password={dbPassword};Encrypt=False";

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

In appsettings.json, I have another piece:

"Default": "Server=tcp:localhost,5532;Initial Catalog=.....etc

I am using Docker, environment variables and therefore the Program.cs is necessary, I cannot use the static one from appsettings.json.

Interesting things happen as I install EF, prepare migrations and when I run

dotnet ef database update

It somehow uses the Program.cs variant, which is correct but which lead to nowhere because at that time, my Docker machines are not running (one of them is providing SQL Server database).

Rather I need to use e.g. the static one.

If I do so, for example by adding manual line

connectionString = builder.Configuration.GetConnectionString("Default") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");

or if I use parameter

dotnet ef database update --connection "Server=tcp:...

all works fine, the database gets updated, I the comment out the line, let the program run, docker containers run and all works like a charm.

But I do not understand at all HOW EF does this?

This means he has to have some way how to "interpret" or "run" at least Program.cs because I can imagine many way how the connectionString variable can be combined, concatenated, .Format-ted etc...

I am frustrated I do not understand the mechanism. Because you run

dotnet ef database update

at the time, your program is stopped or is NOT running.

Everywhere, all people repeat that it is appsettings.json which is used, but apparently according to my own experience, this is not true, rather some result of program run is used.

But even after program finishes, variable content is not kept, or?

What place or method in EF is used to get the non-trivially built connection string? Can it use C# interpreter to somehow "track" all the variables in Program.cs? This seems over-complicated.

As described above, I have no barrier in my project, I just want to understand the principle.


问:
How to change the checked property in a checkbox?
I have a state called ListItems and I wish to display them as checked if the value is present in another state array called filteredListItems. I have created a callback function but this doesn't seem to work. How do I go on about this?

```<code>import React, {useState, useRef} from 'react'
import { connect, useDispatch, useSelector, useStore} from 'react-redux';

import { setEnable} from "../actions";
import './Settings.css'

function Settings(props){

  const dispatch=useDispatch();

  const [listItems,setListItems]=useState(props.defaultenableVal);
  const [filteredListItems,setFilteredListItems]=useState(props.defaultenableVal);

  const dragItem = React.useRef();
  const dragOverItem = React.useRef();

  const handleSort=()=>{
    let _listItems=[...listItems];

    const draggedItemContent=_listItems.splice(dragItem.current,1)[0];

    _listItems.splice(dragOverItem.current,0, draggedItemContent);

    dragItem.current=null;
    dragOverItem.current=null;

    setListItems(_listItems);
  }

  return(
      <div className='container'>
        <h3>Dimensions and Metrics</h3>
          {
            listItems.map((item,index)=>{
              return (
                <div
                  key={index}
                  draggable
                  onDragStart={(e)=>dragItem.current=index}
                  onDragEnter={(e)=>dragOverItem.current=index}
                  onDragEnd={handleSort}
                  onDragOver={(e)=>e.preventDefault()} >
                  <input id={index} name={item} type='checkbox'
                  checked={(()=>{
                    if(filteredListItems.includes(item)){
                      return true
                    }
                    else{
                      return false
                    }
                   })}  />
                  <label htmlFor={index} >{item}</label>
                </div>
              )
            })
          }
    </div>
  )
        }
export default Settings;
</code>```

The value of props.defaultEnableVal is ['Clicks', 'AD Requests', 'AD Responses', 'Impressions', 'Revenue', 'Fill Rate', 'CTR'].
The check does not appear on the checkbox and it doesn't seem to be accepting check input when I click on it.

Body:
I have a state called ListItems and I wish to display them as checked if the value is present in another state array called filteredListItems. I have created a callback function but this doesn't seem to work. How do I go on about this?

import React, {useState, useRef} from 'react'
import { connect, useDispatch, useSelector, useStore} from 'react-redux';

import { setEnable} from "../actions";
import './Settings.css'

function Settings(props){

  const dispatch=useDispatch();

  const [listItems,setListItems]=useState(props.defaultenableVal);
  const [filteredListItems,setFilteredListItems]=useState(props.defaultenableVal);

  const dragItem = React.useRef();
  const dragOverItem = React.useRef();

  const handleSort=()=>{
    let _listItems=[...listItems];

    const draggedItemContent=_listItems.splice(dragItem.current,1)[0];

    _listItems.splice(dragOverItem.current,0, draggedItemContent);

    dragItem.current=null;
    dragOverItem.current=null;

    setListItems(_listItems);
  }

  return(

Dimensions and Metrics

          {
            listItems.map((item,index)=>{
              return (

dragItem.current=index}
                  onDragEnter={(e)=>dragOverItem.current=index}
                  onDragEnd={handleSort}
                  onDragOver={(e)=>e.preventDefault()} >
                  <input id={index} name={item} type='checkbox'
                  checked={(()=>{
                    if(filteredListItems.includes(item)){
                      return true
                    }
                    else{
                      return false
                    }
                   })}  />
                  {item}

              )
            })
          }

  )
        }
export default Settings;

The value of props.defaultEnableVal is ['Clicks', 'AD Requests', 'AD Responses', 'Impressions', 'Revenue', 'Fill Rate', 'CTR'].
The check does not appear on the checkbox and it doesn't seem to be accepting check input when I click on it.


问:
no bar on MDScrollView in kivyMD
i have a label that prints out data and it needs to be scrollable.
so it scrolls now but it does not have a scroll bar and the text bounces back to top once you release it.I have tried adding bar_width: 10 changed nothing.

```<code>from kivy.lang import Builder
from kivymd.uix.scrollview import MDScrollView
from kivy.properties import StringProperty, ObjectProperty
from kivymd.uix.pickers import MDDatePicker
from kivymd.app import MDApp
import json

KV = '''

MDScreenManager:

    MDScreen:
        name: "main"
        MDGridLayout:
            cols: 1
            MDRaisedButton:
                font_size: "32sp"
                text: "Enter payments"
                pos_hint: {"y": .2, "center_x" : .5}
                size_hint: 1, 1
                on_release:
                    root.current = "enter"
            MDRaisedButton:
                font_size: "32sp"
                text: "Check payments"
                pos_hint: {"y": .6, "center_x" : .5}
                size_hint: 1, 1
                on_release:
                    root.current = "view"

    MDScreen:
    #----------------------------------------------------------------------------------------------------------------------
        name: "enter"
        MDFloatLayout:

            MDLabel:
                text: "Date"
                pos_hint: {"x" : 0, "center_y" : .9}
                size_hint: None, None
            MDIconButton:
                icon: "calendar"
                pos_hint: {"center_x": .3, "center_y": .9}
                on_release: app.show_date_picker()
            MDTextField:
                id: date
                helper_text: "Enter a valid date yyyy/mm/dd "
                date_format: 'yyyy/mm/dd'
                validator: "date"
                hint_text: "Enter date"
                pos_hint: {"center_x" : 0.9, "center_y" : .9}
                text: ""
            MDLabel:
                text: "Case id"
                pos_hint: {"x": 0, "center_y": .8}
            MDTextField:
                id: case_id
                hint_text: "Enter case id"
                pos_hint: {"center_x": .9, "center_y": .8}
            MDLabel:
                text: "Payment type"
                size_hint: 1, None
                pos_hint: {"x": 0, "center_y": .7}
            MDTextField:
                id: payment_type
                hint_text: "Payment type"
                pos_hint: {"center_x": .9, "center_y": .7}
            MDLabel:
                text: "Amount"
                pos_hint: {"x" : 0, "center_y": .6}
            MDSwitch:
                pos_hint: {"center_y" : 0.6, "center_x" : 0.3}
                on_active: app.on_checkbox_active(*args)
            MDTextField:
                id: amount
                hint_text: "Enter amount"
                pos_hint: {"center_x": .9, "center_y": .6}

        MDRaisedButton:
            text: "Submit"
            pos_hint: {"y": .2, "center_x" : .5}
            size_hint: 1, 0.3
            on_release: app.add_payment()

        MDRaisedButton:
            text: "Go back"
            pos_hint: {"y": 0, "center_x" : .5}
            size_hint: 1, 0.25
            on_release:
                root.current = "main"
    #---------------------------------------------------------------------------------------------------------------

    MDScreen:
        name: "view"
        MDFloatLayout:
            MDScrollView:
                do_scroll_x: False
                padding: 10, 10
                scroll_type: ['content', 'bars' ]
                bar_width: 20
                MDLabel:
                    id: print_date
                    text: "Nothing to display"
                    pos_hint: {"center_x" : 0, "y" : .6}
                    size_hint: .4, None
                    text_size: self.width, None
                    height: self.texture_size[1]
                    halign: "left"

            MDTextField:
                id: show_date
                mode: "rectangle"
                pos_hint: {"x" : .5, "y" : .7}

            MDIconButton:
                icon: "calendar"
                pos_hint: {"center_x": .7, "center_y": .9}
                size_hint: None, None
                on_release: app.show_date_picker_1()

            MDRaisedButton:
                text: "Check payments"
                pos_hint: {"y" : .2}
                size_hint: 1, 0.1
                on_release:
                    app.view_payment()
            MDRaisedButton:
                text: "Total"
                pos_hint: {"y" : .1}
                size_hint: 1, 0.1
                on_release:
                    app.total()

            MDRaisedButton:
                text: "Go back"
                pos_hint: {"y" : 0}
                size_hint: 1, 0.1
                on_release:
                    root.current = "main"

'''
payments = {}
file = "work.json"

class Test(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Orange"
        return Builder.load_string(KV)

    def on_save(self, instance, value, date_range):
        '''sets the date in Add payment'''
        self.root.ids.date.text = str(value.strftime("%Y/%m/%d"))
        print(value)
    def on_save_1(self, instance, value, date_range):
        '''sets the date in view payment'''
        self.root.ids.show_date.text = str(value.strftime("%Y/%m/%d"))

    def on_cancel(self, instance, value):
        '''Events called when the "CANCEL" dialog box button is clicked.'''

    def show_date_picker(self):
        '''calls the date picker in add payment window'''
        date_dialog = MDDatePicker()
        date_dialog.bind(on_save=self.on_save, on_cancel=self.on_cancel)
        date_dialog.open()

    def show_date_picker_1(self):
        '''calls the date picker in view window'''
        date_dialog = MDDatePicker()
        date_dialog.bind(on_save=self.on_save_1, on_cancel=self.on_cancel)
        date_dialog.open()

    def on_checkbox_active(self, checkbox, value):

        if value:
            payment_amount = float(self.root.ids.amount.text) * 1.5
        else:
            payment_amount = float(self.root.ids.amount.text) / 1.5

        self.root.ids.amount.text = str(payment_amount)
        ##########################################
    def add_payment(self):
        """creates dictionary entry and saves it."""

        # sets date as user input in date field
        date = self.root.ids.date.text
        # sets case_id as user input in case_id field
        case_id = self.root.ids.case_id.text
        # sets amount as user input in amount field
        amount = self.root.ids.amount.text
        # sets payment_type as user input in payment_type field
        payment_type = self.root.ids.payment_type.text
        try:
            self._extracted_from_add_payment_11(date, case_id, payment_type, amount)
        except ValueError as Error:
            self._extracted_from_add_payment_11(date, case_id, payment_type, amount)

    # TODO Rename this here and in `add_payment`
    def _extracted_from_add_payment_11(self, date, case_id, payment_type, amount):
        # checks if json file exists if it doesnt creates it if it does it dumps payments in it
        try:
            with open(file, 'x') as f:
                payments = {}
                j = json.dump(payments, f)
        except FileExistsError:
            with open(file, 'r') as f:
                payments = json.load(f)

        #creates entry in dictionary if date exists appends it if not creates an entry
        if date not in payments:
            payments[date] = []
        payments[date].append(
            {
                "Case id" : case_id,
                "Payment type" : payment_type,
                "Amount" : amount
            })
        #resets the input fields to empty
        self.root.ids.case_id.text = ''
        self.root.ids.amount.text = ''
        self.root.ids.payment_type.text = ''
        #dumps data in json
        with open(file, 'w') as f:
            j = json.dump(payments, f)

    def view_payment(self):
        """finds entry in dictionary and puts all matches to a label"""

        #sets date as input from date field
        date = self.root.ids.show_date.text
        #sets print_date label to empty
        self.root.ids.print_date.text = ""
        #loads data from json
        with open(file, 'r') as f:
            payments = json.load(f)
            #if it finds entry puts it in a label if not sets label text as date does not exist
            try:
                for b, i in enumerate(payments.get(date, None), start=0):
                    self.root.ids.print_date.text += f"{b+1}. Case id:{payments[date][b].get('Case id')}, Payment type:{payments[date][b].get('Payment type')}, Amount:{payments[date][b].get('Amount')}.\n"
            except (KeyError, TypeError) as error: # handle file not found on first launch
                date = self.root.ids.show_date.text
                self.root.ids.print_date.text = "No payments or wrong date"

    def total(self):
        """finds entrys in specific date and sums them up"""

        #sets date as input from show_date field
        date = self.root.ids.show_date.text
        #resets print_date label to empty
        self.root.ids.print_date.text = ''
        total1 = 0
        # finds required dates amount entrys and sums them
        try:
            with open(file, 'r') as f:
                payments = json.load(f)
                for i in payments[date]:
                    # if there is no value it skips it and look for other entry
                    if amount := i.get('Amount'):
                        total1 += float(amount)
                self.root.ids.print_date.text += str(total1)
        except (KeyError,ValueError) as Error:
            self.root.ids.print_date.text = 'Date does not exist'

Test().run()

</code>```

the only thing i noticed it says that MDScrollView import is not being accessed.
any help would be greatly appreciated

Title: no bar on MDScrollView in kivyMD

Body:
i have a label that prints out data and it needs to be scrollable.
so it scrolls now but it does not have a scroll bar and the text bounces back to top once you release it.I have tried adding bar_width: 10 changed nothing.

from kivy.lang import Builder
from kivymd.uix.scrollview import MDScrollView
from kivy.properties import StringProperty, ObjectProperty
from kivymd.uix.pickers import MDDatePicker
from kivymd.app import MDApp
import json

KV = '''

MDScreenManager:

    MDScreen:
        name: "main"
        MDGridLayout:
            cols: 1
            MDRaisedButton:
                font_size: "32sp"
                text: "Enter payments"
                pos_hint: {"y": .2, "center_x" : .5}
                size_hint: 1, 1
                on_release:
                    root.current = "enter"
            MDRaisedButton:
                font_size: "32sp"
                text: "Check payments"
                pos_hint: {"y": .6, "center_x" : .5}
                size_hint: 1, 1
                on_release:
                    root.current = "view"

    MDScreen:
    #----------------------------------------------------------------------------------------------------------------------
        name: "enter"
        MDFloatLayout:

            MDLabel:
                text: "Date"
                pos_hint: {"x" : 0, "center_y" : .9}
                size_hint: None, None
            MDIconButton:
                icon: "calendar"
                pos_hint: {"center_x": .3, "center_y": .9}
                on_release: app.show_date_picker()
            MDTextField:
                id: date
                helper_text: "Enter a valid date yyyy/mm/dd "
                date_format: 'yyyy/mm/dd'
                validator: "date"
                hint_text: "Enter date"
                pos_hint: {"center_x" : 0.9, "center_y" : .9}
                text: ""
            MDLabel:
                text: "Case id"
                pos_hint: {"x": 0, "center_y": .8}
            MDTextField:
                id: case_id
                hint_text: "Enter case id"
                pos_hint: {"center_x": .9, "center_y": .8}
            MDLabel:
                text: "Payment type"
                size_hint: 1, None
                pos_hint: {"x": 0, "center_y": .7}
            MDTextField:
                id: payment_type
                hint_text: "Payment type"
                pos_hint: {"center_x": .9, "center_y": .7}
            MDLabel:
                text: "Amount"
                pos_hint: {"x" : 0, "center_y": .6}
            MDSwitch:
                pos_hint: {"center_y" : 0.6, "center_x" : 0.3}
                on_active: app.on_checkbox_active(*args)
            MDTextField:
                id: amount
                hint_text: "Enter amount"
                pos_hint: {"center_x": .9, "center_y": .6}

        MDRaisedButton:
            text: "Submit"
            pos_hint: {"y": .2, "center_x" : .5}
            size_hint: 1, 0.3
            on_release: app.add_payment()

        MDRaisedButton:
            text: "Go back"
            pos_hint: {"y": 0, "center_x" : .5}
            size_hint: 1, 0.25
            on_release:
                root.current = "main"
    #---------------------------------------------------------------------------------------------------------------

    MDScreen:
        name: "view"
        MDFloatLayout:
            MDScrollView:
                do_scroll_x: False
                padding: 10, 10
                scroll_type: ['content', 'bars' ]
                bar_width: 20
                MDLabel:
                    id: print_date
                    text: "Nothing to display"
                    pos_hint: {"center_x" : 0, "y" : .6}
                    size_hint: .4, None
                    text_size: self.width, None
                    height: self.texture_size[1]
                    halign: "left"

            MDTextField:
                id: show_date
                mode: "rectangle"
                pos_hint: {"x" : .5, "y" : .7}

            MDIconButton:
                icon: "calendar"
                pos_hint: {"center_x": .7, "center_y": .9}
                size_hint: None, None
                on_release: app.show_date_picker_1()

            MDRaisedButton:
                text: "Check payments"
                pos_hint: {"y" : .2}
                size_hint: 1, 0.1
                on_release:
                    app.view_payment()
            MDRaisedButton:
                text: "Total"
                pos_hint: {"y" : .1}
                size_hint: 1, 0.1
                on_release:
                    app.total()

            MDRaisedButton:
                text: "Go back"
                pos_hint: {"y" : 0}
                size_hint: 1, 0.1
                on_release:
                    root.current = "main"

'''
payments = {}
file = "work.json"

class Test(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Orange"
        return Builder.load_string(KV)

    def on_save(self, instance, value, date_range):
        '''sets the date in Add payment'''
        self.root.ids.date.text = str(value.strftime("%Y/%m/%d"))
        print(value)
    def on_save_1(self, instance, value, date_range):
        '''sets the date in view payment'''
        self.root.ids.show_date.text = str(value.strftime("%Y/%m/%d"))

    def on_cancel(self, instance, value):
        '''Events called when the "CANCEL" dialog box button is clicked.'''

    def show_date_picker(self):
        '''calls the date picker in add payment window'''
        date_dialog = MDDatePicker()
        date_dialog.bind(on_save=self.on_save, on_cancel=self.on_cancel)
        date_dialog.open()

    def show_date_picker_1(self):
        '''calls the date picker in view window'''
        date_dialog = MDDatePicker()
        date_dialog.bind(on_save=self.on_save_1, on_cancel=self.on_cancel)
        date_dialog.open()

    def on_checkbox_active(self, checkbox, value):

        if value:
            payment_amount = float(self.root.ids.amount.text) * 1.5
        else:
            payment_amount = float(self.root.ids.amount.text) / 1.5

        self.root.ids.amount.text = str(payment_amount)
        ##########################################
    def add_payment(self):
        """creates dictionary entry and saves it."""

        # sets date as user input in date field
        date = self.root.ids.date.text
        # sets case_id as user input in case_id field
        case_id = self.root.ids.case_id.text
        # sets amount as user input in amount field
        amount = self.root.ids.amount.text
        # sets payment_type as user input in payment_type field
        payment_type = self.root.ids.payment_type.text
        try:
            self._extracted_from_add_payment_11(date, case_id, payment_type, amount)
        except ValueError as Error:
            self._extracted_from_add_payment_11(date, case_id, payment_type, amount)

    # TODO Rename this here and in `add_payment`
    def _extracted_from_add_payment_11(self, date, case_id, payment_type, amount):
        # checks if json file exists if it doesnt creates it if it does it dumps payments in it
        try:
            with open(file, 'x') as f:
                payments = {}
                j = json.dump(payments, f)
        except FileExistsError:
            with open(file, 'r') as f:
                payments = json.load(f)

        #creates entry in dictionary if date exists appends it if not creates an entry
        if date not in payments:
            payments[date] = []
        payments[date].append(
            {
                "Case id" : case_id,
                "Payment type" : payment_type,
                "Amount" : amount
            })
        #resets the input fields to empty
        self.root.ids.case_id.text = ''
        self.root.ids.amount.text = ''
        self.root.ids.payment_type.text = ''
        #dumps data in json
        with open(file, 'w') as f:
            j = json.dump(payments, f)

    def view_payment(self):
        """finds entry in dictionary and puts all matches to a label"""

        #sets date as input from date field
        date = self.root.ids.show_date.text
        #sets print_date label to empty
        self.root.ids.print_date.text = ""
        #loads data from json
        with open(file, 'r') as f:
            payments = json.load(f)
            #if it finds entry puts it in a label if not sets label text as date does not exist
            try:
                for b, i in enumerate(payments.get(date, None), start=0):
                    self.root.ids.print_date.text += f"{b+1}. Case id:{payments[date][b].get('Case id')}, Payment type:{payments[date][b].get('Payment type')}, Amount:{payments[date][b].get('Amount')}.\n"
            except (KeyError, TypeError) as error: # handle file not found on first launch
                date = self.root.ids.show_date.text
                self.root.ids.print_date.text = "No payments or wrong date"

    def total(self):
        """finds entrys in specific date and sums them up"""

        #sets date as input from show_date field
        date = self.root.ids.show_date.text
        #resets print_date label to empty
        self.root.ids.print_date.text = ''
        total1 = 0
        # finds required dates amount entrys and sums them
        try:
            with open(file, 'r') as f:
                payments = json.load(f)
                for i in payments[date]:
                    # if there is no value it skips it and look for other entry
                    if amount := i.get('Amount'):
                        total1 += float(amount)
                self.root.ids.print_date.text += str(total1)
        except (KeyError,ValueError) as Error:
            self.root.ids.print_date.text = 'Date does not exist'

Test().run()

the only thing i noticed it says that MDScrollView import is not being accessed.
any help would be greatly appreciated


问:
How to check if the installed Windows version supports UWP (or DCH) using PowerShell?
I was looking into what versions of Windows support DCH drivers here. The page seems to suggest that any "UWP-based edition of Windows" supports DCH.

While I know this means that Windows 10 and newer support it, is there a PowerShell command that can be ran on most versions of Windows to output whether UWP (or DCH) is supported?


问:
How to activate cookies in embedded browser
I use the RSS reader QuiteRSS to read RSS feeds, among them several StackExchange feeds. Recently, the feeds all ask for cookies to be accepted, but clicking to accept in the embedded browser in QuiteRSS has no effect, and other links in the page are also unclickable. See below for an example.

Does anyone know a method to accept the cookies and read the items as usual?

And please let me know if this is the wrong place to ask. I thought there might be a way to access the embedded browser, even programatically.

Thanks,
Tom


问:
Codility: OddOccurrencesInArray
I tried to answer the exercise of codility of the lesson in arrays but I don't know how to improve my current solution.

It appears that my solution works on 77% of the cases.
The big ones are the problem, and it appears that the time complexity is O (n ** 2 ).
I want to improve it to O ( n) but I don't know how?
I am also new to the use of Hash Maps.

```<code>// you can use includes, for example:
 #include <algorithm>
 #include <map>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
/*
ODD NUMBER IF ELEMENTS
Every element is pared with other that has the same value except for one
Size=2n+1 ,
A= 9,3,9,3,9,7,9
Returns the unique value or the unpaired

-First approach
Traverse the Array and save the unique values in other vector and if you find them later you delete them from the unique array.
Time complexity= O(n)*O(n/2)* = O (n^2)
*for the worst case in which they are [1 2 3 4 1 2 3 4 5]
Space complexity O(n/2)

-Second approach
Sort the array and then Traverse the array
Time complexity O(nlogn)+O(n)
Time space O(1) constant

-Third approach
The values of the array are the position of a second one.
Then the array is traversed to find the one where the value is '1'
Time O (2n) = O (n)
Space O(max value of N) -not efficient

-Fourth approach
Hash Map the value is the key and the frequency is the value
Traverse the HashMap and print the key  who has the value of 1
Time O(n)+ O (n/2 + 1) = O (n)
Space O (n/2 + 1)

-Fifth approach
Probably I could improve the space
*/

int solution(vector<int> &A) {
    map <int, int> hash; //this is a pair so iterator.first is the key and second is the   value

    for (unsigned int i=0 ; i<A.size() ; i++){
        hash[A[i]]++;
        if ( hash[A[i]] == 2) {
            hash.erase (A[i]); //deleting by key  idk the time in a hash requires to delete
        }// I think that with this the space complexity is reduced
    }

    for (auto s : hash){
        if ( s.second == 1){
            return s.first;
            break;
        }
    }
    return 0;
}
</code>```

Title: Codility: OddOccurrencesInArray

Body:
I tried to answer the exercise of codility of the lesson in arrays but I don't know how to improve my current solution.

It appears that my solution works on 77% of the cases.
The big ones are the problem, and it appears that the time complexity is O (n ** 2 ).
I want to improve it to O ( n) but I don't know how?
I am also new to the use of Hash Maps.

// you can use includes, for example:
 #include <algorithm>
 #include <map>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
/*
ODD NUMBER IF ELEMENTS
Every element is pared with other that has the same value except for one
Size=2n+1 ,
A= 9,3,9,3,9,7,9
Returns the unique value or the unpaired

-First approach
Traverse the Array and save the unique values in other vector and if you find them later you delete them from the unique array.
Time complexity= O(n)*O(n/2)* = O (n^2)
*for the worst case in which they are [1 2 3 4 1 2 3 4 5]
Space complexity O(n/2)

-Second approach
Sort the array and then Traverse the array
Time complexity O(nlogn)+O(n)
Time space O(1) constant

-Third approach
The values of the array are the position of a second one.
Then the array is traversed to find the one where the value is '1'
Time O (2n) = O (n)
Space O(max value of N) -not efficient

-Fourth approach
Hash Map the value is the key and the frequency is the value
Traverse the HashMap and print the key  who has the value of 1
Time O(n)+ O (n/2 + 1) = O (n)
Space O (n/2 + 1)

-Fifth approach
Probably I could improve the space
*/

int solution(vector<int> &A) {
    map <int, int> hash; //this is a pair so iterator.first is the key and second is the   value

    for (unsigned int i=0 ; i<A.size() ; i++){
        hash[A[i]]++;
        if ( hash[A[i]] == 2) {
            hash.erase (A[i]); //deleting by key  idk the time in a hash requires to delete
        }// I think that with this the space complexity is reduced
    }

    for (auto s : hash){
        if ( s.second == 1){
            return s.first;
            break;
        }
    }
    return 0;
}


问:
Python upload image with post request
I am trying to upload an image from my computer to a free upload site using python requests

when i run this code it returns a status code 502

what is the problem?

```<code>
import requests

file = {'file': open('test.png','rb')}
request1 = requests.post(
url="https://pasteboard.co/upload", files=file)
print(request1.content)
</code>```

Title: Python upload image with post request

Body:
I am trying to upload an image from my computer to a free upload site using python requests

when i run this code it returns a status code 502

what is the problem?

import requests

file = {'file': open('test.png','rb')}
request1 = requests.post(
url="https://pasteboard.co/upload", files=file)
print(request1.content)


问:
how to fix the snap in the code with no border
im trying to fix the problem of my code where it has a place it will move but it dose not move like the normal border

```<code>bool mousedown;

private void Top_bar_MouseDown(object sender, MouseEventArgs e)
{
  mousedown = true;
}

private void Top_bar_MouseMove(object sender, MouseEventArgs e)
{
  if (mousedown)
   {
     int mousex = MousePosition.X - 200;
     int mousey = MousePosition.Y - 10;
     int form_mousex = System.Windows.Forms.Cursor.Position.X - this.Location.X;
     int form_mousey = System.Windows.Forms.Cursor.Position.Y - this.Location.Y;
     this.SetDesktopLocation(mousex, mousey);
   }
}

private void Top_bar_MouseUp(object sender, MouseEventArgs e)
{
 mousedown = false;
}
</code>```

it to be like a normal windows application border

Body:
im trying to fix the problem of my code where it has a place it will move but it dose not move like the normal border

bool mousedown;

private void Top_bar_MouseDown(object sender, MouseEventArgs e)
{
  mousedown = true;
}

private void Top_bar_MouseMove(object sender, MouseEventArgs e)
{
  if (mousedown)
   {
     int mousex = MousePosition.X - 200;
     int mousey = MousePosition.Y - 10;
     int form_mousex = System.Windows.Forms.Cursor.Position.X - this.Location.X;
     int form_mousey = System.Windows.Forms.Cursor.Position.Y - this.Location.Y;
     this.SetDesktopLocation(mousex, mousey);
   }
}

private void Top_bar_MouseUp(object sender, MouseEventArgs e)
{
 mousedown = false;
}

it to be like a normal windows application border


问:
ESP32 frequency modulation using DAC
Is it possible to generate modulated wave using ESP32 (with or without) it's DAC? I would like to generate signal with carier frequency and modulation frequency.</p>

Title: ESP32 frequency modulation using DAC


问:
There is no sound in the video I created
```<code>ffmpeg -i intro.mp4 -i video.mp4 -i watermark.jpg -filter_complex "[0:v]scale=854x480[intro];[1:v][2:v] overlay=x=10:y=10,drawtext=text=TEXT':box=1:boxborderw=5:boxcolor=black:x=(w-text_w)/2:y=h-th:fontsize=30:fontcolor=white:enable='between(t,0,15)'[main];[intro][main]concat=n=2:v=1:a=0[out]" -map "[out]" -pix_fmt yuv420p -c:a copy out.mp4
</code>```

I want the video to work properly with the sound problem fixed.
I'm waiting for your help

Body:
ffmpeg -i intro.mp4 -i video.mp4 -i watermark.jpg -filter_complex "[0:v]scale=854x480[intro];[1:v][2:v] overlay=x=10:y=10,drawtext=text=TEXT':box=1:boxborderw=5:boxcolor=black:x=(w-text_w)/2:y=h-th:fontsize=30:fontcolor=white:enable='between(t,0,15)'[main];[intro][main]concat=n=2:v=1:a=0[out]" -map "[out]" -pix_fmt yuv420p -c:a copy out.mp4

I want the video to work properly with the sound problem fixed.
I'm waiting for your help


问:
Create a vue-like plain component
Entry level. ES5 standard.

I have built a module:

```<code>import Person from './Person.js';

function Employer()
{
    Person.call(this);

    this.randomMethod = function() {
        console.log('randomMethod');
    }

    this.render = function(elem) {
        elem.innerHTML = this.compileTemplate();
    }

    this.compileTemplate = function() {
        return "<p onclick='this.randomMethod()'>Employer block</p>";
    }
}

export default Employer;
</code>```

As you can see, it has its own view. So, now I am able to create as many objects as I want and bind them to DOM elements. As a next step I would like to teach them to execute its own methods (randomMethod in this case) without any global variables. To have a component, which knows how to render itself and how to process its events on es5 without any frameworks.

At least I need to emit a CustomEvent and I wouldn't like to have such long in-line code but a plain method call.

Something similar to Vue components, which have template and methods properties and you can call those methods from template.

Any ideas in this direction?

Title: Create a vue-like plain component

Body:
Entry level. ES5 standard.

I have built a module:

import Person from './Person.js';

function Employer()
{
    Person.call(this);

    this.randomMethod = function() {
        console.log('randomMethod');
    }

    this.render = function(elem) {
        elem.innerHTML = this.compileTemplate();
    }

    this.compileTemplate = function() {
        return "
Employer block
";
    }
}

export default Employer;

As you can see, it has its own view. So, now I am able to create as many objects as I want and bind them to DOM elements. As a next step I would like to teach them to execute its own methods (randomMethod in this case) without any global variables. To have a component, which knows how to render itself and how to process its events on es5 without any frameworks.

At least I need to emit a CustomEvent and I wouldn't like to have such long in-line code but a plain method call.

Something similar to Vue components, which have template and methods properties and you can call those methods from template.

Any ideas in this direction?


问:
Is there a way to include download progress bars from rich while logging from youtube-dl?
I'm making a script that mass downloads youtube videos from a text file, and wanted to spice up the console logging a bit with rich. However, while the system that I have does output using rich, it doesn't have progress bars for the download.

This is the current state of the code:

```<code>from __future__ import unicode_literals
from rich.logging import RichHandler
import logging
import youtube_dl

logging.basicConfig(level=logging.DEBUG,   format="%(message)s",  datefmt="[%X]",
    handlers=[RichHandler(level=logging.DEBUG, rich_tracebacks=True, markup=True ) ]
)
log = logging.getLogger('rich')
def load(id):
    address = 'http://www.youtube.com/watch?v=' + id
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'wav',
            'preferredquality': '192'
        }],
        'outtmpl': 'audio/%(id)s.wav',
        "logger": log,
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([address])
</code>```

I was wondering if there was anyway to incercept the download portion of the logging to be replaced with some sort of progress bar.

Body:
I'm making a script that mass downloads youtube videos from a text file, and wanted to spice up the console logging a bit with rich. However, while the system that I have does output using rich, it doesn't have progress bars for the download.

This is the current state of the code:

from __future__ import unicode_literals
from rich.logging import RichHandler
import logging
import youtube_dl

logging.basicConfig(level=logging.DEBUG,   format="%(message)s",  datefmt="[%X]",
    handlers=[RichHandler(level=logging.DEBUG, rich_tracebacks=True, markup=True ) ]
)
log = logging.getLogger('rich')
def load(id):
    address = 'http://www.youtube.com/watch?v=' + id
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'wav',
            'preferredquality': '192'
        }],
        'outtmpl': 'audio/%(id)s.wav',
        "logger": log,
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([address])

I was wondering if there was anyway to incercept the download portion of the logging to be replaced with some sort of progress bar.


问:
Call with API Keys in headers for Have I Been Pwned API returning with unauthorised exception
I’m getting the following error:

System.Net.Http.HttpRequestException: 'Request failed with status code Unauthorized'

When I run the following code using RestSharp

```<code>Public Class Form1
    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim client As New RestClient("https://haveibeenpwned.com/api/v3") 'required for auth api
        Dim request As New RestRequest("breachedaccount/email")
        request.AddHeader("hipb-api-key", "key")
        Dim response = Await client.GetAsync(request)
    End Sub
End Class
</code>```

Any help with where I’m going wrong would be much appreciated. I’ve removed the actual key and email from the code.

I’m trying to replicate the following command:

curl 'https://haveibeenpwned.com/api/v3/breachedaccount/email
--header 'hibp-api-key:key’

The haveibeenpwned API requires the API key to be provided in the header, but it is this part that seems to be the problem as the code works for other APIs that don’t need an API key.

Body:
I’m getting the following error:

System.Net.Http.HttpRequestException: 'Request failed with status code Unauthorized'

When I run the following code using RestSharp

Public Class Form1
    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim client As New RestClient("https://haveibeenpwned.com/api/v3") 'required for auth api
        Dim request As New RestRequest("breachedaccount/email")
        request.AddHeader("hipb-api-key", "key")
        Dim response = Await client.GetAsync(request)
    End Sub
End Class

Any help with where I’m going wrong would be much appreciated. I’ve removed the actual key and email from the code.

I’m trying to replicate the following command:

curl 'https://haveibeenpwned.com/api/v3/breachedaccount/email
--header 'hibp-api-key:key’

The haveibeenpwned API requires the API key to be provided in the header, but it is this part that seems to be the problem as the code works for other APIs that don’t need an API key.


问:
pytesseract has bad performance on digits
I have the following image which I want to parse to '4/1/3' with pytesseract.

The result I get is '4/13\n'.

When using a grayscale image, the performance is slightly better from experience. For this image, I get '4/113\n'.

The code I am using is:

```<code>pytesseract.image_to_string(img, config='--psm 8 -c tessedit_char_whitelist=0123456789/', lang='eng')
</code>```

I set the flag --psm 8 to tread it as a single word, and I specified a whitelist of only digits and '/'.

Are there other options I should use to increase the performance of tesseract in this case?

Body:
I have the following image which I want to parse to '4/1/3' with pytesseract.

The result I get is '4/13\n'.

When using a grayscale image, the performance is slightly better from experience. For this image, I get '4/113\n'.

The code I am using is:

pytesseract.image_to_string(img, config='--psm 8 -c tessedit_char_whitelist=0123456789/', lang='eng')

I set the flag --psm 8 to tread it as a single word, and I specified a whitelist of only digits and '/'.

Are there other options I should use to increase the performance of tesseract in this case?


问:
How to access a MySQL database from a Lua script
I am writing a Lua script using VS Code 1.73.1 on a Windows 11 PC. I would like to write some data from the script to a MySQL database that is located on another (Linux) PC that is on my local network.

I tried the following:

add 'mysql = require "luasql.mysql"' to my code. This results in an error because the luasql.mysql module is not found.

'luarocks install luasql-mysql' with the luasql-mysql-2.6.0-1.rockspec file downloaded from Https://github.com/lunarmodules/luasql. This fails because the Lua 5.4 interpreter is not found, and apparently I also have to install Git.

Installed Git but now it cannot find mysql.h. According to Google I have to install a local version of MySql. I tried that but no mysql.h file

What can I do to get the luasql-mysql module working? (Preferrably without installing programs/utilities that I am probably never going to use again)

Thanks in advance


问:
ActivityGroup inside TabHost does not show content after first run
I have issue with ActivityGroup. My app has 4 tabs, 2 of which has ActivityGroup and 2 more simple activity. The problem is that after first run of app content is shown properly, and when leave app through back button and return, tabs with activity group dont shown any content, including menus. While tabs with simple activity work properly.
D'you have any ideas?

Ok, some sort of code)
Setting this tab:

```<code>private TabSpec getFrontPageTab() {

        Intent intent = new Intent(context, ActivityGroupHome.class);
        return tabHost
                .newTabSpec("home")
                .setIndicator(
                        getTabView(R.drawable.tabbar_home, "str_home"))
                .setContent(intent);

    }
</code>```

ActivityGroupHome:

```<code>public class ActivityGroupHome extends ActivityGroupBase {

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    ActivityUtils activityUtils = ActivityUtils.getInstance(this);

    activityUtils.addActivityGroup("Home", this);
    activityUtils.startHomeActivity("Home");

}

}
</code>```

Methods from ActivityUtils:

```<code>public void startHomeActivity(String activityGroupName) {

    if (activityGroupName != null) {

        startHomeActivityForActivityGroup(activityGroupName);

    } else {

        Intent intent = new Intent(context, AsyncMainActivity.class);
        // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);

    }

}

private void startHomeActivityForActivityGroup(String activityGroupName) {

    ActivityGroupListItem activityGroupItem = activityGroups
            .findGroupByName(activityGroupName);

    if (activityGroupItem != null) {

        Intent intent = new Intent(activityGroupItem.activityGroup,
                AsyncMainActivity.class);

        intent.putExtra(ACTIVITY_GROUP_NAME, activityGroupItem.name);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        View view = activityGroupItem.activityGroup
                .getLocalActivityManager().startActivity("Home", intent)
                .getDecorView();
        activityGroupItem.activityGroup.setContentView(view);
        activityGroupItem.stack.add("Home");

    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have issue with ActivityGroup. My app has 4 tabs, 2 of which has ActivityGroup and 2 more simple activity. The problem is that after first run of app content is shown properly, and when leave app through back button and return, tabs with activity group dont shown any content, including menus. While tabs with simple activity work properly.
D'you have any ideas?

Ok, some sort of code)
Setting this tab:

private TabSpec getFrontPageTab() {

        Intent intent = new Intent(context, ActivityGroupHome.class);
        return tabHost
                .newTabSpec("home")
                .setIndicator(
                        getTabView(R.drawable.tabbar_home, "str_home"))
                .setContent(intent);

    }

ActivityGroupHome:

public class ActivityGroupHome extends ActivityGroupBase {

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    ActivityUtils activityUtils = ActivityUtils.getInstance(this);

    activityUtils.addActivityGroup("Home", this);
    activityUtils.startHomeActivity("Home");

}

}

Methods from ActivityUtils:

public void startHomeActivity(String activityGroupName) {

    if (activityGroupName != null) {

        startHomeActivityForActivityGroup(activityGroupName);

    } else {

        Intent intent = new Intent(context, AsyncMainActivity.class);
        // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);

    }

}

private void startHomeActivityForActivityGroup(String activityGroupName) {

    ActivityGroupListItem activityGroupItem = activityGroups
            .findGroupByName(activityGroupName);

    if (activityGroupItem != null) {

        Intent intent = new Intent(activityGroupItem.activityGroup,
                AsyncMainActivity.class);

        intent.putExtra(ACTIVITY_GROUP_NAME, activityGroupItem.name);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        View view = activityGroupItem.activityGroup
                .getLocalActivityManager().startActivity("Home", intent)
                .getDecorView();
        activityGroupItem.activityGroup.setContentView(view);
        activityGroupItem.stack.add("Home");

    }

}


问:
dotnet nuget restore says it's unable to find a package with a specific version, but in the same error messages says it has found it?
I'm attempting to restore packages in my project with

dotnet restore

And am receiving the (seemingly nonsensical) error message:

```<code>/code/modules-mobilebanking/Modules.MobileBanking.API/Modules.MobileBanking.API.csproj : error NU1102: Unable to find package ApplicationLogic.Contract with version (>= 1.1.0)
       /code/modules-mobilebanking/Modules.MobileBanking.API/Modules.MobileBanking.API.csproj : error NU1102:   - Found 2 version(s) in GitLab [ Nearest version: 1.1.0 ]
       /code/modules-mobilebanking/Modules.MobileBanking.API/Modules.MobileBanking.API.csproj : error NU1102:   - Found 0 version(s) in nuget.org
</code>```

So it says it finds two versions of the package, one of which IS EXACTLY the version it says it's looking for. I have read/write access to the nuget source named GitLab, and about a dozen other packages are successfully restored from this nuget source.  I can also query the nuget source and verify that the package exists at two different versions:

```<code>{
"@type": "Package",
"authors": "",
"id": "ApplicationLogic.Contract",
"title": "ApplicationLogic.Contract",
"summary": "",
"totalDownloads": 0,
"verified": true,
"version": "1.1.0",
"versions": [
{
"@id": "https://gtlb.company.com/api/v4/projects/25/packages/nuget/metadata/ApplicationLogic.Contract/1.1.0.json",
"version": "1.1.0",
"downloads": 0
},
{
"@id": "https://gtlb.company.com/api/v4/projects/25/packages/nuget/metadata/ApplicationLogic.Contract/1.0.0.json",
"version": "1.0.0",
"downloads": 0
}
],
"tags": ""
}
</code>```

Body:
I'm attempting to restore packages in my project with

dotnet restore

And am receiving the (seemingly nonsensical) error message:

/code/modules-mobilebanking/Modules.MobileBanking.API/Modules.MobileBanking.API.csproj : error NU1102: Unable to find package ApplicationLogic.Contract with version (>= 1.1.0)
       /code/modules-mobilebanking/Modules.MobileBanking.API/Modules.MobileBanking.API.csproj : error NU1102:   - Found 2 version(s) in GitLab [ Nearest version: 1.1.0 ]
       /code/modules-mobilebanking/Modules.MobileBanking.API/Modules.MobileBanking.API.csproj : error NU1102:   - Found 0 version(s) in nuget.org

So it says it finds two versions of the package, one of which IS EXACTLY the version it says it's looking for. I have read/write access to the nuget source named GitLab, and about a dozen other packages are successfully restored from this nuget source.  I can also query the nuget source and verify that the package exists at two different versions:

{
"@type": "Package",
"authors": "",
"id": "ApplicationLogic.Contract",
"title": "ApplicationLogic.Contract",
"summary": "",
"totalDownloads": 0,
"verified": true,
"version": "1.1.0",
"versions": [
{
"@id": "https://gtlb.company.com/api/v4/projects/25/packages/nuget/metadata/ApplicationLogic.Contract/1.1.0.json",
"version": "1.1.0",
"downloads": 0
},
{
"@id": "https://gtlb.company.com/api/v4/projects/25/packages/nuget/metadata/ApplicationLogic.Contract/1.0.0.json",
"version": "1.0.0",
"downloads": 0
}
],
"tags": ""
}


问:
IntellyJ idea java swing custom JFrame class contains components but its blank on run
Im just try to learn jawa swing.
I created form by IntellyJ idea and places into JPanel button

```<code>package Front;

import javax.swing.*;

public class WelcomingWindow extends JFrame {

    private JButton button1;

    public WelcomingWindow() {
        button1.setVisible(true);
    }
}
</code>```

Then i run it

```<code>public class Run {
    public static void main(String[] args) {
        WelcomingWindow ww = new WelcomingWindow();
        ww.setVisible(true);
    }

}
</code>```

And i get this (after stretching):
https://i.stack.imgur.com/118do.png

I cant find any information why is so.
Also i will be very grateful to see any swing getting started guideline. On winforms i get a lot.
There is WelcomingWindow.form code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="Front.WelcomingWindow">
  <grid id="27dc6" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
    <margin top="0" left="0" bottom="0" right="0"/>
    <constraints>
      <xy x="20" y="20" width="500" height="400"/>
    </constraints>
    <properties/>
    <border type="none"/>
    <children>
      <hspacer id="f184c">
        <constraints>
          <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
        </constraints>
      </hspacer>
      <vspacer id="41919">
        <constraints>
          <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
        </constraints>
      </vspacer>
      <component id="6223c" class="javax.swing.JButton" binding="button1" default-binding="true">
        <constraints>
          <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
        </constraints>
        <properties>
          <text value="Button"/>
        </properties>
      </component>
    </children>
  </grid>
</form>
</code>```

Body:
Im just try to learn jawa swing.
I created form by IntellyJ idea and places into JPanel button

package Front;

import javax.swing.*;

public class WelcomingWindow extends JFrame {

    private JButton button1;

    public WelcomingWindow() {
        button1.setVisible(true);
    }
}

Then i run it

public class Run {
    public static void main(String[] args) {
        WelcomingWindow ww = new WelcomingWindow();
        ww.setVisible(true);
    }

}

And i get this (after stretching):
https://i.stack.imgur.com/118do.png

I cant find any information why is so.
Also i will be very grateful to see any swing getting started guideline. On winforms i get a lot.
There is WelcomingWindow.form code:

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="Front.WelcomingWindow">
  <grid id="27dc6" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
    <margin top="0" left="0" bottom="0" right="0"/>
    <constraints>
      <xy x="20" y="20" width="500" height="400"/>
    </constraints>
    <properties/>
    <border type="none"/>
    <children>
      <hspacer id="f184c">
        <constraints>
          <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
        </constraints>
      </hspacer>
      <vspacer id="41919">
        <constraints>
          <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
        </constraints>
      </vspacer>
      <component id="6223c" class="javax.swing.JButton" binding="button1" default-binding="true">
        <constraints>
          <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
        </constraints>
        <properties>
          <text value="Button"/>
        </properties>
      </component>
    </children>
  </grid>
</form>


问:
Code is paused when app runs in background
This is the code I run. In the simulator the code runs. But on the device as soon as I hide the app the code pauses and the Task.Delay is never done and the second Clipboard set as well.

```<code>await Clipboard.SetTextAsync(text);
await Task.Delay(5000,_cancellationTokenSource.Token);
await Clipboard.SetTextAsync(string.Empty);
</code>```

How could I execute this code when then user has switched to a different application?

Body:
This is the code I run. In the simulator the code runs. But on the device as soon as I hide the app the code pauses and the Task.Delay is never done and the second Clipboard set as well.

await Clipboard.SetTextAsync(text);
await Task.Delay(5000,_cancellationTokenSource.Token);
await Clipboard.SetTextAsync(string.Empty);

How could I execute this code when then user has switched to a different application?


问:
SEQUENTIAL bidirectional P2P with NFC on Gingerbread
I have the following scenario

Phone A prepares an NDEF message and Phone B registers foreground
dispatch.

Phone A pushes the NDEF. Phone B receives this and processes it.

Phone A now registers for foreground dispatch and disables NDEF
push.Phone B replies with an NDEF push.

ALL this is to be done in one swipe. How can I do this?
Right now, I have to pull the devices away for the 2nd part to work. I
have seen the sample on p2p exchange, but in that case, both the
message contents are known in advance. Here, the reply depends on the
request.

Secondly, will there be a proper NFC API with the ability to create
LLCP sockets?

Cheers,
Earlence


问:
Meteor take too long to response a call
I have a peculiar issue, When I call a meteor method on the frontend, Meteor executes and returns the method but my frontend doesn't execute the callback, but It only happens on my production app, on locally the same code works and executes the callback.

At this point, the issue will be maybe optimization but, Is not, because I add some console.time to my backend and the execution time is even faster than my local meteor instance, in 100ms the return method is called, in local is like 500ms.

Example:
frontend

```<code>Meteor.call("method1", (err, res) => {
    console.log("Done :)")
  })
</code>```

backend

```<code>Meteor.methods({method1() {
    console.time("test")
    // do something
    console.timeEnd("test")
    return true
  }
})
</code>```

Title: Meteor take too long to response a call

Body:
I have a peculiar issue, When I call a meteor method on the frontend, Meteor executes and returns the method but my frontend doesn't execute the callback, but It only happens on my production app, on locally the same code works and executes the callback.

At this point, the issue will be maybe optimization but, Is not, because I add some console.time to my backend and the execution time is even faster than my local meteor instance, in 100ms the return method is called, in local is like 500ms.

Example:
frontend

Meteor.call("method1", (err, res) => {
    console.log("Done :)")
  })

backend

Meteor.methods({method1() {
    console.time("test")
    // do something
    console.timeEnd("test")
    return true
  }
})


问:
Heatmap of line segments in 3-D space projected onto 2-D plane
I have a set of data containing the start and endpoints of line segments which exist in 3-D space. Along with the spatial data, I also have an associated value of the volume of the physical element the line segments represent. The volumes are independent of those of other segments (i.e., two segments with the same length do not necessarily have the same volume). Typically, most segments are parallel to an axis, although this is certainly not always the case. I have about 5,000 elements in this dataset:

Due to the fact that I have so many overlapping segments, my goal is to project each element onto the xy, xz, and yz planes and plot a heatmap of the volumetric intensity of the planar projection. For example, see the sketch of a set of monkey bars and the xy and xz heatmaps below. In the 3-D plot, linewidths have been weighted to show volumes.

My data is currently stored in a Pandas DataFrame and I am plotting in Matplotlib. Since I have the coordinates of all elements, coordinate projection is no issue. However, I am not sure how to increase the intensities of the heatmap when elements intersect or are projected with a shorter length. I will also need to expand this dataset to include two-dimensional shapes and three-dimensional forms also defined by a set of two points and a volume parameter. Any ideas are appreciated.