问:
Implement IEquatable for struct, and pass by reference
Is it possible to implement IEquatable from a struct, but pass the compared argument by reference?

Example:

```<code>struct BigToCopy : IEquatable<BigToCopy>
{
    int x, y, z, w, foo bar, etc;

    bool Equals(in BigToCopy other) // does not compile with 'in' parameter
    {
    }
}
</code>```

It does not compile, because seemingly it does not implement IEquatable<BigToCopy> when there is the 'in' keyword.

This one is ok, but it copies by value:

```<code>struct BigToCopy : IEquatable<BigToCopy>
{
    int x, y, z, w, foo bar, etc;

    bool Equals(BigToCopy other) // does compile
    {
    }
}
</code>```

IEqualityComparer has the same problem as far as I can tell. It requires the arguments to be passed by value.

Would compiler optimizations avoid copying even if we pass by value? Note: I'm on Unity. Using mono and il2cpp.

Edit: ok, let's be more concrete. We have a number of classes in our code base that are implemented like this:

```<code>struct Vertex
{
    public Point3d Position; // 3 doubles
    public Vector3d Normal; // 3 doubles
    public Vector2d UV; // 2 doubles
    public Color Color; // 4 bytes
    // possibly some other vertex data

    public override bool Equals(object obj) { ... }
    public bool Equals(in Vertex vertex) { ... }
}
</code>```

There are multiple such classes. They are put in collections as HashSets, Dictionaries, etc. They are also being compared by explicit calls of Equals in some cases. These objects can be created in thousands, maybe even millions, and are processed in some way. They are usually in a hot code path.

Recently, I have found out that dictionary lookup using these objects can lead to object allocation. The reason: these objects don't implement IEquatable. Therefore, the dictionary calls Equals(object obj) overload instead, which leads to boxing (= memory allocation).

I'm fixing these classes right now, by implementing the IEquatable interface and removing the 'in' keyword. But there is some existing code that calls these Equals methods directly, and I was not sure whether I was affecting the performance badly. I could try, but there are many classes I'm fixing this way, so it is too much work to check.
Instead, I add another method:

```<code>public bool EqualsPassByRef(in Vertex vertex) { ... }
</code>```

and replace explicit calls of Equals by EqualsPassByRef.

It works ok this way. The performance would be better compared to before. I just wondered: maybe there is a way to make C# call the 'in' version from the dictionary. Then the 'EqualsPassByRef' versions would not be needed, making the code look better (and possibly also faster in dictionary lookup). From the answers I conclude that it is not possible. Ok, that's still fine.

Btw: I'm new to C#. I'm coming from a C++ world.

Body:
Is it possible to implement IEquatable from a struct, but pass the compared argument by reference?

Example:

struct BigToCopy : IEquatable<BigToCopy>
{
    int x, y, z, w, foo bar, etc;

    bool Equals(in BigToCopy other) // does not compile with 'in' parameter
    {
    }
}

It does not compile, because seemingly it does not implement IEquatable<BigToCopy> when there is the 'in' keyword.

This one is ok, but it copies by value:

struct BigToCopy : IEquatable<BigToCopy>
{
    int x, y, z, w, foo bar, etc;

    bool Equals(BigToCopy other) // does compile
    {
    }
}

IEqualityComparer has the same problem as far as I can tell. It requires the arguments to be passed by value.

Would compiler optimizations avoid copying even if we pass by value? Note: I'm on Unity. Using mono and il2cpp.

Edit: ok, let's be more concrete. We have a number of classes in our code base that are implemented like this:

struct Vertex
{
    public Point3d Position; // 3 doubles
    public Vector3d Normal; // 3 doubles
    public Vector2d UV; // 2 doubles
    public Color Color; // 4 bytes
    // possibly some other vertex data

    public override bool Equals(object obj) { ... }
    public bool Equals(in Vertex vertex) { ... }
}

There are multiple such classes. They are put in collections as HashSets, Dictionaries, etc. They are also being compared by explicit calls of Equals in some cases. These objects can be created in thousands, maybe even millions, and are processed in some way. They are usually in a hot code path.

Recently, I have found out that dictionary lookup using these objects can lead to object allocation. The reason: these objects don't implement IEquatable. Therefore, the dictionary calls Equals(object obj) overload instead, which leads to boxing (= memory allocation).

I'm fixing these classes right now, by implementing the IEquatable interface and removing the 'in' keyword. But there is some existing code that calls these Equals methods directly, and I was not sure whether I was affecting the performance badly. I could try, but there are many classes I'm fixing this way, so it is too much work to check.
Instead, I add another method:

public bool EqualsPassByRef(in Vertex vertex) { ... }

and replace explicit calls of Equals by EqualsPassByRef.

It works ok this way. The performance would be better compared to before. I just wondered: maybe there is a way to make C# call the 'in' version from the dictionary. Then the 'EqualsPassByRef' versions would not be needed, making the code look better (and possibly also faster in dictionary lookup). From the answers I conclude that it is not possible. Ok, that's still fine.

Btw: I'm new to C#. I'm coming from a C++ world.


来源: stackexchange

问:
How to align geom_text labels on geom_col() properly?
I am trying to label columns with geom_text() on a geom_col(). But, the labels (numbers) doesn't labeled the columns properly. It seems that the hjust values are different from each other.

Dataset: https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-12-13/state_retail.csv

My Code:

```<code>state_retail %>%
  group_by(subsector) %>%
  summarise(avg_change_yoy = mean(change_yoy, na.rm = TRUE),
            avg_change_yoy_se = mean(change_yoy_se, na.rm = TRUE),
            total = sum(avg_change_yoy + avg_change_yoy_se)) %>%
  pivot_longer(cols = c("avg_change_yoy", "avg_change_yoy_se"),
               names_to = "avgs",
               values_to = "values") %>%
  arrange(desc(total)) %>%
  slice_head(n = 12) %>%
  ggplot(aes(values, reorder(avgs, values), fill = subsector, color = subsector)) +
  geom_col(position = "dodge") +
  scale_y_discrete(labels = c(
    "avg_change_yoy" = "Average Change Yoy",
    "avg_change_yoy_se" = "Average Change Yoy Se"
  )) +
  theme(legend.position = "bottom") +
  #print value for each bar as well
  geom_text(aes(label = format(round(values, digits = 2), big.mark = ",")), hjust = "inward",
            size = 4, color ="white", position = position_dodge(1))
</code>```

As you can see in the chart below, some labels are at the top of the column, some in the middle and some at the bottom.

How can I arrange these values to be centered on geom_col()? I want all labels to be in the middle like the red columns.

Note: Also, one of the labels doesn't even appear in the column. In the second to last column.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to label columns with geom_text() on a geom_col(). But, the labels (numbers) doesn't labeled the columns properly. It seems that the hjust values are different from each other.

Dataset: https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-12-13/state_retail.csv

My Code:

state_retail %>%
  group_by(subsector) %>%
  summarise(avg_change_yoy = mean(change_yoy, na.rm = TRUE),
            avg_change_yoy_se = mean(change_yoy_se, na.rm = TRUE),
            total = sum(avg_change_yoy + avg_change_yoy_se)) %>%
  pivot_longer(cols = c("avg_change_yoy", "avg_change_yoy_se"),
               names_to = "avgs",
               values_to = "values") %>%
  arrange(desc(total)) %>%
  slice_head(n = 12) %>%
  ggplot(aes(values, reorder(avgs, values), fill = subsector, color = subsector)) +
  geom_col(position = "dodge") +
  scale_y_discrete(labels = c(
    "avg_change_yoy" = "Average Change Yoy",
    "avg_change_yoy_se" = "Average Change Yoy Se"
  )) +
  theme(legend.position = "bottom") +
  #print value for each bar as well
  geom_text(aes(label = format(round(values, digits = 2), big.mark = ",")), hjust = "inward",
            size = 4, color ="white", position = position_dodge(1))

As you can see in the chart below, some labels are at the top of the column, some in the middle and some at the bottom.

How can I arrange these values to be centered on geom_col()? I want all labels to be in the middle like the red columns.

Note: Also, one of the labels doesn't even appear in the column. In the second to last column.


问:
Windows KMS and virtuals machines deletion (Microsoft Windows key volume licenses)
I will probably install a Windows KMS Server in active Directory mode soon, and i have a simple question whereas i can't find any answer at this time.

That i'd like to know :
If i install a windows virtual machine, i join the domain, the final activation is activated for the virtual machine via the KMS, and a count is started to reduce of 1 the total volume licence key available. It's ok for me.

But :

If i delete the windows 10 or 11 virtual machine from the hypervisor (and delete the computer object bounded to it in the AD) : Does the key installed on it is "uncounted" of the total of activations possible with the volume key licence? And then, i'll be able to reinstall a Windows VM without rebuy a new volume activations keys?


问:
Transpose hirarchy table
I need some help with an table that consists of hirarchy data and I want to get a corresponding view out of it.

I have the following table with some sample data given:

AccountTypeCategoryTreeID
ParentViewTypeID
ParentAccountTypeCategoryID
ChildAccountTypeCategoryID
ChildAccountTypeGroupID
ChildAccountTypeID
SortOrder

2
NULL
7
23
NULL
NULL
10

3
91812
NULL
7
NULL
NULL
10

4
NULL
7
20
NULL
NULL
20

5
NULL
23
NULL
NULL
90584
20

6
91812
NULL
NULL
1
NULL
20

7
NULL
23
NULL
NULL
NULL
30

8
NULL
12
NULL
NULL
90586
10

9
NULL
23
12
NULL
NULL
40

10
91830
NULL
NULL
NULL
90584
10

11
91812
NULL
NULL
NULL
90581
30

The column ParentViewTypeID is always the root element of an tree. The columns ChildAccountTypeID and ChildAccountTypeGroupID are always the last element in the tree. The ParentAccountTypeCategoryID and ChildAccountTypeCategoryID represends the structure.

I have created the statement:

