问:
Nhibernate sum/groupby question
```<code>CREATE TABLE [dbo].[OrderHistory](
    [RecordID] [int] IDENTITY(1,1) NOT NULL,
    [UserID] [int] NOT NULL, /* FK to user table*/
    [ItemID] [int] NOT NULL, /* FK to Item table */
    [PurchaseDate] [datetime] NOT NULL,
    [UnitPrice] [money] NOT NULL,
    [Quantity] [float] NOT NULL,
PRIMARY KEY CLUSTERED
(
    [RecordID] ASC
) ON [PRIMARY]
</code>```

I have a table to save order history of users. I need to calculate total money spent by a user on yearly basis. If I write SQL query directly, it is very simple and straightforward:

```<code>select SUM(UnitPrice * Quantity) as TotalAmount, DATEPART(yyyy, PurchaseDate)
from OrderHistory
where UserId = 1
group by DATEPART(yyyy, PurchaseDate)
</code>```

Planned object model is:

```<code>public class YearlySummary {
        public virtual int Year {
            get;
            set;
        }

        public virtual decimal TotalSpent {
            get;
            set;
        }
    }
</code>```

But how can I do it in Nhibernate?

Thanks
Hardy

答:
If you only have to fetch the (historic) data it's quite easy actually. Use a formula in your mapping file:

```<code><property name="TotalSpent" formula="UnitPrice * Quantity" type="Decimal" />
</code>```

This will multiply the two values in the query (e.g. select UnitPrice * Quantity from OrderHistory) and put the result in the TotalSpent property. Note that this won't work for transient objects until you persist the data.

ContentLicense: CC BY-SA 2.5

Title: Nhibernate sum/groupby question