WITH hirachy
AS
(SELECT
        catct.ParentViewTypeID AS [Parent]
       ,COALESCE(catct.ChildAccountTypeID, catct.ChildAccountTypeGroupID, catct.ChildAccountTypeCategoryID) AS [Child]
       ,catct.SortOrder
       ,1 AS [Level]
    FROM CPM_AccountTypeCategoryTree catct
    WHERE catct.ParentViewTypeID IS NOT NULL

    UNION ALL

    SELECT
        Child.ParentAccountTypeCategoryID
       ,COALESCE(Child.ChildAccountTypeID, Child.ChildAccountTypeGroupID, Child.ChildAccountTypeCategoryID) AS [Child]
       ,child.SortOrder
       ,[Level] + 1 AS [Level]
    FROM CPM_AccountTypeCategoryTree Child
    JOIN hirachy g ON g.Child = Child.ParentAccountTypeCategoryID)
SELECT * FROM hirachy
ORDER BY [Level] ASC, SortOrder ASC
```

that gives me the following result set:

Parent
Child
SortOrder
Level

91830
90584
10
1

91812
7
10
1

91812
1
20
1

91812
90581
30
1

7
23
10
2

7
20
20
2

23
83414
10
3

23
90584
20
3

23
NULL
30
3

23
12
40
3

12
90586
10
4

So far so good.

But actualy I want something like this:

Root
Level1
Level2
Level3
Level4

91830
90584

91812
7
23
83414

91812
7
23
90584

91812
7
23
NULL

91812
7
23
12
90586

91812
7
20

91812
1

91812
90581

Can I use my current resultset to create my desired table or do I need a different solution? As the depth of the hirachy is not fixed, I know that I would need some dynamic sql statement. But for now I just need to know how to set up the basic statement.

Hope someone can help me to crack the nut...

Thanks in advance

Alex

Title: Transpose hirarchy table

Body:
I need some help with an table that consists of hirarchy data and I want to get a corresponding view out of it.

I have the following table with some sample data given:

AccountTypeCategoryTreeID
ParentViewTypeID
ParentAccountTypeCategoryID
ChildAccountTypeCategoryID
ChildAccountTypeGroupID
ChildAccountTypeID
SortOrder

2
NULL
7
23
NULL
NULL
10

3
91812
NULL
7
NULL
NULL
10

4
NULL
7
20
NULL
NULL
20

5
NULL
23
NULL
NULL
90584
20

6
91812
NULL
NULL
1
NULL
20

7
NULL
23
NULL
NULL
NULL
30

8
NULL
12
NULL
NULL
90586
10

9
NULL
23
12
NULL
NULL
40

10
91830
NULL
NULL
NULL
90584
10

11
91812
NULL
NULL
NULL
90581
30

The column ParentViewTypeID is always the root element of an tree. The columns ChildAccountTypeID and ChildAccountTypeGroupID are always the last element in the tree. The ParentAccountTypeCategoryID and ChildAccountTypeCategoryID represends the structure.

I have created the statement:

WITH hirachy
AS
(SELECT
        catct.ParentViewTypeID AS [Parent]
       ,COALESCE(catct.ChildAccountTypeID, catct.ChildAccountTypeGroupID, catct.ChildAccountTypeCategoryID) AS [Child]
       ,catct.SortOrder
       ,1 AS [Level]
    FROM CPM_AccountTypeCategoryTree catct
    WHERE catct.ParentViewTypeID IS NOT NULL

    UNION ALL

    SELECT
        Child.ParentAccountTypeCategoryID
       ,COALESCE(Child.ChildAccountTypeID, Child.ChildAccountTypeGroupID, Child.ChildAccountTypeCategoryID) AS [Child]
       ,child.SortOrder
       ,[Level] + 1 AS [Level]
    FROM CPM_AccountTypeCategoryTree Child
    JOIN hirachy g ON g.Child = Child.ParentAccountTypeCategoryID)
SELECT * FROM hirachy
ORDER BY [Level] ASC, SortOrder ASC

that gives me the following result set:

Parent
Child
SortOrder
Level

91830
90584
10
1

91812
7
10
1

91812
1
20
1

91812
90581
30
1

7
23
10
2

7
20
20
2

23
83414
10
3

23
90584
20
3

23
NULL
30
3

23
12
40
3

12
90586
10
4

So far so good.

But actualy I want something like this:

Root
Level1
Level2
Level3
Level4

91830
90584

91812
7
23
83414

91812
7
23
90584

91812
7
23
NULL

91812
7
23
12
90586

91812
7
20

91812
1

91812
90581

Can I use my current resultset to create my desired table or do I need a different solution? As the depth of the hirachy is not fixed, I know that I would need some dynamic sql statement. But for now I just need to know how to set up the basic statement.

Hope someone can help me to crack the nut...

Thanks in advance

Alex


问:
Python addind black lines when writting out text and cannot get rid of them
I am in the process of writting a python script that downloads a copy of quarantined emails from our gateway. The emails are in .eml format ( text ) so was thinking this would be easy but the resulting file does not open in Outlook properly due to the newlines added .

Here is the download/write function :

```<code>def download_message(api_key,endpoint,id):
    endpoint = endpoint + "email/" + id
    headers = {
    'x-fireeye-api-key': api_key,
    'content-type': 'application/json',
    'Accept': 'application/json'}
    data = {}
    r = requests.get(endpoint, headers=headers, data=json.dumps(data))
    if "not found in quarantine." in r.text:
        print("Not found in Quarantine")
    else:
        filename = base_directory + id + ".eml"
        f = open(filename,"w")
        f.write(r.text)
        f.close()
        print("Written : " + id + ".eml" + " to disk")
</code>```

Here is an example of the output file when opened in a text editor

When opened in Outlook this is what it looks like :

If i manually remove all those blank lines ( regex :  ^\n ) and save the file it works as expected.
I have tried quite a few ways of removing those blank lines including strip , rstrip , re.sub and nothing seems to have worked.

If it helps what i was trying to do was create a new variable to hold the "modified" text and then pass that to the write function.
would have looked something like this ( sorry i have tried loads of variations which i have saved but i think you will get the point )

```<code>filedata = r.body.strip("\n") or filedata = re.sub('^\n' , "" , r.text)
...
f.write(filedata)
</code>```

Can anyone help ?

Body:
I am in the process of writting a python script that downloads a copy of quarantined emails from our gateway. The emails are in .eml format ( text ) so was thinking this would be easy but the resulting file does not open in Outlook properly due to the newlines added .

Here is the download/write function :

def download_message(api_key,endpoint,id):
    endpoint = endpoint + "email/" + id
    headers = {
    'x-fireeye-api-key': api_key,
    'content-type': 'application/json',
    'Accept': 'application/json'}
    data = {}
    r = requests.get(endpoint, headers=headers, data=json.dumps(data))
    if "not found in quarantine." in r.text:
        print("Not found in Quarantine")
    else:
        filename = base_directory + id + ".eml"
        f = open(filename,"w")
        f.write(r.text)
        f.close()
        print("Written : " + id + ".eml" + " to disk")

Here is an example of the output file when opened in a text editor

When opened in Outlook this is what it looks like :

If i manually remove all those blank lines ( regex :  ^\n ) and save the file it works as expected.
I have tried quite a few ways of removing those blank lines including strip , rstrip , re.sub and nothing seems to have worked.

If it helps what i was trying to do was create a new variable to hold the "modified" text and then pass that to the write function.
would have looked something like this ( sorry i have tried loads of variations which i have saved but i think you will get the point )

filedata = r.body.strip("\n") or filedata = re.sub('^\n' , "" , r.text)
...
f.write(filedata)

Can anyone help ?


问:
Jalo layer generate different class names
I have this project hierarchy, with jalo class highlighted in blue:

To overwrite jalo class I do

```<code><itemtype code="RgBrandRestriction" extends="AbstractRestriction" autocreate="true" generate="true" jaloclass="com.***.customjalo.RgBrandRestriction">
</code>```

and get generated class

```<code>public abstract class GeneratedRgBrandRestriction
</code>```

then overwrite it by my custom class

```<code>public class RgBrandRestriction extends GeneratedRgBrandRestriction
</code>```

but, when I do <itemtype code="RgCronJob" extends="CronJob" autocreate="true" generate="true" jaloclass="com.***.core.customjalo.cronjob.RgCronJob">

I don't get GeneratedRgCronJob, platform generate com.***.core.customjalo.cronjob.RgCronJob

so I can't extend or get exception "class is already defined"

try to

exclude autocreate="true" generate="true"

do impex for jaloclass

Body:
I have this project hierarchy, with jalo class highlighted in blue:

To overwrite jalo class I do

<itemtype code="RgBrandRestriction" extends="AbstractRestriction" autocreate="true" generate="true" jaloclass="com.***.customjalo.RgBrandRestriction">

and get generated class

public abstract class GeneratedRgBrandRestriction

then overwrite it by my custom class

public class RgBrandRestriction extends GeneratedRgBrandRestriction

but, when I do <itemtype code="RgCronJob" extends="CronJob" autocreate="true" generate="true" jaloclass="com.***.core.customjalo.cronjob.RgCronJob">

I don't get GeneratedRgCronJob, platform generate com.***.core.customjalo.cronjob.RgCronJob

so I can't extend or get exception "class is already defined"

try to

exclude autocreate="true" generate="true"

do impex for jaloclass


问:
how to disable copy paste in workspaces from AWS directory
I am using windows server 2012 and i have created multiple workspaces and attached these workspaces to Active Directory (AD Connector). Now I want to disable copy paste in these workspaces.

I try to disable clipboard redirection from
edit group policy->Administrative Template->Windows Component --> Remote Desktop Sessions->Device and Resource Redirection ->Donot Allow Clipboard redirection(enable it)

but this is not working in workspaces, kindly tell me is it possible to disable copy paste from active directory in workspaces, if yes then kindly share resources


问:
In LWIP SNMPv3 can't understand how to create table for multiple instances oid?
I am facing a challenge with multiple instances in my case I have CharacterEntry Table in which 3 oid but each oid in the table follows double instances one is font index and other is character number.

My code is working with single instance but I cant understand how to create table for multiple instance.

I am using LWIP snmpv3 library.

```<code>/* CharacterEntry .1.3.6.1.4.1.1206.4.2.3.3.4 (.level_0.level_1.level_2)
   where level_0 is the table column ()
   and level_1 the table row (Font index)
   and level_2 the table row (Character number)  */
static const struct snmp_table_col_def characterTable_columns[] = {
    {1, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_ONLY}, /* characterNumber */
    {2, SNMP_ASN1_TYPE_INTEGER,      SNMP_NODE_INSTANCE_READ_WRITE}, /* characterWidth */
    {3, SNMP_ASN1_TYPE_OCTET_STRING,      SNMP_NODE_INSTANCE_READ_WRITE}, /* characterBitmap */
};
* characterTable .1.3.6.1.4.1.1206.4.2.3.3.4 */
static const struct snmp_table_node characterTable = SNMP_TABLE_CREATE(  1, characterTable_columns,  characterTable_get_cell_instance, characterTable_get_next_cell_instance,characterTable_get_value, NULL, characterTable_set_value);

static const u32_t characterTablebase_oid[] = { 1,3,6,1,4,1,1206,4,2,3,3,4};
const struct snmp_mib characterTable_mib = SNMP_MIB_CREATE(characterTablebase_oid, &characterTable.node.node);

</code>```

Please help me how can I implement table for double instances?

Body:
I am facing a challenge with multiple instances in my case I have CharacterEntry Table in which 3 oid but each oid in the table follows double instances one is font index and other is character number.

My code is working with single instance but I cant understand how to create table for multiple instance.

I am using LWIP snmpv3 library.

/* CharacterEntry .1.3.6.1.4.1.1206.4.2.3.3.4 (.level_0.level_1.level_2)
   where level_0 is the table column ()
   and level_1 the table row (Font index)
   and level_2 the table row (Character number)  */
static const struct snmp_table_col_def characterTable_columns[] = {
    {1, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_ONLY}, /* characterNumber */
    {2, SNMP_ASN1_TYPE_INTEGER,      SNMP_NODE_INSTANCE_READ_WRITE}, /* characterWidth */
    {3, SNMP_ASN1_TYPE_OCTET_STRING,      SNMP_NODE_INSTANCE_READ_WRITE}, /* characterBitmap */
};
* characterTable .1.3.6.1.4.1.1206.4.2.3.3.4 */
static const struct snmp_table_node characterTable = SNMP_TABLE_CREATE(  1, characterTable_columns,  characterTable_get_cell_instance, characterTable_get_next_cell_instance,characterTable_get_value, NULL, characterTable_set_value);

static const u32_t characterTablebase_oid[] = { 1,3,6,1,4,1,1206,4,2,3,3,4};
const struct snmp_mib characterTable_mib = SNMP_MIB_CREATE(characterTablebase_oid, &characterTable.node.node);

Please help me how can I implement table for double instances?


问:
How to detect background color on hover Python?
Does anyone know, how you can detect the color on which you're hovering with your cursor with python and returning the color to a string?</p>


问:
Calls to 3rd party exe running within a Process inside Azure .Net Core Web API service (runs on port 6264)
A user on the project I work on has been using a 3rd party exe that he can query to get some data. This exe runs locally and on port 6264, and you can then make calls on your local machine such as:
"http://localhost:6264/api/..."

We would now like put this exe into a production setup, in an Azure Web Api project such that the exe would be running within the Web Api sandbox, and then we can create a Web Api controller to make some RestSharp calls to this exe running locally to the Web Api service and return those results through the controller web api call. That way for any other user wanting to use this data doesnt need to have the exe running on their machine and we have some other background services within Azure that would use this as well to gather data.

I can get this working locally with a simple .Net Core Web Api, that runs the exe within a Process, and then use RestSharp to call the exe API locally. However once i upload to Azure it does not work (i will post the errors further down this post). As an experiment i created a simple background service that runs the process and then calls the running exe (i have left out the users apikey of course)

Simple Web API project with the following hosted service as a simple test:

```<code>public class GatewayService : BackgroundService
{
    private readonly ILogger<GatewayService> _logger;

    public GatewayService(ILogger<GatewayService> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Running Gateway Service");

        string filename = "AnalyticsGateway/AnalyticsGateway.exe";
        string arguments = "";

        var p = new Process();
        string eOut = null;

        p.StartInfo.FileName = filename;
        p.StartInfo.Arguments = arguments;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;

        p.ErrorDataReceived += new DataReceivedEventHandler((sender, e) => eOut += e.Data);

        _logger.LogInformation("Starting AnalyticsGateway.exe");

        if (p.Start())
        {
            _logger.LogInformation("Started AnalyticsGateway.exe");

            _logger.LogInformation("Calling Gateway");

            try
            {
                var client = new RestClient("http://localhost:6264/api/trades?from=2022-12-09T09%3A00%3A00Z&until=2022-12-09T17%3A00%3A00Z&interval=01&intervalUnit=second&instrumentId=10002806&sequenceId=10000302&sequenceItemId=2&ContractType=SinglePeriod");
                var request = new RestRequest(Method.GET);
                request.AddHeader("X-API-KEY", apikey);
                request.AddHeader("accept", "application/json");
                IRestResponse response = client.Execute(request);
                var result = response.Content;

                _logger.LogInformation($"StatusCode: {response.StatusCode}");
                _logger.LogInformation($"ErrorMessage: {response.ErrorMessage}");
                _logger.LogInformation($"IsSuccessful: {response.IsSuccessful}");
                _logger.LogInformation($"ErrorException: {response.ErrorException}");
                _logger.LogInformation($"ResponseStatus: {response.ResponseStatus}");
                _logger.LogInformation($"Result: {result}");
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Unexpected error calling Api");
            }

            try
            {
                _logger.LogInformation("Closing Gateway");

                p.Close();
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Error closing AnalyticsGateway.exe");
            }
        }
        else
        {
            _logger.LogWarning("Unable to start ");
        }
    }
}
</code>```

This works fine on my local setup. However once in azure i get the following log outputs:

```<code>2022-12-16 09:54:11.636 +00:00 [Information] GatewayService: Running Gateway Service
2022-12-16 09:54:11.655 +00:00 [Information] GatewayService: Starting AnalyticsGateway.exe
2022-12-16 09:54:16.329 +00:00 [Information] GatewayService: Started AnalyticsGateway.exe
2022-12-16 09:54:16.329 +00:00 [Information] GatewayService: Calling Gateway
2022-12-16 09:54:16.982 +00:00 [Information] GatewayService: StatusCode: 0
2022-12-16 09:54:16.983 +00:00 [Information] GatewayService: ErrorMessage: An attempt was made to access a socket in a way forbidden by its access permissions. [::ffff:127.0.0.1]:6264 (localhost:6264)
2022-12-16 09:54:16.983 +00:00 [Information] GatewayService: IsSuccessful: False
2022-12-16 09:54:17.031 +00:00 [Information] GatewayService: ErrorException: System.Net.WebException: An attempt was made to access a socket in a way forbidden by its access permissions. [::ffff:127.0.0.1]:6264 (localhost:6264)---> System.Net.Http.HttpRequestException: An attempt was made to access a socket in a way forbidden by its access permissions. [::ffff:127.0.0.1]:6264 (localhost:6264)---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10013): An attempt was made to access a socket in a way forbidden by its access permissions. [::ffff:127.0.0.1]:6264at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)at System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)--- End of stack trace from previous location ---at System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)at System.Net.Sockets.Socket.Connect(String host, Int32 port)at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)at System.Net.HttpWebRequest.<>c__DisplayClass216_0.<<CreateHttpClient>b__1>d.MoveNext()--- End of stack trace from previous location ---at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)--- End of inner exception stack trace ---
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellation(CancellationToken cancellationToken)at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)at System.Net.Http.HttpMessageHandlerStage.Send(HttpRequestMessage request, CancellationToken cancellationToken)at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.HttpMessageHandlerStage.Send(HttpRequestMessage request, CancellationToken cancellationToken)at System.Net.Http.SocketsHttpHandler.Send(HttpRequestMessage request, CancellationToken cancellationToken)at System.Net.Http.HttpMessageInvoker.Send(HttpRequestMessage request, CancellationToken cancellationToken)at System.Net.Http.HttpClient.Send(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)at System.Net.HttpWebRequest.SendRequest(Boolean async)at System.Net.HttpWebRequest.GetResponse()--- End of inner exception stack trace ---at System.Net.HttpWebRequest.GetResponse()at RestSharp.Http.<ExecuteRequest>g__GetRawResponse|185_1(WebRequest request)at RestSharp.Http.ExecuteRequest(String httpMethod, Action`1 prepareRequest)
2022-12-16 09:54:17.032 +00:00 [Information] GatewayService: ResponseStatus: Error
2022-12-16 09:54:17.032 +00:00 [Information] GatewayService: Result:
2022-12-16 09:54:17.032 +00:00 [Information] GatewayService: Closing Gateway
</code>```

Maybe its because i am calling 'localhost' within Azure which isnt allowed or the right way?
Perhaps its because the exe is running on port 6264, is this somehow blocked within Azure? If i remember correctly Azure web app service only allows 80 and 443 but thats only for incoming calls?

I have also tried replacing the localhost with the url of the azure webapp service but i get this error (I have replaced the IP and part of the url with * just for security):

```<code>2022-12-16 10:24:08.392 +00:00 [Information] GatewayService: ErrorMessage: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. [::ffff:*.*.*.*]:6264 (*****.azurewebsites.net:6264)
</code>```

The docs for the 3rd party exe show i can bind to other host / ports

The 3rd party exe does appear to be running within the sandbox as Kudu shows

I am a newbie with Docker but perhaps i can use Docker to run this? If so, how would the exe run within Docker as i thought Docker is a linux setup and this is a windows exe or do i run the Docker as windows somehow - apologies if this is a stupid question.

Thanks

Body:
A user on the project I work on has been using a 3rd party exe that he can query to get some data. This exe runs locally and on port 6264, and you can then make calls on your local machine such as:
"http://localhost:6264/api/..."

We would now like put this exe into a production setup, in an Azure Web Api project such that the exe would be running within the Web Api sandbox, and then we can create a Web Api controller to make some RestSharp calls to this exe running locally to the Web Api service and return those results through the controller web api call. That way for any other user wanting to use this data doesnt need to have the exe running on their machine and we have some other background services within Azure that would use this as well to gather data.

I can get this working locally with a simple .Net Core Web Api, that runs the exe within a Process, and then use RestSharp to call the exe API locally. However once i upload to Azure it does not work (i will post the errors further down this post). As an experiment i created a simple background service that runs the process and then calls the running exe (i have left out the users apikey of course)

Simple Web API project with the following hosted service as a simple test:

public class GatewayService : BackgroundService
{
    private readonly ILogger<GatewayService> _logger;

    public GatewayService(ILogger<GatewayService> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Running Gateway Service");

        string filename = "AnalyticsGateway/AnalyticsGateway.exe";
        string arguments = "";

        var p = new Process();
        string eOut = null;

        p.StartInfo.FileName = filename;
        p.StartInfo.Arguments = arguments;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;

        p.ErrorDataReceived += new DataReceivedEventHandler((sender, e) => eOut += e.Data);

        _logger.LogInformation("Starting AnalyticsGateway.exe");

        if (p.Start())
        {
            _logger.LogInformation("Started AnalyticsGateway.exe");

            _logger.LogInformation("Calling Gateway");

            try
            {
                var client = new RestClient("http://localhost:6264/api/trades?from=2022-12-09T09%3A00%3A00Z&until=2022-12-09T17%3A00%3A00Z&interval=01&intervalUnit=second&instrumentId=10002806&sequenceId=10000302&sequenceItemId=2&ContractType=SinglePeriod");
                var request = new RestRequest(Method.GET);
                request.AddHeader("X-API-KEY", apikey);
                request.AddHeader("accept", "application/json");
                IRestResponse response = client.Execute(request);
                var result = response.Content;

                _logger.LogInformation($"StatusCode: {response.StatusCode}");
                _logger.LogInformation($"ErrorMessage: {response.ErrorMessage}");
                _logger.LogInformation($"IsSuccessful: {response.IsSuccessful}");
                _logger.LogInformation($"ErrorException: {response.ErrorException}");
                _logger.LogInformation($"ResponseStatus: {response.ResponseStatus}");
                _logger.LogInformation($"Result: {result}");
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Unexpected error calling Api");
            }

            try
            {
                _logger.LogInformation("Closing Gateway");

                p.Close();
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Error closing AnalyticsGateway.exe");
            }
        }
        else
        {
            _logger.LogWarning("Unable to start ");
        }
    }
}

This works fine on my local setup. However once in azure i get the following log outputs:

2022-12-16 09:54:11.636 +00:00 [Information] GatewayService: Running Gateway Service
2022-12-16 09:54:11.655 +00:00 [Information] GatewayService: Starting AnalyticsGateway.exe
2022-12-16 09:54:16.329 +00:00 [Information] GatewayService: Started AnalyticsGateway.exe
2022-12-16 09:54:16.329 +00:00 [Information] GatewayService: Calling Gateway
2022-12-16 09:54:16.982 +00:00 [Information] GatewayService: StatusCode: 0
2022-12-16 09:54:16.983 +00:00 [Information] GatewayService: ErrorMessage: An attempt was made to access a socket in a way forbidden by its access permissions. [::ffff:127.0.0.1]:6264 (localhost:6264)
2022-12-16 09:54:16.983 +00:00 [Information] GatewayService: IsSuccessful: False
2022-12-16 09:54:17.031 +00:00 [Information] GatewayService: ErrorException: System.Net.WebException: An attempt was made to access a socket in a way forbidden by its access permissions. [::ffff:127.0.0.1]:6264 (localhost:6264)---> System.Net.Http.HttpRequestException: An attempt was made to access a socket in a way forbidden by its access permissions. [::ffff:127.0.0.1]:6264 (localhost:6264)---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10013): An attempt was made to access a socket in a way forbidden by its access permissions. [::ffff:127.0.0.1]:6264at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)at System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)--- End of stack trace from previous location ---at System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)at System.Net.Sockets.Socket.Connect(String host, Int32 port)at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)at System.Net.HttpWebRequest.<>c__DisplayClass216_0.<<CreateHttpClient>b__1>d.MoveNext()--- End of stack trace from previous location ---at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)--- End of inner exception stack trace ---
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellation(CancellationToken cancellationToken)at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)at System.Net.Http.HttpMessageHandlerStage.Send(HttpRequestMessage request, CancellationToken cancellationToken)at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)at System.Net.Http.HttpMessageHandlerStage.Send(HttpRequestMessage request, CancellationToken cancellationToken)at System.Net.Http.SocketsHttpHandler.Send(HttpRequestMessage request, CancellationToken cancellationToken)at System.Net.Http.HttpMessageInvoker.Send(HttpRequestMessage request, CancellationToken cancellationToken)at System.Net.Http.HttpClient.Send(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)at System.Net.HttpWebRequest.SendRequest(Boolean async)at System.Net.HttpWebRequest.GetResponse()--- End of inner exception stack trace ---at System.Net.HttpWebRequest.GetResponse()at RestSharp.Http.<ExecuteRequest>g__GetRawResponse|185_1(WebRequest request)at RestSharp.Http.ExecuteRequest(String httpMethod, Action`1 prepareRequest)
2022-12-16 09:54:17.032 +00:00 [Information] GatewayService: ResponseStatus: Error
2022-12-16 09:54:17.032 +00:00 [Information] GatewayService: Result:
2022-12-16 09:54:17.032 +00:00 [Information] GatewayService: Closing Gateway

Maybe its because i am calling 'localhost' within Azure which isnt allowed or the right way?
Perhaps its because the exe is running on port 6264, is this somehow blocked within Azure? If i remember correctly Azure web app service only allows 80 and 443 but thats only for incoming calls?

I have also tried replacing the localhost with the url of the azure webapp service but i get this error (I have replaced the IP and part of the url with * just for security):

2022-12-16 10:24:08.392 +00:00 [Information] GatewayService: ErrorMessage: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. [::ffff:*.*.*.*]:6264 (*****.azurewebsites.net:6264)

The docs for the 3rd party exe show i can bind to other host / ports

The 3rd party exe does appear to be running within the sandbox as Kudu shows

I am a newbie with Docker but perhaps i can use Docker to run this? If so, how would the exe run within Docker as i thought Docker is a linux setup and this is a windows exe or do i run the Docker as windows somehow - apologies if this is a stupid question.

Thanks


问:
socket.io server keeps loading when using self certificate
i have troubles with my socket.io server as it keeps loading the site. It dosent give any error, it just keeps loading. please help as i really dont know where the error is.

when im using curl it gives me this: curl: (curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

server.js

```<code>'use strict';

// Setup basic express server
var express = require('express');
var app = express();

const fs = require('fs')
// Routing
const https = require('https');

const secureServer = https.createServer({

key: fs.readFileSync('./server.key'),

cert: fs.readFileSync('./server.cert')

}, express);

//Setup public file

const ios = require('socket.io')(secureServer);

secureServer.listen(4000, () => {

  console.log('secure server started at 4000');

  })
// Chatroom

// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;

ios.on('connection', function (socket) {
  console.log("hello")
}

</code>```

client.js

```<code>    const socket = io(4000, { transports: ['websocket'], rejectUnauthorized: false });
</code>```

Body:
i have troubles with my socket.io server as it keeps loading the site. It dosent give any error, it just keeps loading. please help as i really dont know where the error is.

when im using curl it gives me this: curl: (curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

server.js

'use strict';

// Setup basic express server
var express = require('express');
var app = express();

const fs = require('fs')
// Routing
const https = require('https');

const secureServer = https.createServer({

key: fs.readFileSync('./server.key'),

cert: fs.readFileSync('./server.cert')

}, express);

//Setup public file

const ios = require('socket.io')(secureServer);

secureServer.listen(4000, () => {

  console.log('secure server started at 4000');

  })
// Chatroom

// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;

ios.on('connection', function (socket) {
  console.log("hello")
}

client.js

    const socket = io(4000, { transports: ['websocket'], rejectUnauthorized: false });


问:
Can't create database, '[Name Database]'; exists with doctrine:database:create
I have a problem with my database.
I try to create database with symfony command : doctrine:database:create.
Before, i clone the repository on github, i configure the server on symfony project and i use the command composer install.

I use Symfony 6 and PhpMyAdmin with MAMP.

The file .env (i don't want create a .env.local) :
`

```<code># In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
#  * .env                contains default values for the environment variables needed by the app
#  * .env.local          uncommitted file with local overrides
#  * .env.$APP_ENV       committed environment-specific defaults
#  * .env.$APP_ENV.local uncommitted environment-specific overrides
#
# Real environment variables win over .env files.
#
# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES.
# https://symfony.com/doc/current/configuration/secrets.html
#
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration

###> symfony/framework-bundle ###
  APP_SECRET="fdkjqnfoiuqezhpfidsdqbdhbfqjdsbjhqbsdcljbqjs"
###< symfony/framework-bundle ###

###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
#
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
  DATABASE_URL="mysql://root@127.0.0.1:3306/holland_back"
# DATABASE_URL="postgresql://app:!ChangeMe!@127.0.0.1:5432/app?serverVersion=14&charset=utf8"
###< doctrine/doctrine-bundle ###

###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'
###< nelmio/cors-bundle ###
</code>```

`

The command on my terminal :
holland-back git:(main) ✗ symfony console doctrine:database:create                      Could not create database holland_back for connection named default An exception occurred while executing a query: SQLSTATE[HY000]: General error: 1007 Can't create database 'holland_back'; database exists

I try to create database with symfony command : doctrine:database:create.

I put databases image on PhpMyAdmin.
When I drop database on PhpMyAdmin, the message is :
`Erreur
Requête SQL : Copier

DROP DATABASE holland_back
MySQL a répondu : Documentation

#1008 - Ne peut effacer la base 'holland_back'; elle n'existe pas`
She doesn't exist.

Thanks for your help...
Have a nice day.

Body:
I have a problem with my database.
I try to create database with symfony command : doctrine:database:create.
Before, i clone the repository on github, i configure the server on symfony project and i use the command composer install.

I use Symfony 6 and PhpMyAdmin with MAMP.

The file .env (i don't want create a .env.local) :
`

# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
#  * .env                contains default values for the environment variables needed by the app
#  * .env.local          uncommitted file with local overrides
#  * .env.$APP_ENV       committed environment-specific defaults
#  * .env.$APP_ENV.local uncommitted environment-specific overrides
#
# Real environment variables win over .env files.
#
# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES.
# https://symfony.com/doc/current/configuration/secrets.html
#
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration

###> symfony/framework-bundle ###
  APP_SECRET="fdkjqnfoiuqezhpfidsdqbdhbfqjdsbjhqbsdcljbqjs"
###< symfony/framework-bundle ###

###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
#
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
  DATABASE_URL="mysql://root@127.0.0.1:3306/holland_back"
# DATABASE_URL="postgresql://app:!ChangeMe!@127.0.0.1:5432/app?serverVersion=14&charset=utf8"
###< doctrine/doctrine-bundle ###

###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'
###< nelmio/cors-bundle ###

`

The command on my terminal :
holland-back git:(main) ✗ symfony console doctrine:database:create                      Could not create database holland_back for connection named default An exception occurred while executing a query: SQLSTATE[HY000]: General error: 1007 Can't create database 'holland_back'; database exists

I try to create database with symfony command : doctrine:database:create.

I put databases image on PhpMyAdmin.
When I drop database on PhpMyAdmin, the message is :
`Erreur
Requête SQL : Copier

DROP DATABASE holland_back
MySQL a répondu : Documentation

#1008 - Ne peut effacer la base 'holland_back'; elle n'existe pas`
She doesn't exist.

Thanks for your help...
Have a nice day.


问:
how gamma and beta get updated during backward process in batch normalization layer
Could you please let me know whether it is possible to check how the gamma and beta of the batch normalization layer get updated during the backpropagation process in PyTorch or TensorFlow? I mean, can I print their values in each epoch?</p>


问:
How can I efficiently partition a list of numbers into a number of nonoverlapping buckets efficiently where there are potentially many buckets?
I wrote some code to assign items to a number of buckets.

I have N many buckets of Y many types. And Y numbers. How do you determine all the buckets that each Y number is part of?

A Y number is in a bucket if it is >= start of the bucket range and <= end of the bucket range. It's kind of similar to collision detection.

I am trying to find what user bucket the user 5607 falls into, what thread bucket thread 11 fits into and what server bucket server 3 falls into

I think the Big O notation of my solution is N buckets for the number of buckets.

Is there a faster approach to dividing a list of Y numbers into N buckets?

```<code>from operator import itemgetter
buckets2 = {
  "buckets": [
    {"type": "user", "name": "users-bucket1", "start": 0, "end": 5000},
    {"type": "user", "name": "users-bucket2", "start": 5001, "end": 10000},
    {"type": "user", "name": "users-bucket3", "start": 10001, "end": 15000},
    {"type": "server", "name": "server-bucket1", "start": 0, "end": 3},
    {"type": "server", "name": "server-bucket2", "start": 4, "end": 7},
    {"type": "server","name": "server-bucket3", "start": 8, "end": 10},
    {"type": "thread", "name": "threads-bucket1", "start": 0, "end": 4},
    {"type": "thread", "name": "threads-bucket2", "start": 5, "end": 9},
    {"type": "thread", "name": "threads-bucket3", "start": 10, "end": 14}
    ]
 }

 buckets2["buckets"].sort(key=itemgetter("start"), reverse=True)

 def route2(routing_information):
    buckets = {}
    for item in buckets2["buckets"]:
       if item["end"] >= routing_information[item["type"]]:
           buckets[item["type"]] = item["name"]
    return buckets

 print(route2({ "server": 3, "user": 5607, "thread": 11}))
</code>```

This gives

```<code>{'user': 'users-bucket2', 'thread': 'threads-bucket3', 'server': 'server-bucket1'}
</code>```

This code shall be called very frequently, so I want it to be fast.

Body:
I wrote some code to assign items to a number of buckets.

I have N many buckets of Y many types. And Y numbers. How do you determine all the buckets that each Y number is part of?

A Y number is in a bucket if it is >= start of the bucket range and <= end of the bucket range. It's kind of similar to collision detection.

I am trying to find what user bucket the user 5607 falls into, what thread bucket thread 11 fits into and what server bucket server 3 falls into

I think the Big O notation of my solution is N buckets for the number of buckets.

Is there a faster approach to dividing a list of Y numbers into N buckets?

from operator import itemgetter
buckets2 = {
  "buckets": [
    {"type": "user", "name": "users-bucket1", "start": 0, "end": 5000},
    {"type": "user", "name": "users-bucket2", "start": 5001, "end": 10000},
    {"type": "user", "name": "users-bucket3", "start": 10001, "end": 15000},
    {"type": "server", "name": "server-bucket1", "start": 0, "end": 3},
    {"type": "server", "name": "server-bucket2", "start": 4, "end": 7},
    {"type": "server","name": "server-bucket3", "start": 8, "end": 10},
    {"type": "thread", "name": "threads-bucket1", "start": 0, "end": 4},
    {"type": "thread", "name": "threads-bucket2", "start": 5, "end": 9},
    {"type": "thread", "name": "threads-bucket3", "start": 10, "end": 14}
    ]
 }

 buckets2["buckets"].sort(key=itemgetter("start"), reverse=True)

 def route2(routing_information):
    buckets = {}
    for item in buckets2["buckets"]:
       if item["end"] >= routing_information[item["type"]]:
           buckets[item["type"]] = item["name"]
    return buckets

 print(route2({ "server": 3, "user": 5607, "thread": 11}))

This gives

{'user': 'users-bucket2', 'thread': 'threads-bucket3', 'server': 'server-bucket1'}

This code shall be called very frequently, so I want it to be fast.


问:
Altova Mapforce: Joining XML Input and conditional SQL Join using two tables
I'm trying to get the following done: Using Altova Mapforce, I use an XML file with schema as a source. I want to map it to exactly the same output, but only add data to one field.

The value of the field (it's Tax) is determined using a two table SQL join with a WHERE clause over both tables. The tables are joined using foreign keys, the relation is recognized by Mapforce.

The first field of the WHERE clause comes from the first table (header type table), the second and third field from the second tables (lines type tables).

However, I cannot seem to create the logical and correct equivalent of what I am describing here. I've tried it using complex AND constructions where it then inserts the one field I would need multiple times. I've tried WHERE clauses but they fail as they never supply both tables at the same time and there seems to be no way to use a pre-specified JOINing of two tables as a source. The WHERE clause then recognizes only the fields from the first table, not the second one.

Is there an example for this? Joining two (or more) tables, using WHERE to determine the exact row, then using a value from that row?

Best wishes.

ContentLicense: CC BY-SA 3.0


问:
ngModel detective in Angular like expression does not work fine
I need to create dynamically my calendar class to represent sometimes the first fortnight of the month and other times the second. So once my class has this properties

Other this one

So I bind this class to the template like this

```<code> <mat-table [dataSource]="dataSource">
   <ng-container matColumnDef="{{this.columnsToDisplay[2]}}">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>{{this.columnsToDisplay[2]}}</th>
    <td mat-cell *matCellDef="let element; let i=index">
      <mat-form-field class="form-input">
        <input type="number" matInput [(ngModel)]="quincenaUrl==1?element.dia1:element.dia16"
          (keyup.enter)="editarCelda2($event, i, this.columnsToDisplay[2])" />
      </mat-form-field>
    </td>
  </ng-container>
</code>```

But this

```<code>[(ngModel)]="quincenaUrl==1?element.dia1:element.dia16"
</code>```

Only works in case quincena==2

That is When I edit this cell the dataSource is updated with that value

But when I select the first fortnight

Tha value edited in the template is not updated in the dataSource binded

Any idea, please?

Thanks

Body:
I need to create dynamically my calendar class to represent sometimes the first fortnight of the month and other times the second. So once my class has this properties

Other this one

So I bind this class to the template like this

 <mat-table [dataSource]="dataSource">
   <ng-container matColumnDef="{{this.columnsToDisplay[2]}}">
    {{this.columnsToDisplay[2]}}

      <mat-form-field class="form-input">
        <input type="number" matInput [(ngModel)]="quincenaUrl==1?element.dia1:element.dia16"
          (keyup.enter)="editarCelda2($event, i, this.columnsToDisplay[2])" />
      </mat-form-field>

  </ng-container>

But this

[(ngModel)]="quincenaUrl==1?element.dia1:element.dia16"

Only works in case quincena==2

That is When I edit this cell the dataSource is updated with that value

But when I select the first fortnight

Tha value edited in the template is not updated in the dataSource binded

Any idea, please?

Thanks


问:
Stub out a method call inside a method for testing
I have a method that writes out to a word doc using Apache POI API. The issue I am having is, I want to test the method without creating an external document. The method that creates the document is the .write(OutputStream).

I need to find a way to get that method to doNothing() but when I have tried to mock the XWPFDocument, I get errors that there were 0 invocations on the mock.

Here is the method I am trying to test:

public String populateDoc(String text) {
    try (XWPFDocument doc = new XWPFDocument();
         OutputStream out = Files.newOutputStream(OUT)) {
        StringBuilder sb = new StringBuilder();
        LOGGER.info("Document Created.");
        String[] lines = text.split("\n");
        for (String line : lines) {
            XWPFParagraph para = doc.createParagraph();
            XWPFRun run = para.createRun();
            run.setText(line);
            sb.append(line);
            sb.append("\n");
        }
        LOGGER.info("Document saved.");
        doc.write(out);
        return sb.toString();
    } catch (IOException ioe) {
        LOGGER.error(ioe);
    }
    return null;
}
```
<p>The test I have right now that creates an external document which I don't want:</p>
<pre class="lang-java prettyprint-override"><code>@ExtendWith(MockitoExtension.class)
public class FileWriterTest {
    @Test
    void testFileContainsAParagraph() {
        FileWriter fileWriter = new FileWriter("src/test/resources/outputTest.docx");
        String text = "Hello World.\n";

        Assertions.assertEquals(text, fileWriter.populateDoc(text));
    }
}
</code>```

What I have tried:

@Test
void testTextReturnsHello() throws IOException {
    XWPFDocument doc = mock (XWPFDocument.class);
    FileWriter fileWriter = new FileWriter();
    OutputStream out = Files.newOutputStream(Paths.get("src/test/resources/outputTest.docx"));
    String text = "Hello";
    Mockito.doNothing().when(doc).write(out);

    Assertions.assertEquals(text, fileWriter.populateDoc(text));

    Mockito.verify(doc).write(out);
}
```
<p>Error I get:</p>
<pre class="lang-none prettyprint-override"><code>org.mockito.exceptions.base.MockitoException:
Only void methods can doNothing()!
Example of correct use of doNothing():
    doNothing().
    doThrow(new RuntimeException())
    .when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called
</code>```

Body:
I have a method that writes out to a word doc using Apache POI API. The issue I am having is, I want to test the method without creating an external document. The method that creates the document is the .write(OutputStream).

I need to find a way to get that method to doNothing() but when I have tried to mock the XWPFDocument, I get errors that there were 0 invocations on the mock.

Here is the method I am trying to test:

public String populateDoc(String text) {
    try (XWPFDocument doc = new XWPFDocument();
         OutputStream out = Files.newOutputStream(OUT)) {
        StringBuilder sb = new StringBuilder();
        LOGGER.info("Document Created.");
        String[] lines = text.split("\n");
        for (String line : lines) {
            XWPFParagraph para = doc.createParagraph();
            XWPFRun run = para.createRun();
            run.setText(line);
            sb.append(line);
            sb.append("\n");
        }
        LOGGER.info("Document saved.");
        doc.write(out);
        return sb.toString();
    } catch (IOException ioe) {
        LOGGER.error(ioe);
    }
    return null;
}

The test I have right now that creates an external document which I don't want:

@ExtendWith(MockitoExtension.class)
public class FileWriterTest {
    @Test
    void testFileContainsAParagraph() {
        FileWriter fileWriter = new FileWriter("src/test/resources/outputTest.docx");
        String text = "Hello World.\n";

        Assertions.assertEquals(text, fileWriter.populateDoc(text));
    }
}

What I have tried:

@Test
void testTextReturnsHello() throws IOException {
    XWPFDocument doc = mock (XWPFDocument.class);
    FileWriter fileWriter = new FileWriter();
    OutputStream out = Files.newOutputStream(Paths.get("src/test/resources/outputTest.docx"));
    String text = "Hello";
    Mockito.doNothing().when(doc).write(out);

    Assertions.assertEquals(text, fileWriter.populateDoc(text));

    Mockito.verify(doc).write(out);
}

Error I get:

org.mockito.exceptions.base.MockitoException:
Only void methods can doNothing()!
Example of correct use of doNothing():
    doNothing().
    doThrow(new RuntimeException())
    .when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called


问:
Google Calendar API - How to create a Calendar without duplicates
I would like to create a script in python that creates specific calendar in python for each user with Google Calendar API, I don't know how to to check if the calendar already exists, I don't know if I have to make an excel list with the name and id of the user or if there is an easier way..


问:
How can I condense a long list of items into categories for a repeated logit regression?
I'm using a program called Apollo to make an ordered logit model. In this model, you have to specify a list of variables like this:

```<code>apollo_beta = c(
                b_var1_dum1 = 0,
                b_var1_dum2 = 0,
                b_var1_dum3 = 0,
                b_var2_dum1 = 0,
                b_var2_dum2 = 0,
                b_var3_dum1 = 0,
                b_var3_dum2 = 0,
                b_var3_dum3 = 0,
                b_var3_dum3 = 0)
</code>```

I want to do two things:

Firstly, I want to be able to specify these beforehand:

```<code>specification1 = c(
                   b_var1_dum1 = 0,
                   b_var1_dum2 = 0,
                   b_var1_dum3 = 0,
                   b_var2_dum1 = 0,
                   b_var2_dum2 = 0,
                   b_var3_dum1 = 0,
                   b_var3_dum2 = 0,
                   b_var3_dum3 = 0,
                   b_var3_dum4 = 0)
</code>```

And then be able to call it:

```<code>apollo_beta = specification1
</code>```

Secondly, I want to be able to make categories:

```<code>var1 <- c(
          b_var1_dum1 = 0,
          b_var1_dum2 = 0,
          b_var1_dum3 = 0)
var2 <- c(
          b_var2_dum1 = 0,
          b_var2_dum2 = 0)
var3 <- c(
          b_var3_dum1 = 0,
          b_var3_dum2 = 0,
          b_var3_dum3 = 0,
          b_var3_dum4 = 0)
</code>```

And then be able to use those in the specification:

```<code>specification1 = c(
                   var1,
                   var2,
                   var3)
</code>```

And then:

```<code>apollo_beta = specification1
</code>```

I know you might not have the best knowledge of the very niche programme Apollo. I am not quite sure if this is even possible, but since it would save me days (maybe weeks) of work, can anyone give me a hint on what I might be doing wrong? I worry I have a list within a list.
Since I have to make 60 specifications of the same model with different variations of 6 variables, it would be a lot of code and lot of work if I can't shorten it like this.

Any tips would be greatly appreciated.

Data:

```<code>df <- data.frame(
var1_dum1 = c(0, 1, 0),
var1_dum2 = c(1, 0, 0),
var1_dum3 = c(0, 0, 1),
var2_dum1 = c(0, 1, 0),
var2_dum2 = c(1, 0, 0),
var3_dum1 = c(1, 1, 0),
var3_dum2 = c(1, 0, 0),
var3_dum3 = c(0, 1, 0),
var3_dum4 = c(0, 0, 1),
)
</code>```

So there is a dataset with these variables. In apollo you specify "database = df" first, so it already refers to the variables.
In the list of apollo_beta, it doesn't refer to the variables directly, so technically you can call it what you want. I just want to call it the same as the variables as I will refer to them later.

My question is simple. Can I condense the long list to simply say "specification1". It's just a question of the r language. Whether the items of the list will function the same way as how it was originally written in code.

In other words, would calling apollo_beta in the above three examples lead to the same result? If not, how do I change the code so that it does lead to the same?

Body:
I'm using a program called Apollo to make an ordered logit model. In this model, you have to specify a list of variables like this:

apollo_beta = c(
                b_var1_dum1 = 0,
                b_var1_dum2 = 0,
                b_var1_dum3 = 0,
                b_var2_dum1 = 0,
                b_var2_dum2 = 0,
                b_var3_dum1 = 0,
                b_var3_dum2 = 0,
                b_var3_dum3 = 0,
                b_var3_dum3 = 0)

I want to do two things:

Firstly, I want to be able to specify these beforehand:

specification1 = c(
                   b_var1_dum1 = 0,
                   b_var1_dum2 = 0,
                   b_var1_dum3 = 0,
                   b_var2_dum1 = 0,
                   b_var2_dum2 = 0,
                   b_var3_dum1 = 0,
                   b_var3_dum2 = 0,
                   b_var3_dum3 = 0,
                   b_var3_dum4 = 0)

And then be able to call it:

apollo_beta = specification1

Secondly, I want to be able to make categories:

var1 <- c(
          b_var1_dum1 = 0,
          b_var1_dum2 = 0,
          b_var1_dum3 = 0)
var2 <- c(
          b_var2_dum1 = 0,
          b_var2_dum2 = 0)
var3 <- c(
          b_var3_dum1 = 0,
          b_var3_dum2 = 0,
          b_var3_dum3 = 0,
          b_var3_dum4 = 0)

And then be able to use those in the specification:

specification1 = c(
                   var1,
                   var2,
                   var3)

And then:

apollo_beta = specification1

I know you might not have the best knowledge of the very niche programme Apollo. I am not quite sure if this is even possible, but since it would save me days (maybe weeks) of work, can anyone give me a hint on what I might be doing wrong? I worry I have a list within a list.
Since I have to make 60 specifications of the same model with different variations of 6 variables, it would be a lot of code and lot of work if I can't shorten it like this.

Any tips would be greatly appreciated.

Data:

df <- data.frame(
var1_dum1 = c(0, 1, 0),
var1_dum2 = c(1, 0, 0),
var1_dum3 = c(0, 0, 1),
var2_dum1 = c(0, 1, 0),
var2_dum2 = c(1, 0, 0),
var3_dum1 = c(1, 1, 0),
var3_dum2 = c(1, 0, 0),
var3_dum3 = c(0, 1, 0),
var3_dum4 = c(0, 0, 1),
)

So there is a dataset with these variables. In apollo you specify "database = df" first, so it already refers to the variables.
In the list of apollo_beta, it doesn't refer to the variables directly, so technically you can call it what you want. I just want to call it the same as the variables as I will refer to them later.

My question is simple. Can I condense the long list to simply say "specification1". It's just a question of the r language. Whether the items of the list will function the same way as how it was originally written in code.

In other words, would calling apollo_beta in the above three examples lead to the same result? If not, how do I change the code so that it does lead to the same?


问:
getting TypeError: Cannot read property 'map' of undefined at /node_modules/compromise/builds/three/compromise-three.cjs:1:52703 with Compromise NER
I just started exploring compromise and was just playing with NER and I tried the below code:

```<code>const nlp = require('compromise');

function extractTransactionData(text) {
  const doc = nlp(text);
  const entities = doc.out('terms').map(term => ({
    text: term.text,
    type: term.tag
  }));

  var amount, from, to;

  for (var i = 0; i < entities.length; i++) {
    var entity = entities[i];

    if (entity.type === 'Money') {
      amount = entity.text;
    }

    if (entity.type === 'Person') {
      from = entity.text;
    }

    if (entity.type === 'Person' && from !== entity.text) {
      to = entity.text;
    }
  }
  return {
    amount: amount,
    from: from,
    to: to
  };
}

const text = "You owe $100 to John Smith.";
console.log(extractTransactionData(text));
</code>```

I expect this code to execute and give the below-expected Output:

```<code>{ amount: '$100', from: 'You', to: 'John Smith' }
</code>```

but the code is breaking with

```<code>TypeError: Cannot read property 'map' of undefined at /node_modules/compromise/builds/three/compromise-three.cjs:1:52703
</code>```

Can someone help get this simple code work?

Body:
I just started exploring compromise and was just playing with NER and I tried the below code:

const nlp = require('compromise');

function extractTransactionData(text) {
  const doc = nlp(text);
  const entities = doc.out('terms').map(term => ({
    text: term.text,
    type: term.tag
  }));

  var amount, from, to;

  for (var i = 0; i < entities.length; i++) {
    var entity = entities[i];

    if (entity.type === 'Money') {
      amount = entity.text;
    }

    if (entity.type === 'Person') {
      from = entity.text;
    }

    if (entity.type === 'Person' && from !== entity.text) {
      to = entity.text;
    }
  }
  return {
    amount: amount,
    from: from,
    to: to
  };
}

const text = "You owe $100 to John Smith.";
console.log(extractTransactionData(text));

I expect this code to execute and give the below-expected Output:

{ amount: '$100', from: 'You', to: 'John Smith' }

but the code is breaking with

TypeError: Cannot read property 'map' of undefined at /node_modules/compromise/builds/three/compromise-three.cjs:1:52703

Can someone help get this simple code work?


问:
Graphql Syntax Error: Expected Name, found "{"
I wrote a query of GraphQL.

```<code>import { gql } from '@apollo/client';
export const GET_CART_DETAILS_QUERY = gql`
    query GetProductSizeChartQuery($sku:String!) {
        getProductSizeChart(sku:$sku){
          heading:{
          label
          values: {
          sku
          attribute_id
          size_id
          size
          is_stock
          }
          }
          sizeChart:{
          title
          options:{
          inch
          cm
          }
          }
          optionLabel:{
          label
          }
        }
    }
`;
</code>```

And I am calling it as :

```<code>    const {
        data: ProductSizeChartData,
        loading: ProductSizeChartLoading,
        error: ProductSizeChartError
    } = useQuery(GET_CART_DETAILS_QUERY, {
        variables: { sku: item?.product?.sku }
    });
</code>```

But I am getting an error :

Syntax Error: Expected Name, found "{".

I am not able to detect what is wrong here. Please help !

Body:
I wrote a query of GraphQL.

import { gql } from '@apollo/client';
export const GET_CART_DETAILS_QUERY = gql`
    query GetProductSizeChartQuery($sku:String!) {
        getProductSizeChart(sku:$sku){
          heading:{
          label
          values: {
          sku
          attribute_id
          size_id
          size
          is_stock
          }
          }
          sizeChart:{
          title
          options:{
          inch
          cm
          }
          }
          optionLabel:{
          label
          }
        }
    }
`;

And I am calling it as :

    const {
        data: ProductSizeChartData,
        loading: ProductSizeChartLoading,
        error: ProductSizeChartError
    } = useQuery(GET_CART_DETAILS_QUERY, {
        variables: { sku: item?.product?.sku }
    });

But I am getting an error :

Syntax Error: Expected Name, found "{".

I am not able to detect what is wrong here. Please help !


问:
on cordova app not able to pring the text
I am trying to print functionality on cordova app, i have added the plugin and written the code, but its not showing any print dialog app, nor throughing error.

follwing plugin added the code form below URL
https://github.com/katzer/cordova-plugin-printer
here you go the code

```<code>function get_print()
    {alert('4');
    var options = {
    font: {
        size: 22,
        italic: true,
        align: 'center'
    },
    header: {
        height: '6cm',
        label: {
            text: "\n\nDie Freuden",
            font: {
                bold: true,
                size: 37,
                align: 'center'
            }
        }
    },
    footer: {
        height: '4cm',
        label: {
            text: 'Johann Wolfgang von Goethe, 1749-1832, deutscher Dichter, Naturforscher',
            font: { align: 'center' }
        }
    }
};

cordova.plugins.printer.print("Es flattert um die Quelle\nDie wechselnde Libelle,...", options);

    alert('2');
    }
</code>```

could you please advise me

I am looking the solution

Body:
I am trying to print functionality on cordova app, i have added the plugin and written the code, but its not showing any print dialog app, nor throughing error.

follwing plugin added the code form below URL
https://github.com/katzer/cordova-plugin-printer
here you go the code

function get_print()
    {alert('4');
    var options = {
    font: {
        size: 22,
        italic: true,
        align: 'center'
    },
    header: {
        height: '6cm',
        label: {
            text: "\n\nDie Freuden",
            font: {
                bold: true,
                size: 37,
                align: 'center'
            }
        }
    },
    footer: {
        height: '4cm',
        label: {
            text: 'Johann Wolfgang von Goethe, 1749-1832, deutscher Dichter, Naturforscher',
            font: { align: 'center' }
        }
    }
};

cordova.plugins.printer.print("Es flattert um die Quelle\nDie wechselnde Libelle,...", options);

    alert('2');
    }

could you please advise me

I am looking the solution


问:
How to do exports for different packages
I have monorepo setup for one of my project, and that monorepo is basically a common component library that we are using in different project for components building.

We are facing some issue with bundle size of the package.

I tried using exports in package.json but that too didn't work in our case and also tried exporting default and named exports, but didn't get through it.

What we want to achieve is suppose we want to import List component in some application, so there we want to import like 'import {List} from "@common-lib/List"' like this, but we are not able to achieve that.

I referred to mui library as this is also monorepo, and we are able to import components from monorepo like this.
So can you please suggest what changes we need to make to make it compatible for this.

Thanks


问:
Test cases in .NET Core 6
The problem is in my API, I have multiple reference project methods used in service layer and service layer also has a reference project. My question is how to implement test case in my API with all reference project method layers?

```<code>protected async Task<DatabaseSchemaService> GetDatabaseSchemaServiceObject()
{
    var vaultDataServiceMock = new Mock<IVaultDataService>();
    var _databaseAdapterMock = new Mock<IEnumerable<IDatabaseAdapter>>();
    var _connectionDetailsMock = new Mock<IConnectionDetails>();
    var _databaseServiceMock = new Mock<IRelationalDatabaseService>();

    DatabaseSchemaService databaseSchemaService =
    new DatabaseSchemaService(_databaseAdapterMock.Object,
        _connectionDetailsMock.Object, vaultDataServiceMock.Object, _databaseServiceMock.Object);

    return databaseSchemaService;
}
</code>```
```<code>[Theory]
[InlineData(DatabaseTypeEnum.SqlServer, 13, "LES", ""]
public async void GetAllTableTest(DatabaseTypeEnum databaseTypeEnum, int connectionDetailId, string databaseName,
    string schemaName)
{
    var token = await GetAuthToken();
    var databaseSchemaService = await GetDatabaseSchemaServiceObject();
    var data = await databaseSchemaService.GetTables(databaseTypeEnum, connectionDetailId, databaseName,
         schemaName, token, CancellationToken.None);
}
</code>```

In example we have lots of object to perform a simple getAllTableTest case.

Any idea how do this type of test case?

Title: Test cases in .NET Core 6

Body:
The problem is in my API, I have multiple reference project methods used in service layer and service layer also has a reference project. My question is how to implement test case in my API with all reference project method layers?

protected async Task<DatabaseSchemaService> GetDatabaseSchemaServiceObject()
{
    var vaultDataServiceMock = new Mock<IVaultDataService>();
    var _databaseAdapterMock = new Mock<IEnumerable<IDatabaseAdapter>>();
    var _connectionDetailsMock = new Mock<IConnectionDetails>();
    var _databaseServiceMock = new Mock<IRelationalDatabaseService>();

    DatabaseSchemaService databaseSchemaService =
    new DatabaseSchemaService(_databaseAdapterMock.Object,
        _connectionDetailsMock.Object, vaultDataServiceMock.Object, _databaseServiceMock.Object);

    return databaseSchemaService;
}

[Theory]
[InlineData(DatabaseTypeEnum.SqlServer, 13, "LES", ""]
public async void GetAllTableTest(DatabaseTypeEnum databaseTypeEnum, int connectionDetailId, string databaseName,
    string schemaName)
{
    var token = await GetAuthToken();
    var databaseSchemaService = await GetDatabaseSchemaServiceObject();
    var data = await databaseSchemaService.GetTables(databaseTypeEnum, connectionDetailId, databaseName,
         schemaName, token, CancellationToken.None);
}

In example we have lots of object to perform a simple getAllTableTest case.

Any idea how do this type of test case?


问:
Storybook, TypeScript, when creating a story, IDE is complaining about missing properties from type
I've been trying to use Storybook, Styledcomponents and Typescript but I'm getting an issue when trying to follow the guides out there.

In the part where I comment in my PrimaryButton.stories.tsx my IDE is complaining to add the attributes here instead of the Default.args object.. but everywhere I"m looking at doesn't require me to do this and to add it to the Default.args.

What am I doing wrong?

index.tsx

```<code>interface IProps {
  children: ReactNode,
  onClick: () => void,
  width: string,
}

const PrimaryButton = ({ children, ...args }: IProps) => {
  return (
    <StyledPrimaryButton {...args}>
      {children}
    </StyledPrimaryButton>
  );
};

export default PrimaryButton;
</code>```

PrimaryButton.stories.tsx

```<code>export default {
  title: "Components/PrimaryButton",
  component: PrimaryButton,
} as Meta;

const Template: Story = (args) => (
  <PrimaryButton {...args}>  // COMPLAINS HERE TO ADD MISSING ATTRIBUTES
    Hello World
  </PrimaryButton>
);

export const Default = Template.bind({});

Default.args = {
  children: "PrimaryButton",
  onClick: () => {},
  width: "100px"
};
</code>```

Body:
I've been trying to use Storybook, Styledcomponents and Typescript but I'm getting an issue when trying to follow the guides out there.

In the part where I comment in my PrimaryButton.stories.tsx my IDE is complaining to add the attributes here instead of the Default.args object.. but everywhere I"m looking at doesn't require me to do this and to add it to the Default.args.

What am I doing wrong?

index.tsx

interface IProps {
  children: ReactNode,
  onClick: () => void,
  width: string,
}

const PrimaryButton = ({ children, ...args }: IProps) => {
  return (

  );
};

export default PrimaryButton;

PrimaryButton.stories.tsx

export default {
  title: "Components/PrimaryButton",
  component: PrimaryButton,
} as Meta;

const Template: Story = (args) => (
  <PrimaryButton {...args}>  // COMPLAINS HERE TO ADD MISSING ATTRIBUTES
    Hello World
  </PrimaryButton>
);

export const Default = Template.bind({});

Default.args = {
  children: "PrimaryButton",
  onClick: () => {},
  width: "100px"
};


问:
retryWhen barred in VSCode
Hello I have the retryWhen pipeable function barred in VScode, it seem like a deprecated method, do you have any idea about this:

Title: retryWhen barred in VSCode


问:
Creating a live connection to airtable from tableau
Not sure whether this is the correct outlet for this question but here goes. Currently, my company’s connection to airtable has to be refreshed manually when we are updating our dashboards. However, we are looking to speed this up by periodically running the flow so that the dashboard can be updated automatically.

As of now, what ive researched is to use pyairtable to extract the data and clean it within python first and then use a seperate automation script (pythonanywhere maybe) to run this extract periodically.

My question is: Is there a better way to go about this? or is this really the fastest way to connect it？


问:
Property 'fetchPriority' does not exist on type 'DetailedHTMLProps<LinkHTMLAttributes<HTMLLinkElement>, HTMLLinkElement>'
I am trying to add "fetchPriority" to link tag as below.

```<code>const optionalPreload =
    ServerOnlyHead  ? (
      <ServerOnlyHead
        children={
          <link
            fetchPriority="high" // error here !!!
            rel="preload"
            as="image"
            href={image?.src || ""}
          />
        }
      />
    ) : null;
</code>```

but it throws following error,

```<code>Type '{ fetchPriority: string; rel: string; as: string; href: string; }' is not assignable to type 'DetailedHTMLProps<LinkHTMLAttributes<HTMLLinkElement>, HTMLLinkElement>'.
  Property 'fetchPriority' does not exist on type 'DetailedHTMLProps<LinkHTMLAttributes<HTMLLinkElement>, HTMLLinkElement>'.ts(2322)
'fetchPriority' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.ts(7022)
</code>```

i could see that LinkHTMLAttributes do not have "fetchPriority" property.

```<code>interface LinkHTMLAttributes<T> extends HTMLAttributes<T> {
        as?: string | undefined;
        crossOrigin?: string | undefined;
        href?: string | undefined;
        hrefLang?: string | undefined;
        integrity?: string | undefined;
        media?: string | undefined;
        imageSrcSet?: string | undefined;
        referrerPolicy?: HTMLAttributeReferrerPolicy | undefined;
        rel?: string | undefined;
        sizes?: string | undefined;
        type?: string | undefined;
        charSet?: string | undefined;
    }
</code>```

could some one please let me know how to resolve this ?

Thanks!!

Body:
I am trying to add "fetchPriority" to link tag as below.

const optionalPreload =
    ServerOnlyHead  ? (
      <ServerOnlyHead
        children={
          <link
            fetchPriority="high" // error here !!!
            rel="preload"
            as="image"
            href={image?.src || ""}
          />
        }
      />
    ) : null;

but it throws following error,

Type '{ fetchPriority: string; rel: string; as: string; href: string; }' is not assignable to type 'DetailedHTMLProps<LinkHTMLAttributes<HTMLLinkElement>, HTMLLinkElement>'.
  Property 'fetchPriority' does not exist on type 'DetailedHTMLProps<LinkHTMLAttributes<HTMLLinkElement>, HTMLLinkElement>'.ts(2322)
'fetchPriority' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.ts(7022)

i could see that LinkHTMLAttributes do not have "fetchPriority" property.

interface LinkHTMLAttributes<T> extends HTMLAttributes<T> {
        as?: string | undefined;
        crossOrigin?: string | undefined;
        href?: string | undefined;
        hrefLang?: string | undefined;
        integrity?: string | undefined;
        media?: string | undefined;
        imageSrcSet?: string | undefined;
        referrerPolicy?: HTMLAttributeReferrerPolicy | undefined;
        rel?: string | undefined;
        sizes?: string | undefined;
        type?: string | undefined;
        charSet?: string | undefined;
    }

could some one please let me know how to resolve this ?

Thanks!!


问:
How to make a public EC2 IP to be allocated in an AWS Local Zone?
I have enabled a Local Zone (us-east-1-nyc-1a) in my region (us-east-1), then deployed an EC2 instance into that Local Zone. The public IP that was allocated to my instance, indicates it is geo-located in the parent region (N.Virginia), while I would expect it to be in the Local Zone (NY/NJ).

My CloudFormation template configuration:

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  VpcId:
    Type: AWS::EC2::VPC::Id
Resources:
  Ec2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-0b0dcb5067f052a63
      InstanceType: t3.medium
      SubnetId: !Ref Ec2Subnet
      SecurityGroupIds:
        - !GetAtt WebSecurityGroup.GroupId
  Ec2Subnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VpcId
      CidrBlock: 172.31.96.0/24
      AvailabilityZone: us-east-1-nyc-1a
      MapPublicIpOnLaunch: true
  WebSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
```

I also tried allocating EIP in the Local Zone (and assigning it to the EC2 instance), but it also being geo-located in the parent region.

Will appreciate your suggestions.

Body:
I have enabled a Local Zone (us-east-1-nyc-1a) in my region (us-east-1), then deployed an EC2 instance into that Local Zone. The public IP that was allocated to my instance, indicates it is geo-located in the parent region (N.Virginia), while I would expect it to be in the Local Zone (NY/NJ).

My CloudFormation template configuration:

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  VpcId:
    Type: AWS::EC2::VPC::Id
Resources:
  Ec2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-0b0dcb5067f052a63
      InstanceType: t3.medium
      SubnetId: !Ref Ec2Subnet
      SecurityGroupIds:
        - !GetAtt WebSecurityGroup.GroupId
  Ec2Subnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VpcId
      CidrBlock: 172.31.96.0/24
      AvailabilityZone: us-east-1-nyc-1a
      MapPublicIpOnLaunch: true
  WebSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0

I also tried allocating EIP in the Local Zone (and assigning it to the EC2 instance), but it also being geo-located in the parent region.

Will appreciate your suggestions.


问:
Problem using rsync and relative paths in GitHub Actions
I have a GitHub Actions workflow job that seems like a simple thing, but one that I'm really struggling to implement.

Essentially I want to use rsync to copy several files from the checkout repository to another existing folder in the checkout repository. Here is a snippet of my action:

```<code> steps:
  - name: Checkout
    uses: actions/checkout@v3
    with:
      token: ${{ secrets.token }}
      fetch-depth: '0'

  - name: Rsync Test Files
    working-directory: ./tests/amazon-linux-2/integration-test
    run: |
      rsync -av ../../../ . --exclude tests --exclude .github --exclude .releaserc --exclude README.md --exclude .git
</code>```

There are several files and folders in the root of the checkout repo that I want to copy to ./tests/amazon-linux-2/integration-test. For info, tests is a folder in the project root.

The error I'm getting from the Rsync Test Files step is:

```<code>OCI runtime exec failed: exec failed: unable to start container process: chdir to cwd ("/__w/<repo name>/<repo name>/./tests/amazon-linux-2/integration-test") set in config.json failed: no such file or directory: unknown
</code>```

Two things confuse me that may or may not be related to the problem. There is an additional . between  and tests. Also, the repo name is appearing twice in the path.

I have tried setting the working directory of the Rsync Test Files tasks in multiple places and tweking the rsync command accordingly, but nothing works, with variations of the same error.

Body:
I have a GitHub Actions workflow job that seems like a simple thing, but one that I'm really struggling to implement.

Essentially I want to use rsync to copy several files from the checkout repository to another existing folder in the checkout repository. Here is a snippet of my action:

 steps:
  - name: Checkout
    uses: actions/checkout@v3
    with:
      token: ${{ secrets.token }}
      fetch-depth: '0'

  - name: Rsync Test Files
    working-directory: ./tests/amazon-linux-2/integration-test
    run: |
      rsync -av ../../../ . --exclude tests --exclude .github --exclude .releaserc --exclude README.md --exclude .git

There are several files and folders in the root of the checkout repo that I want to copy to ./tests/amazon-linux-2/integration-test. For info, tests is a folder in the project root.

The error I'm getting from the Rsync Test Files step is:

OCI runtime exec failed: exec failed: unable to start container process: chdir to cwd ("/__w/<repo name>/<repo name>/./tests/amazon-linux-2/integration-test") set in config.json failed: no such file or directory: unknown

Two things confuse me that may or may not be related to the problem. There is an additional . between  and tests. Also, the repo name is appearing twice in the path.

I have tried setting the working directory of the Rsync Test Files tasks in multiple places and tweking the rsync command accordingly, but nothing works, with variations of the same error.