Body:
CREATE TABLE [dbo].[OrderHistory](
    [RecordID] [int] IDENTITY(1,1) NOT NULL,
    [UserID] [int] NOT NULL, /* FK to user table*/
    [ItemID] [int] NOT NULL, /* FK to Item table */
    [PurchaseDate] [datetime] NOT NULL,
    [UnitPrice] [money] NOT NULL,
    [Quantity] [float] NOT NULL,
PRIMARY KEY CLUSTERED
(
    [RecordID] ASC
) ON [PRIMARY]

I have a table to save order history of users. I need to calculate total money spent by a user on yearly basis. If I write SQL query directly, it is very simple and straightforward:

select SUM(UnitPrice * Quantity) as TotalAmount, DATEPART(yyyy, PurchaseDate)
from OrderHistory
where UserId = 1
group by DATEPART(yyyy, PurchaseDate)

Planned object model is:

public class YearlySummary {
        public virtual int Year {
            get;
            set;
        }

        public virtual decimal TotalSpent {
            get;
            set;
        }
    }

But how can I do it in Nhibernate?

Thanks
Hardy

Body:
If you only have to fetch the (historic) data it's quite easy actually. Use a formula in your mapping file:

<property name="TotalSpent" formula="UnitPrice * Quantity" type="Decimal" />

This will multiply the two values in the query (e.g. select UnitPrice * Quantity from OrderHistory) and put the result in the TotalSpent property. Note that this won't work for transient objects until you persist the data.


来源: stackexchange

问:
How to perform a MIN value Grouped By Date Measure in PowerBI?
I have a measure called PERC that basically spits out a percentage.  I am now creating a measure that I can place in the "Y-Axis Start" function for a trend line.  I need this new measure to calculate the MIN of PERC grouped by [MonthYear] (a column in my data).  How do I perform this? I have tried using the GROUPBY function but keep getting errors no matter how much I play with MIN, MINA and MINX...

My brain wants to do this:

```<code>CALCULATE(
    MIN([PERC], "*Grouped By*"('Data'[MonthYear])
    )
</code>```

Thank you in advance.  I'll be happy to answer any follow up questions for more context.

答:
Try

```<code>MinPERCbyMonthYear :=
VAR MyTable =
    SUMMARIZE ( Table1, Table1[MonthYear], "PERCbyMonthYear", [PERC] )
RETURN
    MINX ( MyTable, [PERCbyMonthYear] )
</code>```

replacing Table1 as required.

ContentLicense: CC BY-SA 4.0

Body:
I have a measure called PERC that basically spits out a percentage.  I am now creating a measure that I can place in the "Y-Axis Start" function for a trend line.  I need this new measure to calculate the MIN of PERC grouped by [MonthYear] (a column in my data).  How do I perform this? I have tried using the GROUPBY function but keep getting errors no matter how much I play with MIN, MINA and MINX...

My brain wants to do this:

CALCULATE(
    MIN([PERC], "*Grouped By*"('Data'[MonthYear])
    )

Thank you in advance.  I'll be happy to answer any follow up questions for more context.

Body:
Try

MinPERCbyMonthYear :=
VAR MyTable =
    SUMMARIZE ( Table1, Table1[MonthYear], "PERCbyMonthYear", [PERC] )
RETURN
    MINX ( MyTable, [PERCbyMonthYear] )

replacing Table1 as required.


问:
How to resolve NaN:NaN:NaN error in Mozilla Firefox
I'm currently working on below code, trying to retrieve last success and last failure dates from Jenkins. It works fine on chrome for both the dates but gives NaN error in firefox for last success date.

```<code>$.ajax({
                                                    type : "get",
                                                    url : 'getJobsSuccessdetails?jobname='+jobname,
                                                    data:{"username": $('#userName').val()},
                                                    contentType : "application/json; charset=utf-8",
                                                    traditional : true,
                                                    cache : false,
                                                    success : function(response) {
                                                        console.log("SUCCESS resposne = "+JSON.stringify(response));
                                                        var unixts = response[0].timestamp;
                                                        var date = new Date(unixts);
                                                        console.log("data.getDate() = "+date.getDate())

                                                        var sDate = ("0" + date.getDate()).slice(-2) + '/' + ("0" + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' - ' + date.getUTCHours() + ':' + date.getUTCMinutes();

                                                        console.log("data.getDate() = "+sDate);
</code>```

Expected result:
Last Success ----> 07/01/2020 - 9:27

Result:
Last Success ----> an/an/Nan - Nan:Nan

Can anyone please help me with the code to resolve this issue?

答:
Declaring the date as a date object and placing a space on both sides of the minus sign got this to work for me:</p>
```<code>var date = new Date();

var sDate = ("0" + date.getDate()).slice(-2) + "/" +
            ("0" + (date.getDate() + 1)).slice(-2) + "/" +
            date.getFullYear() + " - " +
            date.getUTCHours() + ":" + date.getUTCMinutes();

console.log(sDate); // Last Success --> 08/09/2022 - 5:59
</code>```

Body:
I'm currently working on below code, trying to retrieve last success and last failure dates from Jenkins. It works fine on chrome for both the dates but gives NaN error in firefox for last success date.

$.ajax({
                                                    type : "get",
                                                    url : 'getJobsSuccessdetails?jobname='+jobname,
                                                    data:{"username": $('#userName').val()},
                                                    contentType : "application/json; charset=utf-8",
                                                    traditional : true,
                                                    cache : false,
                                                    success : function(response) {
                                                        console.log("SUCCESS resposne = "+JSON.stringify(response));
                                                        var unixts = response[0].timestamp;
                                                        var date = new Date(unixts);
                                                        console.log("data.getDate() = "+date.getDate())

                                                        var sDate = ("0" + date.getDate()).slice(-2) + '/' + ("0" + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' - ' + date.getUTCHours() + ':' + date.getUTCMinutes();

                                                        console.log("data.getDate() = "+sDate);

Expected result:
Last Success ----> 07/01/2020 - 9:27

Result:
Last Success ----> an/an/Nan - Nan:Nan

Can anyone please help me with the code to resolve this issue?

Body:
Declaring the date as a date object and placing a space on both sides of the minus sign got this to work for me:

var date = new Date();

var sDate = ("0" + date.getDate()).slice(-2) + "/" +
            ("0" + (date.getDate() + 1)).slice(-2) + "/" +
            date.getFullYear() + " - " +
            date.getUTCHours() + ":" + date.getUTCMinutes();

console.log(sDate); // Last Success --> 08/09/2022 - 5:59


问:
How save a entire text file to a array and display in textbox
```<code>string[] readText = File.ReadAllLines(path);
foreach (string s in readText)
{
     textBox1.Text = string.Join(",",s);
}
</code>```

This is what is in the text file:

10,

1,2,3,4,5,

6,76,81,9

in the text box in visual studio it only displays the last line, i am trying to make it display everything

答:
First lets understand with your current approach why only the last line is displayed in the textBox1?

You are iterating over each line and assigning the same to textBox1.Text. You are not storing previous lines any where, so in every iteration previous data get replaced with new line data.

```<code>foreach (string s in readText)
{
    textBox1.Text = string.Join(",",s);  //Assigning new data everytime.
}
</code>```

This is the reason, after the execution foreach loop, only last line data is displayed.

Solution:

Now lets see how can we fix it,

Instead of assigning each line to textBox1, store entire data into a StringBuilder object and finally assign it to textBox1.

```<code>string[] readText = File.ReadAllLines(path);
StringBuilder sb = new StringBuilder();
foreach (string s in readText)
{
   sb.AppendLine(string.Join(",",s));
}
textBox1.Text = sb.ToString();
</code>```

If the data is already comma separated in the text file then you just need to join each link by \n, we do not require string.Join(',', s) again inside foreach loop,

```<code>textBox1.Text = string.Join(@"\n", readText);
</code>```

Body:
string[] readText = File.ReadAllLines(path);
foreach (string s in readText)
{
     textBox1.Text = string.Join(",",s);
}

This is what is in the text file:

10,

1,2,3,4,5,

6,76,81,9

in the text box in visual studio it only displays the last line, i am trying to make it display everything

Body:
First lets understand with your current approach why only the last line is displayed in the textBox1?

You are iterating over each line and assigning the same to textBox1.Text. You are not storing previous lines any where, so in every iteration previous data get replaced with new line data.

foreach (string s in readText)
{
    textBox1.Text = string.Join(",",s);  //Assigning new data everytime.
}

This is the reason, after the execution foreach loop, only last line data is displayed.

Solution:

Now lets see how can we fix it,

Instead of assigning each line to textBox1, store entire data into a StringBuilder object and finally assign it to textBox1.

string[] readText = File.ReadAllLines(path);
StringBuilder sb = new StringBuilder();
foreach (string s in readText)
{
   sb.AppendLine(string.Join(",",s));
}
textBox1.Text = sb.ToString();

If the data is already comma separated in the text file then you just need to join each link by \n, we do not require string.Join(',', s) again inside foreach loop,

textBox1.Text = string.Join(@"\n", readText);


问:
How to count active javascript timeouts?
I am using Selenium to test a web app that uses Dojo, and it uses java script to display certain elements. I want to wait until all of the elements are desplayed before I try to manipulate the page, however I am having trouble.

I have started by waiting for the dojo inFlight variable to be 0, this says that all ajax has finished. This doesn't always work because it seems to do some things on a timeout afterwards.

I have also tried repeatedly looking for the element, but this isn't too nice, as perhaps there is some javascript later which will use this field in some way.

So basically I want a method (in firefox at least) to query the javascript waiting to run on a setTimeout (or setInterval) I could even cope with a way of wrapping the built in call through a function of my own just to keep track of this.

Any thoughts or suggestions appreciated!

答:
Whenever you call setTimeout of setInterval -- a timer id is returned.

Save that timer id in an array

Inside the function that you're calling on the timeout, pop that timer id off the array. Because we have to remove that id from the array as soon as the timer ends.

Any time you want to check the no. of active timers, just query the length of that array.

ContentLicense: CC BY-SA 3.0


问:
How do I align this flex grid more evenly?
I have a flex grid with 4 boxes under "Our Services". Site is located here:

My HTML and CSS code is on the site: https://cleanautoinfo.com/surechoice/#services

I am having a hard time formatting it for StackOverflow because the code is already reformatted and it keeps adding cleartext from the code into stackoverflow.

答:
ctrl+shift+i or F12 or inspect element tool on most browsers is a powerful tool to debug elements. If you inspect on the website itself there's a utility class for margin-top that's causing the misalignment. See picture below:

You can either remove mt-md-5 on that div or add the same utility class to your other div.


问:
Not getting the "Submit for verification" button for OAuth verification in GCP
I have created a Gmail/Calendar add-on in Google Apps Script and I want to publish it to the marketplace.

I am following the steps at https://developers.google.com/workspace/marketplace/configure-oauth-consent-screen#fill_out_the_oauth_consent_screen. I am on the "Submit for OAuth verification" step which leads to https://support.google.com/cloud/answer/9110914#submit-howto. It says:

Click the Edit App button.

Enter the information required on the configuration page, and then click Submit for verification. If the submit for verification button does not appear at the end of the configuration pages, save what you have completed and repeat steps 1-4.

I have gone through all the steps but the Submit for verification never comes up. I'm not sure what I am doing wrong?

答:
Your first problem is that you do not have a domain name that you own/control. gmail.com and github.com are not owned by you.

Verify your site ownership

Your second problem is that you are requesting restricted scopes. Google will probably demand a security audit. Sensitive scopes can also trigger an audit.

To verify, create another client and remove the sensitive and restricted scopes and add a domain name that you own/control. To read more about the effect of scopes and possible exceptions:

Sensitive and Restricted Scopes


问:
I Want to load image from json in my assest as a string and then pass it to an imageview. How to do it?
I Want to load image from json in my assest as a string  and then pass it  to an imageview. How to do it?</p>

答:
Say your json is something like:

```<code>const book = {
id: 1,
title: "my title",
img:"/image/file.png",
...
}
...
</code>```

you may pass that object directly in your image tag:

eg.

```<code><img src="{book.img}" />
</code>```

Body:
Say your json is something like:

const book = {
id: 1,
title: "my title",
img:"/image/file.png",
...
}
...

you may pass that object directly in your image tag:

eg.

<img src="{book.img}" />


问:
Angular 6: How to change page background-color dynamically
I work on an Angular 6 app (with Bootstrap 4) and need to change the page background color depending on which page the user enters. Default is white, but for login and registration screen the page color needs to be blue.

What I found so far:

in ngAfterViewInit() using
this.elementRef.nativeElement.ownerDocument: this approach makes the
app more vulnerable to XSS attacks and I want to avoid that.

Set View Encapsulation to None in app.component.ts: this way I can
set the body color in the app.component, that is 1 step forward.

So, now I have in my app.component.css:

```<code>body {
  background-color: blue;
}
</code>```

Question:
How can I change that color value (in app.component) using a variable?

With [ngStyle] I can not reach the body background-color.

Maybe using a css variable? but how can I change the value of that css variable dynamically?

I'm new to Sass, but might this offer a solution?

My question is different from the other question on this subject as I need to be able tochange the color value dynamically.

答:
Personally i replace :

```<code><body>
<app-root></app-root>
</body>
</code>```

to

```<code><app-root></app-root>
</code>```

and then i add all the time the body on components or if i have multi
router-outlets i add it on app.component.css

Body:
I work on an Angular 6 app (with Bootstrap 4) and need to change the page background color depending on which page the user enters. Default is white, but for login and registration screen the page color needs to be blue.

What I found so far:

in ngAfterViewInit() using
this.elementRef.nativeElement.ownerDocument: this approach makes the
app more vulnerable to XSS attacks and I want to avoid that.

Set View Encapsulation to None in app.component.ts: this way I can
set the body color in the app.component, that is 1 step forward.

So, now I have in my app.component.css:

body {
  background-color: blue;
}

Question:
How can I change that color value (in app.component) using a variable?

With [ngStyle] I can not reach the body background-color.

Maybe using a css variable? but how can I change the value of that css variable dynamically?

I'm new to Sass, but might this offer a solution?

My question is different from the other question on this subject as I need to be able tochange the color value dynamically.

Body:
Personally i replace :

<body>
<app-root></app-root>
</body>

to

<app-root></app-root>

and then i add all the time the body on components or if i have multi
router-outlets i add it on app.component.css


问:
MongoDB - Aggregate with nested array not working
I have 2 collections using a simple nested array. An example of the records looks like so:

menus

```<code>{
    "_id" : ObjectId("620323fe80ec16abea7a0205"),
    "name" : "A new menu",
    "description" : "",
    "menuData" : [
        {
            "catName" : "Cat 2",
            "items" : [
                "61ded42461b1d8966c5efc45",
                "61ded55001e3cafb8db19198",
                "61df9adf2441b6113033f341",
                "61dfa8c82441b6113033f738"
            ]
        },
        {
            "catName" : "Cat 1",
            "items" : [
                "62020691adda4aab89f1742d",
                "61dfa8c82441b6113033f738"
            ]
        }
    ],
    "status" : "active",
}
</code>```

and I'm trying to complete a lookup on the menu items array (menuData.items). These are object IDs from another collection.

menuitems
One example is:

```<code>{
    "_id" : ObjectId("61ded55001e3cafb8db19198"),
    "name" : "Coca-Cola 600ml",
    "description" : "Refreshing taste...ahhh",
    "price" : 3.95,
    "tags" : [
        "drinks"
    ],
    "options" : [

    ],
    "status" : "active",
}
</code>```

Using the following aggregate, I do not get the output of the lookup

```<code>db.getCollection("menus").aggregate(
[
    {
        "$match" : {
            "_id" : ObjectId("620323fe80ec16abea7a0205")
        }
    },
    {
        "$addFields" : {
            "newField" : "$menuData.items"
        }
    },
    {
        "$unwind" : {
            "path" : "$newField"
        }
    },
    {
        "$lookup" : {
            "from" : "menuitems",
            "localField" : "newField",
            "foreignField" : "_id",
            "as" : "items"
        }
    }
]
);
</code>```

Output

```<code>{
    "_id" : ObjectId("620323fe80ec16abea7a0205"),
    "name" : "A new menu",
    "description" : "",
    "menuData" : [
        {
            "catName" : "Cat 2",
            "items" : [
                "61ded42461b1d8966c5efc45",
                "61ded55001e3cafb8db19198",
                "61df9adf2441b6113033f341",
                "61dfa8c82441b6113033f738"
            ]
        },
        {
            "catName" : "Cat 1",
            "items" : [
                "62020691adda4aab89f1742d",
                "61dfa8c82441b6113033f738"
            ]
        }
    ],
    "status" : "active",
    "createdBy" : ObjectId("61bb07c778e39ca45c161d81"),
    "createdByModel" : "Administrator",
    "createdAt" : ISODate("2022-02-09T02:16:30.108+0000"),
    "updatedAt" : ISODate("2022-02-09T04:26:00.837+0000"),
    "__v" : NumberInt(0),
    "newField" : [
        "61ded42461b1d8966c5efc45",
        "61ded55001e3cafb8db19198",
        "61df9adf2441b6113033f341",
        "61dfa8c82441b6113033f738"
    ],
    "items" : [

    ]
}
</code>```

As you can see, items are empty. I tried to complete this without $addFields and $unwind - with the same result.

Any help is greatly appreciated.

答:
You need $lookup with pipeline.

Converting ObjectId to string (newFields hold set of Id strings while menuItems document Id is an ObjectId)

Check the converted id string is within the newFields array via $in.

```<code>{
  "$lookup": {
    "from": "menuitems",
    let: {
      newField: "$newField"
    },
    pipeline: [
      {
        $match: {
          $expr: {
            $in: [
              {
                $toString: "$_id"
              },
              "$$newField"
            ]
          }
        }
      }
    ],
    "as": "items"
  }
}
</code>```

Sample Demo on Mongo Playground

Body:
I have 2 collections using a simple nested array. An example of the records looks like so:

menus

{
    "_id" : ObjectId("620323fe80ec16abea7a0205"),
    "name" : "A new menu",
    "description" : "",
    "menuData" : [
        {
            "catName" : "Cat 2",
            "items" : [
                "61ded42461b1d8966c5efc45",
                "61ded55001e3cafb8db19198",
                "61df9adf2441b6113033f341",
                "61dfa8c82441b6113033f738"
            ]
        },
        {
            "catName" : "Cat 1",
            "items" : [
                "62020691adda4aab89f1742d",
                "61dfa8c82441b6113033f738"
            ]
        }
    ],
    "status" : "active",
}

and I'm trying to complete a lookup on the menu items array (menuData.items). These are object IDs from another collection.

menuitems
One example is:

{
    "_id" : ObjectId("61ded55001e3cafb8db19198"),
    "name" : "Coca-Cola 600ml",
    "description" : "Refreshing taste...ahhh",
    "price" : 3.95,
    "tags" : [
        "drinks"
    ],
    "options" : [

    ],
    "status" : "active",
}

Using the following aggregate, I do not get the output of the lookup

db.getCollection("menus").aggregate(
[
    {
        "$match" : {
            "_id" : ObjectId("620323fe80ec16abea7a0205")
        }
    },
    {
        "$addFields" : {
            "newField" : "$menuData.items"
        }
    },
    {
        "$unwind" : {
            "path" : "$newField"
        }
    },
    {
        "$lookup" : {
            "from" : "menuitems",
            "localField" : "newField",
            "foreignField" : "_id",
            "as" : "items"
        }
    }
]
);

Output

{
    "_id" : ObjectId("620323fe80ec16abea7a0205"),
    "name" : "A new menu",
    "description" : "",
    "menuData" : [
        {
            "catName" : "Cat 2",
            "items" : [
                "61ded42461b1d8966c5efc45",
                "61ded55001e3cafb8db19198",
                "61df9adf2441b6113033f341",
                "61dfa8c82441b6113033f738"
            ]
        },
        {
            "catName" : "Cat 1",
            "items" : [
                "62020691adda4aab89f1742d",
                "61dfa8c82441b6113033f738"
            ]
        }
    ],
    "status" : "active",
    "createdBy" : ObjectId("61bb07c778e39ca45c161d81"),
    "createdByModel" : "Administrator",
    "createdAt" : ISODate("2022-02-09T02:16:30.108+0000"),
    "updatedAt" : ISODate("2022-02-09T04:26:00.837+0000"),
    "__v" : NumberInt(0),
    "newField" : [
        "61ded42461b1d8966c5efc45",
        "61ded55001e3cafb8db19198",
        "61df9adf2441b6113033f341",
        "61dfa8c82441b6113033f738"
    ],
    "items" : [

    ]
}

As you can see, items are empty. I tried to complete this without $addFields and $unwind - with the same result.

Any help is greatly appreciated.

Body:
You need $lookup with pipeline.

Converting ObjectId to string (newFields hold set of Id strings while menuItems document Id is an ObjectId)

Check the converted id string is within the newFields array via $in.

{
  "$lookup": {
    "from": "menuitems",
    let: {
      newField: "$newField"
    },
    pipeline: [
      {
        $match: {
          $expr: {
            $in: [
              {
                $toString: "$_id"
              },
              "$$newField"
            ]
          }
        }
      }
    ],
    "as": "items"
  }
}

Sample Demo on Mongo Playground


问:
Is dynamodb-geo supported in lambda running Node?
I'm trying to create a simple application following this article, but I cannot get my Node Lambda function to find the dynamodb-geo package.

Here is what I have:

```<code>const AWS = require('aws-sdk');
const ddbGeo = require('dynamodb-geo');

exports.handler = async (event, context) => {
  // Rest of the code here
};
</code>```

And the error Lambda throws is:

START RequestId: 5d40d132-040f-447d-bd76-35c4cec0236a Version: $LATEST
  2019-10-05T10:04:24.719Z  undefined   ERROR   Uncaught
  Exception {"errorType":"Runtime.ImportModuleError","errorMessage":"Error:
  Cannot find module
  'dynamodb-geo'","stack":["Runtime.ImportModuleError: Error: Cannot
  find module 'dynamodb-geo'","    at _loadUserApp
  (/var/runtime/UserFunction.js:100:13)","    at
  Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","

  at Object. (/var/runtime/index.js:45:30)","    at
  Module._compile (internal/modules/cjs/loader.js:778:30)","    at
  Object.Module._extensions..js
  (internal/modules/cjs/loader.js:789:10)","    at Module.load
  (internal/modules/cjs/loader.js:653:32)","    at tryModuleLoad
  (internal/modules/cjs/loader.js:593:12)","    at Function.Module._load
  (internal/modules/cjs/loader.js:585:3)","    at
  Function.Module.runMain (internal/modules/cjs/loader.js:831:12)","

  at startup (internal/bootstrap/node.js:283:19)"]} END RequestId:
  5d40d132-040f-447d-bd76-35c4cec0236a REPORT RequestId:
  5d40d132-040f-447d-bd76-35c4cec0236a  Duration: 1146.75 ms    Billed
  Duration: 1200 ms Memory Size: 512 MB Max Memory Used: 35 MB   Unknown
  application error occurred Runtime.ImportModuleError

Any clue on what could be happening?

答: You can use a Lambda layer in order to easily import external packages:</p>

Body:
I'm trying to create a simple application following this article, but I cannot get my Node Lambda function to find the dynamodb-geo package.

Here is what I have:

const AWS = require('aws-sdk');
const ddbGeo = require('dynamodb-geo');

exports.handler = async (event, context) => {
  // Rest of the code here
};

And the error Lambda throws is:

START RequestId: 5d40d132-040f-447d-bd76-35c4cec0236a Version: $LATEST
  2019-10-05T10:04:24.719Z  undefined   ERROR   Uncaught
  Exception {"errorType":"Runtime.ImportModuleError","errorMessage":"Error:
  Cannot find module
  'dynamodb-geo'","stack":["Runtime.ImportModuleError: Error: Cannot
  find module 'dynamodb-geo'","    at _loadUserApp
  (/var/runtime/UserFunction.js:100:13)","    at
  Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","

  at Object. (/var/runtime/index.js:45:30)","    at
  Module._compile (internal/modules/cjs/loader.js:778:30)","    at
  Object.Module._extensions..js
  (internal/modules/cjs/loader.js:789:10)","    at Module.load
  (internal/modules/cjs/loader.js:653:32)","    at tryModuleLoad
  (internal/modules/cjs/loader.js:593:12)","    at Function.Module._load
  (internal/modules/cjs/loader.js:585:3)","    at
  Function.Module.runMain (internal/modules/cjs/loader.js:831:12)","

  at startup (internal/bootstrap/node.js:283:19)"]} END RequestId:
  5d40d132-040f-447d-bd76-35c4cec0236a REPORT RequestId:
  5d40d132-040f-447d-bd76-35c4cec0236a  Duration: 1146.75 ms    Billed
  Duration: 1200 ms Memory Size: 512 MB Max Memory Used: 35 MB   Unknown
  application error occurred Runtime.ImportModuleError

Any clue on what could be happening?


问:
d3 5+ - Appending circles about a semi-circle or arc
Suppose we wanted to make a list-like visual. Setting the y logic for the circles can be as simple as:

```<code>var data = [0,1,2,3,4,5,6,7,8,9];

var yScale = d3.scaleLinear()
    .range([height,0])
    .domain([0,9]);

svg.selectAll(null)
    .data(data)
    .enter()
    .append('circle')
    .attr('cy', function(d) { return yScale(d) })
    .attr('cx', 100)
    .attr('r', 10)
    .style('fill', "#a6a6a6");
</code>```

However, suppose we wanted to go for some style points and arrange the circles not in a blocky / tabular arrangement but rather arrange them about a circle or arc. I had this result in mind (only concerned with the outer circles):

While I think d3 does have trigonometric functions, I have never seen them used in pixel coordinates. I'd imagine the pseudo-code to be something like:

```<code>var semiCircleScale = d3.?????
    .range([250 degrees, 110 degrees])
    .domain([0,9]);

svg.selectAll(null)
    .data(data)
    .enter()
    .append('circle')
    .attr('cy', function(d) { return semiCircleScale(d) })
    .attr('cx', 100)
    .attr('r', 10)
    .style('fill', "#a6a6a6");
</code>```

Question

Is anyone familiar with using circle / arc scales for use with x,y logic for appending shapes? Or is there an easier/less-math-intensive way?

答:
So the idea is to create 2 different path of arc and then calculate the circumference and place the circles along with.

```<code>d3.svg.arc()
.append("path")
.attr("d", arc1)
</code>```

Here is a fiddle link with minimum code to establish the idea
https://jsfiddle.net/Dibyanshu/g03p6sxj/

Body:
Suppose we wanted to make a list-like visual. Setting the y logic for the circles can be as simple as:

var data = [0,1,2,3,4,5,6,7,8,9];

var yScale = d3.scaleLinear()
    .range([height,0])
    .domain([0,9]);

svg.selectAll(null)
    .data(data)
    .enter()
    .append('circle')
    .attr('cy', function(d) { return yScale(d) })
    .attr('cx', 100)
    .attr('r', 10)
    .style('fill', "#a6a6a6");

However, suppose we wanted to go for some style points and arrange the circles not in a blocky / tabular arrangement but rather arrange them about a circle or arc. I had this result in mind (only concerned with the outer circles):

While I think d3 does have trigonometric functions, I have never seen them used in pixel coordinates. I'd imagine the pseudo-code to be something like:

var semiCircleScale = d3.?????
    .range([250 degrees, 110 degrees])
    .domain([0,9]);

svg.selectAll(null)
    .data(data)
    .enter()
    .append('circle')
    .attr('cy', function(d) { return semiCircleScale(d) })
    .attr('cx', 100)
    .attr('r', 10)
    .style('fill', "#a6a6a6");

Question

Is anyone familiar with using circle / arc scales for use with x,y logic for appending shapes? Or is there an easier/less-math-intensive way?

Body:
So the idea is to create 2 different path of arc and then calculate the circumference and place the circles along with.

d3.svg.arc()
.append("path")
.attr("d", arc1)

Here is a fiddle link with minimum code to establish the idea
https://jsfiddle.net/Dibyanshu/g03p6sxj/


问:
Is it allowed to use two generic T types (like T and TSource) in C# methods?
Is it allowed to use two generic T types (like T and TSource) in C# methods?</p>
```<code>public T GetResutls<T>(TSource sourceClass, string jsonString) where TSource : class
</code>```

答:
Yes, but you have to write both types between the angle brackets:</p>
```<code>    public TResult GetResults<TResult, TSource>(TSource source)
    {
       // TODO: Implement your code here
    }
</code>```

Body:
Is it allowed to use two generic T types (like T and TSource) in C# methods?

public T GetResutls<T>(TSource sourceClass, string jsonString) where TSource : class

Body:
Yes, but you have to write both types between the angle brackets:

    public TResult GetResults<TResult, TSource>(TSource source)
    {
       // TODO: Implement your code here
    }


问:
List View Threshold
I have a Sharepoint List that exceeded 5000 items limit today. After reading numerous suggestions, I:

indexed columns

Created a filtered default view that returns 3000 items.

Even though the default view now returns only 3000 items. In the List Settings Page I still see an error message saying "The number of items in this list exceeds the list view threshold, which is 5000 items. Tasks that cause excessive server load are currently prohibited. Could you please let me know what could be an issue and why filtering and indexing didn't help? Thank you!

答:
Please do the following troubleshooting:

1.Columns with column types like people, lookup, or managed metadata can cause list view threshold errors when sorting. Therefore, we recommend that you can use text, number, date, and other column types in the first sort.

2.Displaying 12 or more columns of the following types can cause a list view threshold error: people, lookup, and managed metadata. Displaying columns of other types will not.

3.Clear the browser cache or test with another browser.

Title: List View Threshold


问:
Chaining a new object instance in PHP
We have the following chaining:

```<code>$obj = new obj();
$obj->setname($params1)->setcolor($params2);
</code>```

Is there a way to do the same chaining on one line, without creating a dummy function?

P.S: I want to skip the part where the constructor itself is on a new line. I want to construct the object and start the chaining on the same line. Something like this:

```<code>$obj = new obj()->setname($params1)->setcolor($params2);
</code>```

答:
Should be possible if you allways return the object itself in the function.</p>

```<code>function setname($param) {
    // set the name etc..
    return $this;
}
</code>```

Title: Chaining a new object instance in PHP

Body:
We have the following chaining:

$obj = new obj();
$obj->setname($params1)->setcolor($params2);

Is there a way to do the same chaining on one line, without creating a dummy function?

P.S: I want to skip the part where the constructor itself is on a new line. I want to construct the object and start the chaining on the same line. Something like this:

$obj = new obj()->setname($params1)->setcolor($params2);

Body:
Should be possible if you allways return the object itself in the function.

function setname($param) {
    // set the name etc..
    return $this;
}


问:
Regex to exclude sub directory
I'm going an automatic global registration. I'm struggling to figure how to exclude a specific sub directory. How would a regex for that look? I'm sorry to not have an example of a try but I have no idea honestly. Searching I found a few examples but it never matches to exclude just a directory.

This is how I get the components now.

```<code>const registerComponents = () => {
  const pascalCase = (name: string) => {
    return _.chain(name).camelCase().upperFirst().value()
  }

  const context = require.context('@/components', true, /\w+\.(vue)$/)
  _.forEach(context.keys(), fileName => {
    const componentConfig = context(fileName)

    const name = (fileName.split('/').pop() || '').replace(/\.\w+$/, '')
    const componentName = pascalCase(name)

    Vue.component(componentName, componentConfig.default || componentConfig)
  })
}
</code>```

This is the structure. I would like to exclude the folder /_exclude/

```<code>components/_exclude/file.vue
components/_exclude/file2.vue
components/_exclude/svg/globe.vue
components/some-file.vue
components/svg/cart.vue
</code>```

答:
In your case, easy:

console.log( 'components/_exclude/file.vue'.replace(/\/_exclude\//,'/')  ); // <- RegEx
console.log( 'components/_exclude/file2.vue'.replace('/_exclude/','/') ); // <- String
console.log( 'components/_exclude/svg/globe.vue'.replace(/\/_exclude\//,'/') );
console.log( 'components/some-file.vue'.replace(/\/_exclude\//,'/') );
console.log( 'components/svg/cart.vue'.replace(/\/_exclude\//,'/') );

console.log( ' --- Or ---' );

console.log(
`components/_exclude/file.vue
components/_exclude/file2.vue
components/_exclude/svg/globe.vue
components/some-file.vue
components/svg/cart.vue`.replace(/\/_exclude\//g,'/') // <-- Using global flag (g) in case of more than one
);```
</div>
</div>
</p>
<p>Also for taking the component name, we can use <code>match</code> instead:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log( 'components/_exclude/file.vue'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );
console.log( 'components/folder/file.vue?query=notme.ext'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );
console.log( 'components/folder.name/file.vue'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );
console.log( 'components/folder/file.min.vue'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );</code>```

Update

General idea for take the pathInfo managed:

pathInfo function

function pathInfo(s) {
    s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
    return {folders:s[1],file:s[2],filename:s[3],fileext:s[4]};
}
var sample='folder/myfolder/excludeme/another/excludeme/onemore/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
  "folders": "folder/myfolder/excludeme/another/excludeme/onemore/",
  "file": "file.min.js",
  "filename": "file.min",
  "fileext": ".js"
}
*/
console.log(result.folders.split('/').filter(a=>a!='excludeme').join('/')+result.file);
// folder/myfolder/another/onemore/file.min.js```
</div>
</div>
</p>
<h4>pathInfo (+Folders list) function</h4>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function pathInfo(s) {
    s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
    return {path:s[1],folders:s[1].split('/'),file:s[2],filename:s[3],fileext:s[4]};
}
var sample='folder/myfolder/excludeme/another/excludeme/onemore/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
  "path": "folder/myfolder/excludeme/another/excludeme/onemore/",
  "folders": [
    "folder",
    "myfolder",
    "excludeme",
    "another",
    "excludeme",
    "onemore",
    ""
  ],
  "file": "file.min.js",
  "filename": "file.min",
  "fileext": ".js"
}
*/
console.log(result.folders.filter(a=>a!='excludeme').join('/')+result.file);
// folder/myfolder/another/onemore/file.min.js</code>```

Title: Regex to exclude sub directory

Body:
I'm going an automatic global registration. I'm struggling to figure how to exclude a specific sub directory. How would a regex for that look? I'm sorry to not have an example of a try but I have no idea honestly. Searching I found a few examples but it never matches to exclude just a directory.

This is how I get the components now.

const registerComponents = () => {
  const pascalCase = (name: string) => {
    return _.chain(name).camelCase().upperFirst().value()
  }

  const context = require.context('@/components', true, /\w+\.(vue)$/)
  _.forEach(context.keys(), fileName => {
    const componentConfig = context(fileName)

    const name = (fileName.split('/').pop() || '').replace(/\.\w+$/, '')
    const componentName = pascalCase(name)

    Vue.component(componentName, componentConfig.default || componentConfig)
  })
}

This is the structure. I would like to exclude the folder /_exclude/

components/_exclude/file.vue
components/_exclude/file2.vue
components/_exclude/svg/globe.vue
components/some-file.vue
components/svg/cart.vue

Body:
In your case, easy:

console.log( 'components/_exclude/file.vue'.replace(/\/_exclude\//,'/')  ); // <- RegEx
console.log( 'components/_exclude/file2.vue'.replace('/_exclude/','/') ); // <- String
console.log( 'components/_exclude/svg/globe.vue'.replace(/\/_exclude\//,'/') );
console.log( 'components/some-file.vue'.replace(/\/_exclude\//,'/') );
console.log( 'components/svg/cart.vue'.replace(/\/_exclude\//,'/') );

console.log( ' --- Or ---' );

console.log(
`components/_exclude/file.vue
components/_exclude/file2.vue
components/_exclude/svg/globe.vue
components/some-file.vue
components/svg/cart.vue`.replace(/\/_exclude\//g,'/') // <-- Using global flag (g) in case of more than one
);

Also for taking the component name, we can use match instead:

console.log( 'components/_exclude/file.vue'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );
console.log( 'components/folder/file.vue?query=notme.ext'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );
console.log( 'components/folder.name/file.vue'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );
console.log( 'components/folder/file.min.vue'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );

Update

General idea for take the pathInfo managed:

pathInfo function

function pathInfo(s) {
    s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
    return {folders:s[1],file:s[2],filename:s[3],fileext:s[4]};
}
var sample='folder/myfolder/excludeme/another/excludeme/onemore/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
  "folders": "folder/myfolder/excludeme/another/excludeme/onemore/",
  "file": "file.min.js",
  "filename": "file.min",
  "fileext": ".js"
}
*/
console.log(result.folders.split('/').filter(a=>a!='excludeme').join('/')+result.file);
// folder/myfolder/another/onemore/file.min.js

pathInfo (+Folders list) function

function pathInfo(s) {
    s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
    return {path:s[1],folders:s[1].split('/'),file:s[2],filename:s[3],fileext:s[4]};
}
var sample='folder/myfolder/excludeme/another/excludeme/onemore/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
  "path": "folder/myfolder/excludeme/another/excludeme/onemore/",
  "folders": [
    "folder",
    "myfolder",
    "excludeme",
    "another",
    "excludeme",
    "onemore",
    ""
  ],
  "file": "file.min.js",
  "filename": "file.min",
  "fileext": ".js"
}
*/
console.log(result.folders.filter(a=>a!='excludeme').join('/')+result.file);
// folder/myfolder/another/onemore/file.min.js


问:
How to trigger SwiftUI animation via change of non-State variable
It's easy to have an animation begin when a view appears, by using .onAppear(). But I'd like to perform a repeating animation whenever one of the view's non-State variables changes. An example:

Here is a view that I would like to "throb" whenever its throbbing parameter, set externally, is true:

```<code>struct MyCircle: View {
    var throbbing: Bool
    @State var scale = 1.0
    var body: some View {
        Circle()
            .frame(width: 100 * scale, height: 100 * scale)
            .foregroundColor(.blue)
            .animation(.easeInOut.repeatForever(), value: scale)
            .onAppear { scale = 1.2 }
    }
}
</code>```

Currently the code begins throbbing immediately, regardless of the throbbing variable.

But imagine this scenario:

```<code>struct ContentView: View {
    @State var throb: Bool = false
    var body: some View {
        VStack {
            Button("Throb: \(throb ? "ON" : "OFF")") { throb.toggle() }
            MyCircle(throbbing: throb)
        }
    }
}
</code>```

It looks like this:

Any ideas how I can modify MyCircle so that the throbbing starts when the button is tapped and ends when it is tapped again?

答:
You can use onChange to watch throbbing and then assign an animation. If true, add a repeating animation, and if false, just animate back to the original scale size:

```<code>struct MyCircle: View {
    var throbbing: Bool
    @State private var scale : CGFloat = 0
    var body: some View {
        Circle()
            .frame(width: 100, height: 100)
            .scaleEffect(1 + scale)
            .foregroundColor(.blue)
            .onChange(of: throbbing) { newValue in
                if newValue {
                    withAnimation(.easeInOut.repeatForever()) {
                        scale = 0.2
                    }
                } else {
                    withAnimation {
                        scale = 0
                    }
                }
            }
    }
}
</code>```

Body:
It's easy to have an animation begin when a view appears, by using .onAppear(). But I'd like to perform a repeating animation whenever one of the view's non-State variables changes. An example:

Here is a view that I would like to "throb" whenever its throbbing parameter, set externally, is true:

struct MyCircle: View {
    var throbbing: Bool
    @State var scale = 1.0
    var body: some View {
        Circle()
            .frame(width: 100 * scale, height: 100 * scale)
            .foregroundColor(.blue)
            .animation(.easeInOut.repeatForever(), value: scale)
            .onAppear { scale = 1.2 }
    }
}

Currently the code begins throbbing immediately, regardless of the throbbing variable.

But imagine this scenario:

struct ContentView: View {
    @State var throb: Bool = false
    var body: some View {
        VStack {
            Button("Throb: \(throb ? "ON" : "OFF")") { throb.toggle() }
            MyCircle(throbbing: throb)
        }
    }
}

It looks like this:

Any ideas how I can modify MyCircle so that the throbbing starts when the button is tapped and ends when it is tapped again?

Body:
You can use onChange to watch throbbing and then assign an animation. If true, add a repeating animation, and if false, just animate back to the original scale size:

struct MyCircle: View {
    var throbbing: Bool
    @State private var scale : CGFloat = 0
    var body: some View {
        Circle()
            .frame(width: 100, height: 100)
            .scaleEffect(1 + scale)
            .foregroundColor(.blue)
            .onChange(of: throbbing) { newValue in
                if newValue {
                    withAnimation(.easeInOut.repeatForever()) {
                        scale = 0.2
                    }
                } else {
                    withAnimation {
                        scale = 0
                    }
                }
            }
    }
}


问:
AWS STS session token expired api request not retrying after refresh method called and updated credentials in javaScript
I am using @Chime-sdk and @Angular-12 using AWS STS token, which one will expired after 15 minutes. After Expired STS token AWS call refresh method so I used refresh() method to call my back-end api for new token then I re-assign all credentials, till now it's working good.

But it can't retry last api or request after completed refresh method execution.
below attached my code:

```<code>this._aws.credentials.refresh = (() => {
      this.exampleApiService.getToken().toPromise()
        .then((response: any) => {
          this._aws.credentials.accessKeyId = response.accessKeyId;
          this._aws.credentials.secretAccessKey = response.secretAccessKey
          this._aws.credentials.sessionToken = response.sessionToken;
          this._aws.credentials.expireTime = response.expireTime;
          this._aws.credentials.expired = false;
          this.setChimeClient();

        }).catch(error => {
          console.log(error)
        });
    })
</code>```

So How can i retry or recall my last last api call or request ?

答:
After trying multiple way, I get solution that's was to easy.

Chime pass a callBack function to refresh function so after credential set if we call, callBack function then Chime re-initiate last API call or process.

if we fail to generate refresh or new token then we can pass error in callBack function as param. below added example code.

```<code>this._aws.credentials.refresh = ((callback) => {
      this.exampleApiService.getToken().toPromise()
        .then((response: any) => {
          this._aws.credentials.accessKeyId = response.accessKeyId;
          this._aws.credentials.secretAccessKey = response.secretAccessKey
          this._aws.credentials.sessionToken = response.sessionToken;
          this._aws.credentials.expireTime = response.expireTime;
          this._aws.credentials.expired = false;
          this.setChimeClient();
          callback();
        }).catch(error => {
          console.log(error)
        });
    })
</code>```

Body:
I am using @Chime-sdk and @Angular-12 using AWS STS token, which one will expired after 15 minutes. After Expired STS token AWS call refresh method so I used refresh() method to call my back-end api for new token then I re-assign all credentials, till now it's working good.

But it can't retry last api or request after completed refresh method execution.
below attached my code:

this._aws.credentials.refresh = (() => {
      this.exampleApiService.getToken().toPromise()
        .then((response: any) => {
          this._aws.credentials.accessKeyId = response.accessKeyId;
          this._aws.credentials.secretAccessKey = response.secretAccessKey
          this._aws.credentials.sessionToken = response.sessionToken;
          this._aws.credentials.expireTime = response.expireTime;
          this._aws.credentials.expired = false;
          this.setChimeClient();

        }).catch(error => {
          console.log(error)
        });
    })

So How can i retry or recall my last last api call or request ?

Body:
After trying multiple way, I get solution that's was to easy.

Chime pass a callBack function to refresh function so after credential set if we call, callBack function then Chime re-initiate last API call or process.

if we fail to generate refresh or new token then we can pass error in callBack function as param. below added example code.

this._aws.credentials.refresh = ((callback) => {
      this.exampleApiService.getToken().toPromise()
        .then((response: any) => {
          this._aws.credentials.accessKeyId = response.accessKeyId;
          this._aws.credentials.secretAccessKey = response.secretAccessKey
          this._aws.credentials.sessionToken = response.sessionToken;
          this._aws.credentials.expireTime = response.expireTime;
          this._aws.credentials.expired = false;
          this.setChimeClient();
          callback();
        }).catch(error => {
          console.log(error)
        });
    })


问:
R: Recode cells in matrix with no symmetric match
I have an adjacency matrix of 0s and 1s that indicate tie nominations. Some nominations are not reciprocated, so the matrix is asymmetrical.

I would like to recode the cell values from 1 to 0 if they do not have a symmetrical match.

Sample small matrix:

```<code>     [,1] [,2] [,3] [,4]
[1,]    0    1    0    1
[2,]    0    0    1    0
[3,]    0    0    0    1
[4,]    1    0    1    0
</code>```

Output desired:

```<code>     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    0    0
[3,]    0    0    0    1
[4,]    1    0    1    0
</code>```

答:
First the data, then a one-liner will do it. Treat 0/1 as logical and AND the matrix with its transpose. +() coerces to integer and the trick is done.

x <- scan(text="    0    1    0    1
    0    0    1    0
    0    0    0    1
    1    0    1    0")
x <- matrix(x, nrow = 4, byrow = TRUE)

y <- +(x & t(x))
y
#>      [,1] [,2] [,3] [,4]
#> [1,]    0    0    0    1
#> [2,]    0    0    0    0
#> [3,]    0    0    0    1
#> [4,]    1    0    1    0
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
I have an adjacency matrix of 0s and 1s that indicate tie nominations. Some nominations are not reciprocated, so the matrix is asymmetrical.

I would like to recode the cell values from 1 to 0 if they do not have a symmetrical match.

Sample small matrix:

     [,1] [,2] [,3] [,4]
[1,]    0    1    0    1
[2,]    0    0    1    0
[3,]    0    0    0    1
[4,]    1    0    1    0

Output desired:

     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    0    0
[3,]    0    0    0    1
[4,]    1    0    1    0

Body:
First the data, then a one-liner will do it. Treat 0/1 as logical and AND the matrix with its transpose. +() coerces to integer and the trick is done.

x <- scan(text="    0    1    0    1
    0    0    1    0
    0    0    0    1
    1    0    1    0")
x <- matrix(x, nrow = 4, byrow = TRUE)

y <- +(x & t(x))
y
#>      [,1] [,2] [,3] [,4]
#> [1,]    0    0    0    1
#> [2,]    0    0    0    0
#> [3,]    0    0    0    1
#> [4,]    1    0    1    0

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
Summary of all numeric variables with collapse R package
The summary of multiple variables may be obtained by applying fsummarise and across functions from collapse R package. For example:

```<code>library(collapse)
library(magrittr)
wlddev %>%
  fgroup_by(region, income) %>%
  fsummarise(across(PCGDP:GINI, fmean, w = POP))

                       region              income      PCGDP   LIFEEX     GINI
1         East Asia & Pacific         High income 29172.7552 76.83283 32.79182
2         East Asia & Pacific Lower middle income  1756.6480 64.25623 36.07647
3         East Asia & Pacific Upper middle income  2357.6168 68.40768 39.94810
4       Europe & Central Asia         High income 29335.5511 75.66616 32.25404
5       Europe & Central Asia          Low income   803.2234 62.45228 32.22326
6       Europe & Central Asia Lower middle income  2256.9684 68.48909 28.97857
7       Europe & Central Asia Upper middle income  7772.5035 68.01573 38.70512
8   Latin America & Caribbean         High income 10217.0626 73.04484 49.41109
9   Latin America & Caribbean          Low income  1317.9024 55.45075 41.10000
10  Latin America & Caribbean Lower middle income  1913.8993 63.86360 50.65115
11  Latin America & Caribbean Upper middle income  7564.8294 69.46947 52.90072
12 Middle East & North Africa         High income 25889.0715 72.38335 36.93006
13 Middle East & North Africa          Low income  1049.8255 63.62748 35.89218
14 Middle East & North Africa Lower middle income  2015.0739 65.55189 33.21199
15 Middle East & North Africa Upper middle income  4861.2074 66.74364 40.19273
16              North America         High income 37840.9568 75.54352 39.73948
17                 South Asia          Low income   471.7241 55.56794 37.24783
18                 South Asia Lower middle income   882.7061 60.19159 33.04111
19                 South Asia Upper middle income  1830.8876 70.30871 36.97996
20         Sub-Saharan Africa         High income  8253.2074 71.79170 39.18180
21         Sub-Saharan Africa          Low income   518.5847 52.03107 40.26600
22         Sub-Saharan Africa Lower middle income  1587.8770 52.07344 42.87172
23         Sub-Saharan Africa Upper middle income  6528.2845 58.35122 61.30462
</code>```

Wondering how to get summary of all numeric variables, something like this (only collapse solution due to high speed)

```<code>wlddev %>%
  fgroup_by(region, income) %>%
  fsummarise(across(num_vars(.), fmean, w = POP))

Error in cols2int(cols, d, nam) :
  cols must be a function, character vector, numeric indices or logical vector!
</code>```

Any hints, please.

答:
I am not sure if you are looking for this.</p>
```<code>library(collapse)
library(magrittr)
wlddev %>%
  fgroup_by(region, income) %>%
  fsummarise(across(is.numeric, fmean, w = POP))
</code>```

Body:
The summary of multiple variables may be obtained by applying fsummarise and across functions from collapse R package. For example:

library(collapse)
library(magrittr)
wlddev %>%
  fgroup_by(region, income) %>%
  fsummarise(across(PCGDP:GINI, fmean, w = POP))

                       region              income      PCGDP   LIFEEX     GINI
1         East Asia & Pacific         High income 29172.7552 76.83283 32.79182
2         East Asia & Pacific Lower middle income  1756.6480 64.25623 36.07647
3         East Asia & Pacific Upper middle income  2357.6168 68.40768 39.94810
4       Europe & Central Asia         High income 29335.5511 75.66616 32.25404
5       Europe & Central Asia          Low income   803.2234 62.45228 32.22326
6       Europe & Central Asia Lower middle income  2256.9684 68.48909 28.97857
7       Europe & Central Asia Upper middle income  7772.5035 68.01573 38.70512
8   Latin America & Caribbean         High income 10217.0626 73.04484 49.41109
9   Latin America & Caribbean          Low income  1317.9024 55.45075 41.10000
10  Latin America & Caribbean Lower middle income  1913.8993 63.86360 50.65115
11  Latin America & Caribbean Upper middle income  7564.8294 69.46947 52.90072
12 Middle East & North Africa         High income 25889.0715 72.38335 36.93006
13 Middle East & North Africa          Low income  1049.8255 63.62748 35.89218
14 Middle East & North Africa Lower middle income  2015.0739 65.55189 33.21199
15 Middle East & North Africa Upper middle income  4861.2074 66.74364 40.19273
16              North America         High income 37840.9568 75.54352 39.73948
17                 South Asia          Low income   471.7241 55.56794 37.24783
18                 South Asia Lower middle income   882.7061 60.19159 33.04111
19                 South Asia Upper middle income  1830.8876 70.30871 36.97996
20         Sub-Saharan Africa         High income  8253.2074 71.79170 39.18180
21         Sub-Saharan Africa          Low income   518.5847 52.03107 40.26600
22         Sub-Saharan Africa Lower middle income  1587.8770 52.07344 42.87172
23         Sub-Saharan Africa Upper middle income  6528.2845 58.35122 61.30462

Wondering how to get summary of all numeric variables, something like this (only collapse solution due to high speed)

wlddev %>%
  fgroup_by(region, income) %>%
  fsummarise(across(num_vars(.), fmean, w = POP))

Error in cols2int(cols, d, nam) :
  cols must be a function, character vector, numeric indices or logical vector!

Any hints, please.

Body:
I am not sure if you are looking for this.

library(collapse)
library(magrittr)
wlddev %>%
  fgroup_by(region, income) %>%
  fsummarise(across(is.numeric, fmean, w = POP))


问:
"No appropriate default constructor available" error in Visual C++
I don't get it. I've been staring at the code the code for three hours and I can't see the problem.

The class I'm creating, called TwoDayPackage is derived from a class called Package.

This is how I defined the constructor:

```<code>    TwoDayPackage(string, string, string, string, int, string, string, string, string, int, float, float, float);
</code>```

This is how I implement the constructor:

```<code>TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
{
Package::Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, weight, cost);
flatRate = flat;
}
</code>```

This is how i use it in my main function.

```<code>TwoDayPackage pack2(senderName, senderAddress, senderState, senderCountry, senderZIP, receipientName, receipientAddress, receipientState, receipientCountry, receipientZIP, weight, cost, flat);
</code>```

I know my argument list is pretty long, there's a reason for that.
Thanks.

答:
Should use:</p>

```<code>TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string  sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
 :Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, weight, cost)
  {
    flatRate = flat;
   }
</code>```

OwnerDisplayName: chustar

Body:
I don't get it. I've been staring at the code the code for three hours and I can't see the problem.

The class I'm creating, called TwoDayPackage is derived from a class called Package.

This is how I defined the constructor:

    TwoDayPackage(string, string, string, string, int, string, string, string, string, int, float, float, float);

This is how I implement the constructor:

TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
{
Package::Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, weight, cost);
flatRate = flat;
}

This is how i use it in my main function.

TwoDayPackage pack2(senderName, senderAddress, senderState, senderCountry, senderZIP, receipientName, receipientAddress, receipientState, receipientCountry, receipientZIP, weight, cost, flat);

I know my argument list is pretty long, there's a reason for that.
Thanks.

Body:
Should use:

TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string  sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
 :Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, weight, cost)
  {
    flatRate = flat;
   }

OwnerDisplayName: dirkgently


问:
Global variables - accessing from View class
Having a bit of a problem. Unfortunately I'm at work (not home) so cannot show code.

Basically, I've got three class files - my main class, which at the moment is handling the touchscreen functionality - an act class, which is an extends View and is called by the main class (draws on the screen) - and a global class, which contains global variables, all the functions to set and retrieve them etc.

Now, I've got the global variables working okay after following some tutorials and forum answers. The file is declared in the manifest and, in the main class (which I think is an extends application) works fine (using all the getApplicationContext stuff).

However, I really need to get them to work in the act class (which is an extends View) but they're not. I gather this is obviously because this is an extends View which is something it doesn't seem I can do anything about.

Anyone got any ideas?

Thanks.

For replies (as I'm a newb so can't answer yet, and comments don't seem to want to work with IE6 - our IT dept sucks)

@David Olsson - thanks, will give that a go when I get in.

@Aioobe - heh, no, not really in much of a hurry. Should've posted last night. Normally it's the other way round, I'm at home, not work so can't show code...

And if you are at my home can you check on the dog?

答:
You could always use a method where you put the reference for the  global variables.
IE in your View class: </p>

```<code>private MyGlobalVariables myVariables;
public void setGlobalVariable(MyGlobalVariables variables) {
    myVariables = variables;
}
</code>```

<p>and then in your activity class I guess you have a reference to your View, if you don't just create one and use </p>

```<code>myView.setGlobalVariable(myVariables);
</code>```

Body:
You could always use a method where you put the reference for the  global variables.
IE in your View class:

private MyGlobalVariables myVariables;
public void setGlobalVariable(MyGlobalVariables variables) {
    myVariables = variables;
}

and then in your activity class I guess you have a reference to your View, if you don't just create one and use

myView.setGlobalVariable(myVariables);


问:
React Testing waiting for useDispatch and state change
I'm testing a component that I need to wait for a dispatch call to be made and then wait for the 'loading' state to change as well.

I'm using jest.mock to deliver the results of the dispatch however it appears as though the results aren't being delivered as far as I can tell...

My Post Detail Component:
useEffect(() => {

```<code>    const postDetail = async () => {

        await dispatch(postDetailView(postID))
        console.log('post Detail', postID)
        setLoading(false)
    }

    postDetail()

}, [dispatch])
</code>```

My Test Setup:

```<code>const mockDispatch = jest.fn();

jest.mock('react-redux', () => ({
    ...jest.requireActual('react-redux'),
    useDispatch: () => mockDispatch.mockReturnValueOnce({
        _id: '12345',
        title:'A New Post',
        description: 'A New Description'
    }) // Return a value since I'm expecting a value to be returned before I redirect
}))

describe('Post Detail', () => {

    it('Post Detail Get View', async () => {

        const result = await waitFor(() =>  render(
        <MemoryRouter initialEntries={['/detail/12345']}>
            <Provider store={store}>
                <Routes>
                    <Route path='/detail/:postID' exact element={<PostDetail/>} />
                </Routes>
            </Provider>
        </MemoryRouter>))

        // This produces and Error that title does not exist
        const postElementTitle = screen.getByText(/title/i)

        //This test passes
        expect(mockDispatch).toHaveBeenCalledTimes(1)

    })

})
</code>```

What I'm hoping would happen is the component would load in the waitFor block and call dispatch, get the results, but that does not seem to be happening, and oddly the dispatch call does get called successfully but the results don't seem to be making it to the component.

The Error results:

```<code> TestingLibraryElementError: Unable to find an element with the text: /title/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

    Ignored nodes: comments, <script />, <style />
    <body>
      <div>
        <div
          class="card"
        >
          <div
            class="row"
          >
            <div
              class="col"
            >
              <a
                href="/detail/undefined" // this is where the ID of the dispatch results should appear but it's coming up blank
              >
                <p /> //This is where title from the dispatch tests should be appearing but it's blank
              </a>
            </div>
            <div
              class="col"
            >
              <p />
            </div>
            <div
              class="col"
            >
              <button
                class="btn btn-outline-primary"
                type="button"
              >
                Update
              </button>
              <button
                class="btn btn-outline-danger"
                type="button"
              >
                Delete
              </button>
            </div>

          </div>
        </div>
      </div>
    </body>
</code>```

Versions I'm using:

```<code>"@reduxjs/toolkit": "^1.7.1",
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
"react": "^17.0.2",
"react-redux": "^7.2.6",
"react-router-dom": "^6.2.1",
"react-scripts": "5.0.0",
</code>```

To recap what's going on (I think) is that the dispatch element is getting called but the results are not getting read by the component itself.  I'm not sure how to remedy this or if anyone can see any glaring missteps on my part.  Thanks in advance.

答:
I figured out what I did wrong and that I also had an incorrect approach to testing a component itself.  Also I learned a lot about redux and how complicated it is to test but the learning was a good thing for me to figure out more ins and outs of redux.

TestingFile

```<code>const store = configureStore({
    reducer:{
        post: postReducer,
        alert: alertReducer
    }
})

const MockComponent = (props={}, history={}) => {
    return(
        <BrowserRouter>
            <Provider store={store}>
                <PostDetail/>
            </Provider>
        </BrowserRouter>)
}

const mockDispatch = jest.fn();
// const mockSelector = jest.fn()

jest.mock('react-redux', () => ({
    ...jest.requireActual('react-redux'),
    useDispatch: () => mockDispatch
    // useSelector: () => mockSelector.mockReturnValueOnce(true)
}))

// // mock useNavigate
describe('Post Detail', ()=>{

    it('post detail', async () => {

        render(MockComponent())

        // Use dispatch to update the store correctly
        store.dispatch(postSliceActions.postDetail({_id:1, title:'A new Post', description: 'A new Desc'}))

        // Check that dispatch was called within the component
        expect(mockDispatch).toHaveBeenCalledTimes(1)

        // Ensure the loading screen has time to go away
        await waitForElementToBeRemoved(() => screen.queryByText(/Loading/i))

        // Check for the post title in the component
        expect(screen.getByText(/a new post/i)).toBeInTheDocument()

        // screen.debug()

    })

})
</code>```

Also this article helped me as well, especially with the waiting for the element to be removed...https://kentcdodds.com/blog/fix-the-not-wrapped-in-act-warning

Thanks,

Body:
I'm testing a component that I need to wait for a dispatch call to be made and then wait for the 'loading' state to change as well.

I'm using jest.mock to deliver the results of the dispatch however it appears as though the results aren't being delivered as far as I can tell...

My Post Detail Component:
useEffect(() => {

    const postDetail = async () => {

        await dispatch(postDetailView(postID))
        console.log('post Detail', postID)
        setLoading(false)
    }

    postDetail()

}, [dispatch])

My Test Setup:

const mockDispatch = jest.fn();

jest.mock('react-redux', () => ({
    ...jest.requireActual('react-redux'),
    useDispatch: () => mockDispatch.mockReturnValueOnce({
        _id: '12345',
        title:'A New Post',
        description: 'A New Description'
    }) // Return a value since I'm expecting a value to be returned before I redirect
}))

describe('Post Detail', () => {

    it('Post Detail Get View', async () => {

        const result = await waitFor(() =>  render(
        <MemoryRouter initialEntries={['/detail/12345']}>
            <Provider store={store}>
                <Routes>
                    <Route path='/detail/:postID' exact element={<PostDetail/>} />
                </Routes>
            </Provider>
        </MemoryRouter>))

        // This produces and Error that title does not exist
        const postElementTitle = screen.getByText(/title/i)

        //This test passes
        expect(mockDispatch).toHaveBeenCalledTimes(1)

    })

})

What I'm hoping would happen is the component would load in the waitFor block and call dispatch, get the results, but that does not seem to be happening, and oddly the dispatch call does get called successfully but the results don't seem to be making it to the component.

The Error results:

 TestingLibraryElementError: Unable to find an element with the text: /title/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

    Ignored nodes: comments,

Body:
I figured out what I did wrong and that I also had an incorrect approach to testing a component itself.  Also I learned a lot about redux and how complicated it is to test but the learning was a good thing for me to figure out more ins and outs of redux.

TestingFile

const store = configureStore({
    reducer:{
        post: postReducer,
        alert: alertReducer
    }
})

const MockComponent = (props={}, history={}) => {
    return(
        <BrowserRouter>
            <Provider store={store}>
                <PostDetail/>
            </Provider>
        </BrowserRouter>)
}

const mockDispatch = jest.fn();
// const mockSelector = jest.fn()

jest.mock('react-redux', () => ({
    ...jest.requireActual('react-redux'),
    useDispatch: () => mockDispatch
    // useSelector: () => mockSelector.mockReturnValueOnce(true)
}))

// // mock useNavigate
describe('Post Detail', ()=>{

    it('post detail', async () => {

        render(MockComponent())

        // Use dispatch to update the store correctly
        store.dispatch(postSliceActions.postDetail({_id:1, title:'A new Post', description: 'A new Desc'}))

        // Check that dispatch was called within the component
        expect(mockDispatch).toHaveBeenCalledTimes(1)

        // Ensure the loading screen has time to go away
        await waitForElementToBeRemoved(() => screen.queryByText(/Loading/i))

        // Check for the post title in the component
        expect(screen.getByText(/a new post/i)).toBeInTheDocument()

        // screen.debug()

    })

})

Also this article helped me as well, especially with the waiting for the element to be removed...https://kentcdodds.com/blog/fix-the-not-wrapped-in-act-warning

Thanks,


问:
Turning a Binary Tree to a sorted array
Is there a way to turn a Binary to a sorted array without having to traverse the tree for every array index?

```<code>Node root;
Node runner;
int current_smallest;

void findsmallest(Node root){
    //Pre-order traversal
    if(root == null){
        return;
    }else{
        runner = root;
        if(current_smallest == null){
            current_smallest = runner.element;
        }else{
            if(current_smallest > runner.element){
            current_smallest = runner.element;
            }
        }
        findsmallest(runner.left);
        findsmallest(runner.right);
    }
}

void fill_array( int [] array ){

    for(int i =0; i < array.length(); i++){
        findsmallest(root);
        array[i] = current_smallest;
    }
}
</code>```

As you can see this can be take a long time if there are a lot of nodes in the tree.
Btw, I forgot to show that the whole tree would have to be traversed at the start to get the length of the array.

答:
```<code>Here is java code for same:

int[] result = new int[9];
fillArray(tree, result, 0);

public int fillArray(Tree tree, int[] result, int index) {
        if (tree.left != null) {
            index = fillArray(tree.left, result, index);
        }
        result[index++] = tree.val;

        if (tree.right != null) {
            index = fillArray(tree.right, result, index);
        }

   return index;
}
</code>```

Title: Turning a Binary Tree to a sorted array

Body:
Is there a way to turn a Binary to a sorted array without having to traverse the tree for every array index?

Node root;
Node runner;
int current_smallest;

void findsmallest(Node root){
    //Pre-order traversal
    if(root == null){
        return;
    }else{
        runner = root;
        if(current_smallest == null){
            current_smallest = runner.element;
        }else{
            if(current_smallest > runner.element){
            current_smallest = runner.element;
            }
        }
        findsmallest(runner.left);
        findsmallest(runner.right);
    }
}

void fill_array( int [] array ){

    for(int i =0; i < array.length(); i++){
        findsmallest(root);
        array[i] = current_smallest;
    }
}

As you can see this can be take a long time if there are a lot of nodes in the tree.
Btw, I forgot to show that the whole tree would have to be traversed at the start to get the length of the array.


问:
ERROR "MODULE NOT FOUND" on Typescript index.ts activation
i was building this discord bot using discord.js v13
and everytime i run my code (that i completly did not rip off from https://www.youtube.com/watch?v=JMmUW4d3Noc&t=614s)

Here is my code: Package.json

```<code>  "name": "Ceeby",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "discord.js": "^13.6.0",
    "dotenv": "^16.0.0"
  }
}
</code>```

Index.ts

```<code>  import DiscordJS, { Intents, Message } from 'discord.js'
import dotenv from 'dotenv'
dotenv.config()

const client = new DiscordJS.Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES,
    ]
})

client.on("ready", () => {
    console.log("Ceeby Is Active")
})

client.on('messageCreate', (Message) =>{
    if(Message.content === 'ping'){
        Message.reply({
            content: 'pong',
        })
    }
})

client.login(process.env.TOKEN)

</code>```

.ENV file

```<code>TOKEN=<THIS IS MY TOKEN HERE>
</code>```

i already tried doing it twice, restarting, reinstalling everything and still the same problem.
here is the error:
`Error: Cannot find module 'node:events'
Require stack:

C:\Users\Fady Mena\Desktop\Ceeby\node_modules\discord.js\src\client\BaseClient.js

C:\Users\Fady Mena\Desktop\Ceeby\node_modules\discord.js\src\index.js

C:\Users\Fady Mena\Desktop\Ceeby\index.ts
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:962:15)
at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (C:\Users\Fady Mena\AppData\Roaming\npm\node_modules\ts-node\node_modules@cspotcode\source-map-support\source-map-support.js:679:30)
at Function.Module._load (internal/modules/cjs/loader.js:838:27)
at Module.require (internal/modules/cjs/loader.js:1022:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object. (C:\Users\Fady Mena\Desktop\Ceeby\node_modules\discord.js\src\client\BaseClient.js:3:22)
at Module._compile (internal/modules/cjs/loader.js:1118:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1138:10)
at Module.load (internal/modules/cjs/loader.js:982:32)
at Function.Module._load (internal/modules/cjs/loader.js:875:14) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\Users\Fady Mena\Desktop\Ceeby\node_modules\discord.js\src\client\BaseClient.js',
'C:\Users\Fady Mena\Desktop\Ceeby\node_modules\discord.js\src\index.js',
'C:\Users\Fady Mena\Desktop\Ceeby\index.ts'
]
}
`

答:
Discord.js V13 requires a node version greater than 16.9.0 and you are running a version older than that as node:events was introduced in node V16+(Unsure which one exactly)
https://github.com/discordjs/discord.js

Body:
i was building this discord bot using discord.js v13
and everytime i run my code (that i completly did not rip off from https://www.youtube.com/watch?v=JMmUW4d3Noc&t=614s)

Here is my code: Package.json

  "name": "Ceeby",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "discord.js": "^13.6.0",
    "dotenv": "^16.0.0"
  }
}

Index.ts

  import DiscordJS, { Intents, Message } from 'discord.js'
import dotenv from 'dotenv'
dotenv.config()

const client = new DiscordJS.Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES,
    ]
})

client.on("ready", () => {
    console.log("Ceeby Is Active")
})

client.on('messageCreate', (Message) =>{
    if(Message.content === 'ping'){
        Message.reply({
            content: 'pong',
        })
    }
})

client.login(process.env.TOKEN)

.ENV file

TOKEN=<THIS IS MY TOKEN HERE>

i already tried doing it twice, restarting, reinstalling everything and still the same problem.
here is the error:
`Error: Cannot find module 'node:events'
Require stack:

C:\Users\Fady Mena\Desktop\Ceeby\node_modules\discord.js\src\client\BaseClient.js

C:\Users\Fady Mena\Desktop\Ceeby\node_modules\discord.js\src\index.js

C:\Users\Fady Mena\Desktop\Ceeby\index.ts
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:962:15)
at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (C:\Users\Fady Mena\AppData\Roaming\npm\node_modules\ts-node\node_modules@cspotcode\source-map-support\source-map-support.js:679:30)
at Function.Module._load (internal/modules/cjs/loader.js:838:27)
at Module.require (internal/modules/cjs/loader.js:1022:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object. (C:\Users\Fady Mena\Desktop\Ceeby\node_modules\discord.js\src\client\BaseClient.js:3:22)
at Module._compile (internal/modules/cjs/loader.js:1118:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1138:10)
at Module.load (internal/modules/cjs/loader.js:982:32)
at Function.Module._load (internal/modules/cjs/loader.js:875:14) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\Users\Fady Mena\Desktop\Ceeby\node_modules\discord.js\src\client\BaseClient.js',
'C:\Users\Fady Mena\Desktop\Ceeby\node_modules\discord.js\src\index.js',
'C:\Users\Fady Mena\Desktop\Ceeby\index.ts'
]
}
`


问:
Is there an event that is fired when a discord channel is renamed?
Can't find this anywhere, any help would be appreciated.

I have a really hacky method that works, but isn't efficient at all.

答:
The event fired is on_guild_channel_update. Note that this event also fires for updates like topic changes or permissions changes, not just renaming.

Example use:

@bot.event
async def on_guild_channel_update(before, after):
    if before.name != after.name:
        # This update renamed the channel.
        print(f"On guild {before.guild.name} channel {before.name} was updated to {after.name}")
```
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>On guild Achxy's server channel foo was updated to bar
</code>```

Read more:

class discord.abc.GuildChannel

Body:
The event fired is on_guild_channel_update. Note that this event also fires for updates like topic changes or permissions changes, not just renaming.

Example use:

@bot.event
async def on_guild_channel_update(before, after):
    if before.name != after.name:
        # This update renamed the channel.
        print(f"On guild {before.guild.name} channel {before.name} was updated to {after.name}")

Output:

On guild Achxy's server channel foo was updated to bar

Read more:

class discord.abc.GuildChannel


问:
No Entity Data Model (EDMX) Template with Visual Studio 2010 SP1 & ADO.NET Entity Framework 4.1
I'm having a lot of issues with the templates of Visual Studio 2010 SP1 & ADO.NET Entity Framework 4.1

I noticed that other people had these problems, and asked similar questions, but I don't think they gave enough information to make it solve-able.

The Problem: ADO.NET Entity Data Model Templates are not appearing whatsoever

Screenshot: http://c0848462.cdn.cloudfiles.rackspacecloud.com/f067439f6e8f25d5fd36761fd1efc88a74fd765ff1.png

Solution File

```<code>Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "localhost", "http://localhost:36626", "{9BA46BAD-E736-4943-ACAD-EDE2E7A1A21E}"
    ProjectSection(WebsiteProperties) = preProject
        UseIISExpress = "true"
        TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.0"
        Debug.AspNetCompiler.VirtualPath = "/localhost_36626"
        Debug.AspNetCompiler.PhysicalPath = "..\..\My Web Sites\Jantire\"
        Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_36626\"
        Debug.AspNetCompiler.Updateable = "true"
        Debug.AspNetCompiler.ForceOverwrite = "true"
        Debug.AspNetCompiler.FixedNames = "false"
        Debug.AspNetCompiler.Debug = "True"
        Release.AspNetCompiler.VirtualPath = "/localhost_36626"
        Release.AspNetCompiler.PhysicalPath = "..\..\My Web Sites\Jantire\"
        Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_36626\"
        Release.AspNetCompiler.Updateable = "true"
        Release.AspNetCompiler.ForceOverwrite = "true"
        Release.AspNetCompiler.FixedNames = "false"
        Release.AspNetCompiler.Debug = "False"
        SlnRelativePath = "..\..\My Web Sites\Jantire\"
    EndProjectSection
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {9BA46BAD-E736-4943-ACAD-EDE2E7A1A21E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {9BA46BAD-E736-4943-ACAD-EDE2E7A1A21E}.Debug|Any CPU.Build.0 = Debug|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
EndGlobal
</code>```

Relevant System Specs:

Visual Studio 2010 Professional SP1

ADO.NET Entity Data Model 4.1

ASP.NET MVC 3 Tools Update

Windows 7 x64 SP1

WebMatrix

I'm coding this using both WebMatrix and Visual Studio 2010 Professional SP1

答:
Open the install media for VS2010 and browse to ":\WCU\EFTools".
Her you will find two files:

ADONETEntityFrameworkTools_enu.msi

ADONETEntityFrameworkTools_enu.cab

Copy those files to a folder on your PC.

Create a log file in the folder - for instance with the name "Log.txt"

Open a cmd prompt (possibly run the cmd prompt as administrator) and navigate to the
folder with the msi and cap files.

Run this command:

ADONETEntityFrameworkTools_enu.msi USING_EXUIH=1 /log "Log.txt"

It will take a while to install so be patient.

The installation should now be visible in "Control Panel -> Installed Programs" as "Microsoft Visual Studio 2010 ADO.NET Entity Framework Tools".

The items template should be visible in Visual Studio when adding a new item to a project. (Add New Item->Data->ADO.NET Entity Data Model).

More info here: http://msdn.microsoft.com/en-us/library/ee225240.aspx

Body:
I'm having a lot of issues with the templates of Visual Studio 2010 SP1 & ADO.NET Entity Framework 4.1

I noticed that other people had these problems, and asked similar questions, but I don't think they gave enough information to make it solve-able.

The Problem: ADO.NET Entity Data Model Templates are not appearing whatsoever

Screenshot: http://c0848462.cdn.cloudfiles.rackspacecloud.com/f067439f6e8f25d5fd36761fd1efc88a74fd765ff1.png

Solution File

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "localhost", "http://localhost:36626", "{9BA46BAD-E736-4943-ACAD-EDE2E7A1A21E}"
    ProjectSection(WebsiteProperties) = preProject
        UseIISExpress = "true"
        TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.0"
        Debug.AspNetCompiler.VirtualPath = "/localhost_36626"
        Debug.AspNetCompiler.PhysicalPath = "..\..\My Web Sites\Jantire\"
        Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_36626\"
        Debug.AspNetCompiler.Updateable = "true"
        Debug.AspNetCompiler.ForceOverwrite = "true"
        Debug.AspNetCompiler.FixedNames = "false"
        Debug.AspNetCompiler.Debug = "True"
        Release.AspNetCompiler.VirtualPath = "/localhost_36626"
        Release.AspNetCompiler.PhysicalPath = "..\..\My Web Sites\Jantire\"
        Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_36626\"
        Release.AspNetCompiler.Updateable = "true"
        Release.AspNetCompiler.ForceOverwrite = "true"
        Release.AspNetCompiler.FixedNames = "false"
        Release.AspNetCompiler.Debug = "False"
        SlnRelativePath = "..\..\My Web Sites\Jantire\"
    EndProjectSection
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {9BA46BAD-E736-4943-ACAD-EDE2E7A1A21E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {9BA46BAD-E736-4943-ACAD-EDE2E7A1A21E}.Debug|Any CPU.Build.0 = Debug|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
EndGlobal

Relevant System Specs:

Visual Studio 2010 Professional SP1

ADO.NET Entity Data Model 4.1

ASP.NET MVC 3 Tools Update

Windows 7 x64 SP1

WebMatrix

I'm coding this using both WebMatrix and Visual Studio 2010 Professional SP1


问:
Heroku worker dyno not showing up even though it is added in Procfile
I am trying to set up Heroku to host my Discord bot. I am sure that I have set up my Procfile correctly, but the worker dyno doesn't show up under Resources. Only the web dyno shows up and that doesn't work as it crashes with error R10 immediately after startup. Can someone help?

Procfile

```<code>worker: node index.js
</code>```

package.json

```<code>{
  "name": "bot name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "author",
  "license": "ISC",
  "dependencies": {
    "discord.js": "^12.2.0"
  }
}
</code>```

Log

```<code>2020-07-28T17:03:18.000000+00:00 app[api]: Build started by user
2020-07-28T17:03:42.000000+00:00 app[api]: Build succeeded
2020-07-28T16:58:24.618732+00:00 app[api]: Release v20 created by user
2020-07-28T16:58:24.897854+00:00 heroku[web.1]: State changed from crashed to starting
2020-07-28T16:58:27.754015+00:00 heroku[web.1]: Starting process with command `npm start`
2020-07-28T16:58:31.218171+00:00 app[web.1]:
2020-07-28T16:58:31.218205+00:00 app[web.1]: > bot@0.9.0 start /app
2020-07-28T16:58:31.218206+00:00 app[web.1]: > node index.js
2020-07-28T16:58:31.218206+00:00 app[web.1]:
2020-07-28T16:58:32.169174+00:00 app[web.1]: LOG> bot is now online!
2020-07-28T16:58:35.000000+00:00 app[api]: Build started by user
2020-07-28T16:58:58.755714+00:00 heroku[web.1]: State changed from starting to down
2020-07-28T16:58:58.660155+00:00 app[api]: Deploy 643b70ba by user
2020-07-28T16:58:58.660155+00:00 app[api]: Release v21 created by user
2020-07-28T16:58:59.000000+00:00 app[api]: Build succeeded
2020-07-28T16:59:28.079035+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2020-07-28T16:59:28.102556+00:00 heroku[web.1]: Stopping process with SIGKILL
2020-07-28T16:59:28.220163+00:00 heroku[web.1]: Process exited with status 137
</code>```

答:
Go to your heroku app

Select Resources menu

Turn on the "worker: node index.js" and turn off the "web npm start"

Body:
I am trying to set up Heroku to host my Discord bot. I am sure that I have set up my Procfile correctly, but the worker dyno doesn't show up under Resources. Only the web dyno shows up and that doesn't work as it crashes with error R10 immediately after startup. Can someone help?

Procfile

worker: node index.js

package.json

{
  "name": "bot name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "author",
  "license": "ISC",
  "dependencies": {
    "discord.js": "^12.2.0"
  }
}

Log

2020-07-28T17:03:18.000000+00:00 app[api]: Build started by user
2020-07-28T17:03:42.000000+00:00 app[api]: Build succeeded
2020-07-28T16:58:24.618732+00:00 app[api]: Release v20 created by user
2020-07-28T16:58:24.897854+00:00 heroku[web.1]: State changed from crashed to starting
2020-07-28T16:58:27.754015+00:00 heroku[web.1]: Starting process with command `npm start`
2020-07-28T16:58:31.218171+00:00 app[web.1]:
2020-07-28T16:58:31.218205+00:00 app[web.1]: > bot@0.9.0 start /app
2020-07-28T16:58:31.218206+00:00 app[web.1]: > node index.js
2020-07-28T16:58:31.218206+00:00 app[web.1]:
2020-07-28T16:58:32.169174+00:00 app[web.1]: LOG> bot is now online!
2020-07-28T16:58:35.000000+00:00 app[api]: Build started by user
2020-07-28T16:58:58.755714+00:00 heroku[web.1]: State changed from starting to down
2020-07-28T16:58:58.660155+00:00 app[api]: Deploy 643b70ba by user
2020-07-28T16:58:58.660155+00:00 app[api]: Release v21 created by user
2020-07-28T16:58:59.000000+00:00 app[api]: Build succeeded
2020-07-28T16:59:28.079035+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2020-07-28T16:59:28.102556+00:00 heroku[web.1]: Stopping process with SIGKILL
2020-07-28T16:59:28.220163+00:00 heroku[web.1]: Process exited with status 137


问:
Clone a google cloud VM
I have google cloud VM with Ubuntu installed along with various services and libraries. I need to make a similar bootable VM with the same OS and all the data, libraries etc in the already configured VM. How do I clone the VM with these requirements?

I tried to create an image from the already existing VM and could not SSH into it.

So I retraced my installations step by step trying to figure out which step is breaking the image.
I created an Ubuntu(18.04) VM and used that to create an image. The instance I created using the image did allow me to SSH into.

Next installed Ubuntu desktop and xorg server and created an image after that. Using that image, I created a new VM and tried to SSH into it.
But unfortunately, the SSH connection could not be established. So I think it is these installations that are causing the error if it is not some sort of system error.

Below are the exact commands I ran to install these after creating an Ubuntu(18.04) VM:

```<code> sudo passwd username
  sudo su -
  passwd
  apt update && apt upgrade -y
  adduser username root
  adduser username admin
  adduser username sudo

  apt-get install ubuntu-desktop -y
  apt-get install xserver-xorg-video-dummy

  nano /etc/X11/xorg.conf
</code>```

and pasted the following into the .conf file

```<code>Section "Device"
    Identifier  "Configured Video Device"
    Driver      "dummy"
  EndSection
  Section "Monitor"
    Identifier  "Configured Monitor"
    HorizSync 31.5-48.5
    VertRefresh 50-70
  EndSection
  Section "Screen"
    Identifier  "Default Screen"
    Monitor     "Configured Monitor"
    Device      "Configured Video Device"
    DefaultDepth 24
    SubSection "Display"
    Depth 24
    Modes "1600x900"
    EndSubSection
  EndSection
</code>```

After this state, I created the image using which I could not instantiate a VM that I could SSH into.

答:
Follow this process in order to create the image exactly as the one you have already set up and you know is working correctly. As you may already know, this is a custom image so they are available only to your Cloud project. You can create a custom image from boot disks and other images if you would like also. Then, use the custom image to create an instance.

I will also suggest you to give a look at this document which would give you a deeper knowledge on the task.

Regards,

Title: Clone a google cloud VM

Body:
I have google cloud VM with Ubuntu installed along with various services and libraries. I need to make a similar bootable VM with the same OS and all the data, libraries etc in the already configured VM. How do I clone the VM with these requirements?

I tried to create an image from the already existing VM and could not SSH into it.

So I retraced my installations step by step trying to figure out which step is breaking the image.
I created an Ubuntu(18.04) VM and used that to create an image. The instance I created using the image did allow me to SSH into.

Next installed Ubuntu desktop and xorg server and created an image after that. Using that image, I created a new VM and tried to SSH into it.
But unfortunately, the SSH connection could not be established. So I think it is these installations that are causing the error if it is not some sort of system error.

Below are the exact commands I ran to install these after creating an Ubuntu(18.04) VM:

 sudo passwd username
  sudo su -
  passwd
  apt update && apt upgrade -y
  adduser username root
  adduser username admin
  adduser username sudo

  apt-get install ubuntu-desktop -y
  apt-get install xserver-xorg-video-dummy

  nano /etc/X11/xorg.conf

and pasted the following into the .conf file

Section "Device"
    Identifier  "Configured Video Device"
    Driver      "dummy"
  EndSection
  Section "Monitor"
    Identifier  "Configured Monitor"
    HorizSync 31.5-48.5
    VertRefresh 50-70
  EndSection
  Section "Screen"
    Identifier  "Default Screen"
    Monitor     "Configured Monitor"
    Device      "Configured Video Device"
    DefaultDepth 24
    SubSection "Display"
    Depth 24
    Modes "1600x900"
    EndSubSection
  EndSection

After this state, I created the image using which I could not instantiate a VM that I could SSH into.


问:
Connector is not giving a straight line in Anylogic
Please, the connector "the tools that join two objects together" in my AnyLogic is not giving a straight line anymore.

Please, how can I solve this?

Please check the attached screenshot. Unlike every other connectionenter image description here in this flowchart, the connection between batch and sink is not straightenter image description here.

Please, help

答:
If you mean something like this:

Just double-click on the handle you don't like and it goes away. And here is the help on this and more.


问:
How to log sql script on try catch
I have a scenario  SaveChanges();  failed for two sql script ,is that possible to log sql script in catch method ?
EX add method :- _sqlDb.Deleted.Add(deleted);</p>
```<code>catch (DbOperationException ex)
               {
               //something here
               }
</code>```

答:
For a own written sql statement you could use a variable declared outside of try/catch</p>
```<code>string sql = string.Empty;
try
{
  // build your sql statement, ie:
  sql = "SELECT * FROM <table>";
  // execute statement
}
catch(Excepction ex)
{
  Console.WriteLine(ex.Message);
  Console.WriteLine(sql);
}
</code>```

Title: How to log sql script on try catch

Body:
I have a scenario  SaveChanges();  failed for two sql script ,is that possible to log sql script in catch method ?
EX add method :- _sqlDb.Deleted.Add(deleted);

catch (DbOperationException ex)
               {
               //something here
               }

Body:
For a own written sql statement you could use a variable declared outside of try/catch

string sql = string.Empty;
try
{
  // build your sql statement, ie:
  sql = "SELECT * FROM <table>";
  // execute statement
}
catch(Excepction ex)
{
  Console.WriteLine(ex.Message);
  Console.WriteLine(sql);
}


问:
Is there an equivalent of $` in Javascript's `replace()` for Python's re.sub()?
In JS, you can use

$`  Inserts the portion of the string that precedes the matched substring.

$'  Inserts the portion of the string that follows the matched substring.

To get the substring before and after the match.

Is there an equivalent of this in Python's re.sub()?

答:
Instead of a replacement string, you can pass a function to re.sub. The function will receive a match object, and should return the replacement for the match.

Within the function, you can use match.start() and match.end() to get the start and end indices of the match in the original string, and match.string to get the original string passed to re.sub. Thus,

```<code>match.string[:match.start()]
</code>```

gives the effect of $`, and

```<code>match.string[match.end():]
</code>```

gives the effect of $'.

Body:
Instead of a replacement string, you can pass a function to re.sub. The function will receive a match object, and should return the replacement for the match.

Within the function, you can use match.start() and match.end() to get the start and end indices of the match in the original string, and match.string to get the original string passed to re.sub. Thus,

match.string[:match.start()]

gives the effect of $`, and

match.string[match.end():]

gives the effect of $'.