问:
Could not delete /.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/appname/WEB-INF/lib. May be locked by another process
I am trying to run an web app. In the beginning it was going well, but I had to delete some jars from the project folder. I didn't delete the jars using eclipse. So, I started to get these errors:

```<code>Publishing failed with multiple errors
Could not delete C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF/lib. May be locked by another process.
Could not delete C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF. May be locked by another process.
</code>```

I tried to delete my whole project and code it again. But it doesn't work. I also deleted the Tomcat server but again it doesn't work. Then I realized that to "fix" this problem I have to delete this folder:

C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF.

And clean the server and the project. But when I close eclipse and open again I get the same error, then I have to do this process.

Anyone here knows how to fix this kind of tomcat bug?

答:
When you have multiple projects in the workspace, the run button will record the run history, so you should press the triangle button to select the correct run option.
For example, when I choose to run "AjaxAdms" directly, an error will be reported, but if I choose to "run tomcat on the localhost" option, no error will be reported.
Also, as shown in Figure 2 and 3, you should remove unnecessary projects from the Tomcat server.

Body:
I am trying to run an web app. In the beginning it was going well, but I had to delete some jars from the project folder. I didn't delete the jars using eclipse. So, I started to get these errors:

Publishing failed with multiple errors
Could not delete C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF/lib. May be locked by another process.
Could not delete C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF. May be locked by another process.

I tried to delete my whole project and code it again. But it doesn't work. I also deleted the Tomcat server but again it doesn't work. Then I realized that to "fix" this problem I have to delete this folder:

C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF.

And clean the server and the project. But when I close eclipse and open again I get the same error, then I have to do this process.

Anyone here knows how to fix this kind of tomcat bug?


来源: stackexchange

问:
How can I remove a certain value in a flatmap?
This is the flatmap:

```<code> const options = names.flatMap(
    (object) => object.name + " - " + object.size + "- " + object.category
  );
</code>```

console.log(options):

If the object.category is equals to S-XL how can I not display its values? But if the object.category  is equals too ft it will display the object.category ?Any help would be appreciated. Thank you

I'll be using the flatMap here:

```<code><Autocomplete
        disablePortal
        isOptionEqualToValue={(option, value) => option?.label === value?.label}
        id="combo-box-demo"
        options={options}
        fullWidth
        value={value}
        onChange={onChange}
        renderInput={(params) => <TextField {...params} label="Products" />}
        required
      />
</code>```

答:
```<code>  const options = names.flatMap(
      (object) =>
               object.name +
               " - " +
              object.size +
              `${object.category == "ft" ? "- " + object.category : ""}`
    );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is the flatmap:

 const options = names.flatMap(
    (object) => object.name + " - " + object.size + "- " + object.category
  );

console.log(options):

If the object.category is equals to S-XL how can I not display its values? But if the object.category  is equals too ft it will display the object.category ?Any help would be appreciated. Thank you

I'll be using the flatMap here:

<Autocomplete
        disablePortal
        isOptionEqualToValue={(option, value) => option?.label === value?.label}
        id="combo-box-demo"
        options={options}
        fullWidth
        value={value}
        onChange={onChange}
        renderInput={(params) => <TextField {...params} label="Products" />}
        required
      />


问:
Move RDS Aurora Instance from private to public subnet
I currently have the typical setup of an RDS cluster with 1 instance running in a private subnet. I am migrating our application out of AWS and into Heroku (while leaving the DB as is), but I need to be able to connect to the DB from the Heroku dynos.

What I can't figure out is how to move the DB out of the private subnet and into a public one.

The AWS docs have instructions for moving from public to private, and I thought I could just follow them for the opposite direction too. But the process involves standing up a new secondary in the desired subnet using Multi-AZ configuration and a failover. But when I go to Modify my instance, there is no option for configuring Multi-AZ:

It seems like Aurora instances in particular do not support Multi-AZ? "Multi-AZ DB clusters are in preview for RDS for MySQL and RDS for PostgreSQL" Leaving me somewhat stuck.

Edit I did just see this message elsewhere: "You have no Aurora Replicas in your DB cluster." which might be why Multi-AZ is not available. But I'm not seeing any options to spin up a replica anywhere.

Again my goal is to get my Aurora DB into a public subnet (or otherwise make it accessible from the internet, but not through an SSH tunnel)

答:
The Availability Zone options are in the "Availability & durability" section above "Connectivity" FYI

I just had your same issue but with a Postgres DB, though I have the option to change its "Subnet group" in the Connectivity section, which you don't have it seems, but it only appears for me if the DB is NOT currently multi-AZ. AWS will prevent you from moving the DB between subnet groups* in the same VPC, but you can just move the DB to a subnet group in a different VPC and then move it back to the subnet group that you actually want it in (configured with the appropriate public subnets).

*You can create subnet groups in the RDS service, left side menu.


问:
How to define repeat and layer in vega-lite api
I have a data which looks something like this:

```<code>student_name,d,e
student1,0.1,0.7
student2,0.2,0.3
student3,0.3,0.4
student4,0.25,0.2
student5,0.4,0.15
student6,0.6,0.2
student7,0.15,0.5
student8,0.7,0.13
student9,0.56,0.22
student10,0.35,0.2
</code>```

I want to visualize this data with vega-lite-api such that X-axis will have students and there will be two line charts each for column d and e. I tried something like this:

```<code>vl
  .markLine()
  .encode(
    vl.x().fieldN('student_name').sort('y'),
    vl.y().fieldQ('d'),
  );
</code>```

This correctly shows column d values on y axis against students on x axis:

However, I am unable to guess how I can have column e values on y axis too.
I guess I need to repeat and layer, something like this:

```<code>{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "url": "data/movies.json"
  },
  "repeat": {
    "layer": ["US Gross", "Worldwide Gross"]
  },
  "spec": {
    "mark": "line",
    "encoding": {
      "x": {
        "bin": true,
        "field": "IMDB Rating",
        "type": "quantitative"
      },
      "y": {
        "aggregate": "mean",
        "field": {"repeat": "layer"},
        "type": "quantitative",
        "title": "Mean of US and Worldwide Gross"
      },
      "color": {
        "datum": {"repeat": "layer"},
        "type": "nominal"
      }
    }
  }
}
</code>```

which outputs:

But I am unable to guess how can translate repeat and layer in above vega-lite grammar to vega-lite-api calls.

答:
According to the documentation you can use the vl.repeat and vl.layer methods to build repeat and layer objects.

You can then insert these into your spec with the spec.repeat method returned by vl.encode(), and with the y.field method.

Using your example, the following JS code

vl
  .markLine()
  .encode(
    vl.x().fieldN('student_name').sort('y'),
    vl.y().field(vl.repeat('layer')),
  ).repeat(
    vl.layer(["d", "e"])
  )
```
<p>will output this JSON:</p>
<pre class="lang-json prettyprint-override"><code>{
   "$schema":"https://vega.github.io/schema/vega-lite/v4.json",
   "repeat":{
      "layer":[
         "d",
         "e"
      ]
   },
   "spec":{
      "mark":{
         "type":"line"
      },
      "encoding":{
         "x":{
            "field":"student_name",
            "type":"nominal",
            "sort":"y"
         },
         "y":{
            "field":{
               "repeat":"layer"
            }
         }
      }
   }
}
</code>```

This notebook will let you experiment with a live version of this code.

Body:
I have a data which looks something like this:

student_name,d,e
student1,0.1,0.7
student2,0.2,0.3
student3,0.3,0.4
student4,0.25,0.2
student5,0.4,0.15
student6,0.6,0.2
student7,0.15,0.5
student8,0.7,0.13
student9,0.56,0.22
student10,0.35,0.2

I want to visualize this data with vega-lite-api such that X-axis will have students and there will be two line charts each for column d and e. I tried something like this:

vl
  .markLine()
  .encode(
    vl.x().fieldN('student_name').sort('y'),
    vl.y().fieldQ('d'),
  );

This correctly shows column d values on y axis against students on x axis:

However, I am unable to guess how I can have column e values on y axis too.
I guess I need to repeat and layer, something like this:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "url": "data/movies.json"
  },
  "repeat": {
    "layer": ["US Gross", "Worldwide Gross"]
  },
  "spec": {
    "mark": "line",
    "encoding": {
      "x": {
        "bin": true,
        "field": "IMDB Rating",
        "type": "quantitative"
      },
      "y": {
        "aggregate": "mean",
        "field": {"repeat": "layer"},
        "type": "quantitative",
        "title": "Mean of US and Worldwide Gross"
      },
      "color": {
        "datum": {"repeat": "layer"},
        "type": "nominal"
      }
    }
  }
}

which outputs:

But I am unable to guess how can translate repeat and layer in above vega-lite grammar to vega-lite-api calls.

Body:
According to the documentation you can use the vl.repeat and vl.layer methods to build repeat and layer objects.

You can then insert these into your spec with the spec.repeat method returned by vl.encode(), and with the y.field method.

Using your example, the following JS code

vl
  .markLine()
  .encode(
    vl.x().fieldN('student_name').sort('y'),
    vl.y().field(vl.repeat('layer')),
  ).repeat(
    vl.layer(["d", "e"])
  )

will output this JSON:

{
   "$schema":"https://vega.github.io/schema/vega-lite/v4.json",
   "repeat":{
      "layer":[
         "d",
         "e"
      ]
   },
   "spec":{
      "mark":{
         "type":"line"
      },
      "encoding":{
         "x":{
            "field":"student_name",
            "type":"nominal",
            "sort":"y"
         },
         "y":{
            "field":{
               "repeat":"layer"
            }
         }
      }
   }
}

This notebook will let you experiment with a live version of this code.


问:
Assertion testing a void function
I am writing a code with multiple void methods within a class, I am tasked with testing all of my methods using the assert from the c++ header <cassert>.  Here is one of my methods, that goes through the array in the class and trims the leading and trailing blank spaces. How would I write a function to test this method using assert? I am confused because there is no return value.

```<code>void trim_all() {
    // Iterate through all strings
    for (int i = 0; i < strSize; i++) {
        // Initialize variables
        int begin = 0;
        int end = arr[i].size() - 1;
        // While loops to check how many spaces in front and back
        while (begin < arr[i].size() && arr[i][begin] == ' ') {
            begin++;
        }
        while (end >= 0 && arr[i][end] == ' ') {
            end--;
        }
        // Update string to trimmed version
        arr[i] = arr[i].substr(begin, end - begin + 1);
    }
}
</code>```

答:
I agree with paddy, assert is not a good fit here - it will terminate your program on the first failure.

However, all test frameworks have their version of assertion, that would report the failure (optionally with details) and keep going.

For that later case, the assertion is trivial: iterate through your arr and make sure that each string doesn't begin or end with a space.

See this: Using ASSERT and EXPECT in GoogleTest

Title: Assertion testing a void function

Body:
I am writing a code with multiple void methods within a class, I am tasked with testing all of my methods using the assert from the c++ header <cassert>.  Here is one of my methods, that goes through the array in the class and trims the leading and trailing blank spaces. How would I write a function to test this method using assert? I am confused because there is no return value.

void trim_all() {
    // Iterate through all strings
    for (int i = 0; i < strSize; i++) {
        // Initialize variables
        int begin = 0;
        int end = arr[i].size() - 1;
        // While loops to check how many spaces in front and back
        while (begin < arr[i].size() && arr[i][begin] == ' ') {
            begin++;
        }
        while (end >= 0 && arr[i][end] == ' ') {
            end--;
        }
        // Update string to trimmed version
        arr[i] = arr[i].substr(begin, end - begin + 1);
    }
}


问:
Checkbox classList Toggle
I'm trying to use a custom slider with an input type=checkbox to toggle between dark-mode and light-mode. It is not working with the javascript code I have.

var checkbox = document.getElementById('checkbox');
    checkbox.addEventListener('change', themeChange);

    function themeChange(){
      if (checkbox.checked == true){
        document.getElementById('body').classList.toggle('dark-mode');
      } else {
        document.getElementById('body').classList.toggle('light-mode');
      }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dark-mode {
      background-color: black;
      color: white;
    }

    .light-mode {
      background-color: white;
      color: black;
    }</code>```

       <input id="checkbox" type="checkbox" >

    ```

答:
.toggle() will remove and add one single class. Try it this way instead

```<code>function themeChange(){
  if (checkBox.checked == true){
    document.getElementById('body').classList.add('dark-mode');
    document.getElementById('body').classList.remove('light-mode');
  } else {
    document.getElementById('body').classList.remove('dark-mode');
    document.getElementById('body').classList.add('light-mode');
}
</code>```

Title: Checkbox classList Toggle

Body:
I'm trying to use a custom slider with an input type=checkbox to toggle between dark-mode and light-mode. It is not working with the javascript code I have.

var checkbox = document.getElementById('checkbox');
    checkbox.addEventListener('change', themeChange);

    function themeChange(){
      if (checkbox.checked == true){
        document.getElementById('body').classList.toggle('dark-mode');
      } else {
        document.getElementById('body').classList.toggle('light-mode');
      }
    }

.dark-mode {
      background-color: black;
      color: white;
    }

    .light-mode {
      background-color: white;
      color: black;
    }

       <input id="checkbox" type="checkbox" >

Body:
.toggle() will remove and add one single class. Try it this way instead

function themeChange(){
  if (checkBox.checked == true){
    document.getElementById('body').classList.add('dark-mode');
    document.getElementById('body').classList.remove('light-mode');
  } else {
    document.getElementById('body').classList.remove('dark-mode');
    document.getElementById('body').classList.add('light-mode');
}


问:
How to integrate FxCop into Visual Studio 2005?
I use VS2005 but the version is not integrated to fxcop. Now I need to have some code metrics and the most proper is fxcop. How can I integrate VS with fxcop? Which version of fxcop do I need? What else should I take under consideration before I integrate fxcop?

Thanks,
Sun

答:
As far as I know, the only way to do this is to run FxCop as an external tool. See here for details:

http://geekswithblogs.net/sdorman/archive/2007/02/18/106630.aspx

You should be able to use the latest version of FxCop, if you want to.

ContentLicense: CC BY-SA 3.0


问:
ASP.NET Core 1.1 compiling with C# dynamic Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
I'm using Visual Studio 2017 RC and started a new ASP.NET Core project targeting the full .NET Framework.

This line of code will not compile.

```<code> dynamic handler = _container.GetService(handlerType);

 if (handler == null) _logger.LogError("Can't find handler to handle " + cmd.GetType().Name);
</code>```

I get the following error

```<code>CS0656  Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
</code>```

After some Googling it looks like this is because I'm missing the Microsoft.CSharp Assembly. There are plenty of people who have stumbled into his issue but not seemingly with .NET Core 1.1.

So I did this Install-Package Microsoft.CSharp and got version 4.3.0. My project still won't build.

If I add an Assembly Reference to Microsoft.CSharp (the GAC'd version) then it Compiles and runs.

Is this a Bug? I would have expected the NuGet package to fix this?

答:
There was a similar problem.
I wanted to create a NetStandartd 2.0 library for the NetFramework 4.6.2 environment that uses a dynamic object and got the error "Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create". This error is caused by the absence of the Microsoft.CSharp library.
By correcting .csproj file I was able to make the correct linking:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0;net462</TargetFramework>
    <DependsOnNETStandard>netstandard2.0</DependsOnNETStandard>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>
</Project>
</code>```

Body:
I'm using Visual Studio 2017 RC and started a new ASP.NET Core project targeting the full .NET Framework.

This line of code will not compile.

 dynamic handler = _container.GetService(handlerType);

 if (handler == null) _logger.LogError("Can't find handler to handle " + cmd.GetType().Name);

I get the following error

CS0656  Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

After some Googling it looks like this is because I'm missing the Microsoft.CSharp Assembly. There are plenty of people who have stumbled into his issue but not seemingly with .NET Core 1.1.

So I did this Install-Package Microsoft.CSharp and got version 4.3.0. My project still won't build.

If I add an Assembly Reference to Microsoft.CSharp (the GAC'd version) then it Compiles and runs.

Is this a Bug? I would have expected the NuGet package to fix this?

Body:
There was a similar problem.
I wanted to create a NetStandartd 2.0 library for the NetFramework 4.6.2 environment that uses a dynamic object and got the error "Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create". This error is caused by the absence of the Microsoft.CSharp library.
By correcting .csproj file I was able to make the correct linking:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0;net462</TargetFramework>
    <DependsOnNETStandard>netstandard2.0</DependsOnNETStandard>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>
</Project>


问:
How can I retrieve all members when querying for appRoleAssignedTo in Microsoft Graph?
I am attempting to programmatically retrieve a list of users (principalType = "User") and their associated appRoleId values for an enterprise app using itsresourceId value from Azure AD.  There is a total of ten Users with a combined total of twenty appRoleId values associated with the app.  However, when I run my query I receive data for just two users and a combined total of four appRoleId values.

Here's my C# code:

```<code>GraphServiceClient myGraphClient = GetGraphServiceClient([scopes]);
// Retrieve the [Id] value for the app.  Note [Id] is a pseudonym for the [resourceId] required to retrieve users and app roles assigned.
var servPrinPage = await myGraphClient.ServicePrincipals.Request()
   .Select("id,appRoles")
   .Filter($"startswith(displayName, 'Display Name')")
   .GetAsync()
   .ConfigureAwait(false);
// Using the first [Id] value from the [ServicePrincipals] page, retrieve the list of users and their assigned roles for the app.
var appRoleAssignedTo = await myGraphClient.ServicePrincipals[servPrinPage[0].Id].AppRoleAssignedTo.Request().GetAsync().ConfigureAwait(false);
</code>```

The query returns a ServicePrincipalAppRoleAssignedToCollectionPage (as expected) but the collection only contains four pages (one per User/appRoleId combination).

As an aside, the following query in Microsoft Graph Explorer produces an equivalent result:

```<code>https://graph.microsoft.com/v1.0/servicePrincipals/[resourceId]/appRoleAssignedTo
</code>```

What am I missing here?  I need to be able to retrieve the complete list of users and assigned app roles.  Any assistance is greatly appreciated.

答:
The issue I was confronting has to do with the pagination feature employed by Azure AD and MS Graph.  In a nutshell, I was forced to submit two queries in order to retrieve all twenty records I was expecting.

If you have a larger set of records to be retrieved you may be faced with submitting a much larger number of successive queries. The successive queries are managed using a "skiptoken" passed as a request header each time your query is resubmitted.

Here is my revised code with notation....

```<code>// Step #1:  Create a class in order to strongly type the <List> which will hold your results.
// Not absolutely necessary but always a good idea when working with <Lists> in C#.

private class AppRoleByUser
{
    public string AzureDisplayName;
    public string PrincipalDisplayName;
}

// Step #2: Submit a query to acquire the [id] for the Service Principal (i.e. your app).
// Note the [ServicePrincipals].[id] property is synonymous with the [resourceId] needed to
// retrieve [AppRoleAssignedTo] values from Microsoft Graph in the next step.

// Initialize the Microsoft Graph Client.
GraphServiceClient myGraphClient = GetGraphServiceClient("Directory.Read.All");

// Retrieve the Service Principals page containing the app [Id].
var servPrinPage = await myGraphClient.ServicePrincipals.Request().Select("id,appRoles").Filter($"startswith(displayName, 'Your App Name')").GetAsync().ConfigureAwait(false);

// Store the app [Id] in a local variable (for readability).
string resourceId = servPrinPage[0].Id;

// Step #3: Using the [Id]/[ResourceId] value from the previous step, retrieve a list of AppRoleId/DisplayName pairs for your app.

// Results of the successive queries are typed against the class created earlier and are appended to the <List>.
List<AppRoleByUser> appRoleByUser  = new List<AppRoleByUser>();

// Note, unlike "Filter" or "Search" parameters, it is not possible to
// add a "Skiptoken" parameter directly to your query in C#.
// Instead, it is necessary to insert the "skiptoken" as request header using the Graph QueryOption class.
// Note the QueryOption List is passed as an empty object on the first pass of the while loop.
var queryOptions = new List<QueryOption>();

// Initialize the variable to hold the anticipated query result.
ServicePrincipalAppRoleAssignedToCollectionPage appRoleAssignedTo = new ServicePrincipalAppRoleAssignedToCollectionPage();

// Note the number of user/role combinations associated with an app is not always known.
// Consequently, you may be faced with the need to acquire multiple pages
// (and submit multiple consecutive queries) in order to obtain a complete
// listing of user/role combinations.
// The "while" loop construct will be utilized to manage query iteration.
// Execution of the "while" loop will be stopped when the "bRepeat" variable is set to false.

bool bRepeat = true;
while (bRepeat == true)
{
    appRoleAssignedTo = (ServicePrincipalAppRoleAssignedToCollectionPage) await myGraphClient.ServicePrincipals[resourceId].AppRoleAssignedTo.Request(queryOptions).GetAsync().ConfigureAwait(false);
    foreach (AppRoleAssignment myPage in appRoleAssignedTo)
    {
        // I was not able to find a definitive answer in any of the documents I
        // found but it appears the final record in the recordset carries a
        // [PrincipalType] = "Group" (all others carry a [PrincipalType] = "User").
        if (myPage.PrincipalType != "Group")
        {
            // Insert "User" data into the List<AppRoleByUser> collection.
            appRoleByUser.Add(new AppRoleByUser{ AzureDisplayName = myPage.PrincipalDisplayName, AzureUserRole = myPage.AppRoleId.ToString() });
        }
        else
        {
            // The "bRepeat" variable is initially set to true and is set to
            // false when the "Group" record is detected thus signaling
            // task completion and closing execution of the "while" loop.
            bRepeat = false;
        }
    }
    // Acquire the "nextLink" string from the response header.
    // The "nextLink" string contains the "skiptoken" string required for the next
    // iteration of the query.
    string nextLinkValue = appRoleAssignedTo.AdditionalData["@odata.nextLink"].ToString();

    // Parse the "skiptoken" value from the response header.
    string skipToken = nextLinkValue.Substring(nextLinkValue.IndexOf("=") + 1);

    // Include the "skiptoken" as a request header in the next iteration of the query.
    queryOptions = new List<QueryOption>()
    {
        new QueryOption("$skiptoken", skipToken)
    };
}
</code>```

That's a long answer to what should have been a simple question.  I am relatively new to Microsoft Graph but it appears to me Microsoft has a long way to go in making this API developer-friendly.  All I needed was to know the combination of AppRoles and Users associated with a single, given Azure AD app.  One query and one response should have been more than sufficient.

At any rate, I hope my toil might help save time for someone else going forward.

Body:
I am attempting to programmatically retrieve a list of users (principalType = "User") and their associated appRoleId values for an enterprise app using itsresourceId value from Azure AD.  There is a total of ten Users with a combined total of twenty appRoleId values associated with the app.  However, when I run my query I receive data for just two users and a combined total of four appRoleId values.

Here's my C# code:

GraphServiceClient myGraphClient = GetGraphServiceClient([scopes]);
// Retrieve the [Id] value for the app.  Note [Id] is a pseudonym for the [resourceId] required to retrieve users and app roles assigned.
var servPrinPage = await myGraphClient.ServicePrincipals.Request()
   .Select("id,appRoles")
   .Filter($"startswith(displayName, 'Display Name')")
   .GetAsync()
   .ConfigureAwait(false);
// Using the first [Id] value from the [ServicePrincipals] page, retrieve the list of users and their assigned roles for the app.
var appRoleAssignedTo = await myGraphClient.ServicePrincipals[servPrinPage[0].Id].AppRoleAssignedTo.Request().GetAsync().ConfigureAwait(false);

The query returns a ServicePrincipalAppRoleAssignedToCollectionPage (as expected) but the collection only contains four pages (one per User/appRoleId combination).

As an aside, the following query in Microsoft Graph Explorer produces an equivalent result:

https://graph.microsoft.com/v1.0/servicePrincipals/[resourceId]/appRoleAssignedTo

What am I missing here?  I need to be able to retrieve the complete list of users and assigned app roles.  Any assistance is greatly appreciated.

Body:
The issue I was confronting has to do with the pagination feature employed by Azure AD and MS Graph.  In a nutshell, I was forced to submit two queries in order to retrieve all twenty records I was expecting.

If you have a larger set of records to be retrieved you may be faced with submitting a much larger number of successive queries. The successive queries are managed using a "skiptoken" passed as a request header each time your query is resubmitted.

Here is my revised code with notation....

// Step #1:  Create a class in order to strongly type the <List> which will hold your results.
// Not absolutely necessary but always a good idea when working with <Lists> in C#.

private class AppRoleByUser
{
    public string AzureDisplayName;
    public string PrincipalDisplayName;
}

// Step #2: Submit a query to acquire the [id] for the Service Principal (i.e. your app).
// Note the [ServicePrincipals].[id] property is synonymous with the [resourceId] needed to
// retrieve [AppRoleAssignedTo] values from Microsoft Graph in the next step.

// Initialize the Microsoft Graph Client.
GraphServiceClient myGraphClient = GetGraphServiceClient("Directory.Read.All");

// Retrieve the Service Principals page containing the app [Id].
var servPrinPage = await myGraphClient.ServicePrincipals.Request().Select("id,appRoles").Filter($"startswith(displayName, 'Your App Name')").GetAsync().ConfigureAwait(false);

// Store the app [Id] in a local variable (for readability).
string resourceId = servPrinPage[0].Id;

// Step #3: Using the [Id]/[ResourceId] value from the previous step, retrieve a list of AppRoleId/DisplayName pairs for your app.

// Results of the successive queries are typed against the class created earlier and are appended to the <List>.
List<AppRoleByUser> appRoleByUser  = new List<AppRoleByUser>();

// Note, unlike "Filter" or "Search" parameters, it is not possible to
// add a "Skiptoken" parameter directly to your query in C#.
// Instead, it is necessary to insert the "skiptoken" as request header using the Graph QueryOption class.
// Note the QueryOption List is passed as an empty object on the first pass of the while loop.
var queryOptions = new List<QueryOption>();

// Initialize the variable to hold the anticipated query result.
ServicePrincipalAppRoleAssignedToCollectionPage appRoleAssignedTo = new ServicePrincipalAppRoleAssignedToCollectionPage();

// Note the number of user/role combinations associated with an app is not always known.
// Consequently, you may be faced with the need to acquire multiple pages
// (and submit multiple consecutive queries) in order to obtain a complete
// listing of user/role combinations.
// The "while" loop construct will be utilized to manage query iteration.
// Execution of the "while" loop will be stopped when the "bRepeat" variable is set to false.

bool bRepeat = true;
while (bRepeat == true)
{
    appRoleAssignedTo = (ServicePrincipalAppRoleAssignedToCollectionPage) await myGraphClient.ServicePrincipals[resourceId].AppRoleAssignedTo.Request(queryOptions).GetAsync().ConfigureAwait(false);
    foreach (AppRoleAssignment myPage in appRoleAssignedTo)
    {
        // I was not able to find a definitive answer in any of the documents I
        // found but it appears the final record in the recordset carries a
        // [PrincipalType] = "Group" (all others carry a [PrincipalType] = "User").
        if (myPage.PrincipalType != "Group")
        {
            // Insert "User" data into the List<AppRoleByUser> collection.
            appRoleByUser.Add(new AppRoleByUser{ AzureDisplayName = myPage.PrincipalDisplayName, AzureUserRole = myPage.AppRoleId.ToString() });
        }
        else
        {
            // The "bRepeat" variable is initially set to true and is set to
            // false when the "Group" record is detected thus signaling
            // task completion and closing execution of the "while" loop.
            bRepeat = false;
        }
    }
    // Acquire the "nextLink" string from the response header.
    // The "nextLink" string contains the "skiptoken" string required for the next
    // iteration of the query.
    string nextLinkValue = appRoleAssignedTo.AdditionalData["@odata.nextLink"].ToString();

    // Parse the "skiptoken" value from the response header.
    string skipToken = nextLinkValue.Substring(nextLinkValue.IndexOf("=") + 1);

    // Include the "skiptoken" as a request header in the next iteration of the query.
    queryOptions = new List<QueryOption>()
    {
        new QueryOption("$skiptoken", skipToken)
    };
}

That's a long answer to what should have been a simple question.  I am relatively new to Microsoft Graph but it appears to me Microsoft has a long way to go in making this API developer-friendly.  All I needed was to know the combination of AppRoles and Users associated with a single, given Azure AD app.  One query and one response should have been more than sufficient.

At any rate, I hope my toil might help save time for someone else going forward.


问:
Download dataTable is printing HTML along with table
I have this sample app to display and download dataTable. But it is also printing HTML script on top of the downloaded attachment. It is printing logo and title HTML but I also want to preserve them on the app.</p>
```<code>library(shiny)
library(DT)
ui <- fluidPage(
  titlePanel(title = tags$div(img(src = "test.jpg", width = 170, height = 115, align = "left"))),
  titlePanel(title = tags$div(class = "header" , tags$p("Cars", tags$br(), tags$h4("MTCARS", style = "text-align: center; color:navy;"), style = "text-align: center; color:navy;"))),
  dataTableOutput("table_output")
)

server <- function(input, output, session){
  output$table_output <- renderDataTable(server=FALSE,{
    DT::datatable(head(mtcars), extensions = c('Buttons'),
                  options = list(autoWidth = FALSE, dom = 'lfrtipB',
                                 buttons = list(list(extend = "csv", text = "CSV", filename = "cars",
                                                     exportOptions = list(modifier = list(page = "all"))),
                                                list(extend = "excel", text = "EXCEL", filename = "cars",
                                                     exportOptions = list(modifier = list(page = "all"))),
                                                list(extend = "pdf", text = "PDF", filename = "cars",
                                                     exportOptions = list(modifier = list(page = "all")))
                                 ))) })
}

shinyApp(ui, server)
</code>```

答:
I had to change the UI function to get the proper attachment.</p>
```<code>ui <- fluidPage(
  img(src = "test.jpg", width = 170, height = 115, align = "left"),
  tags$div(class = "header" , tags$h2("Cars", tags$br(), tags$h4("MTCARS", style = "text-align: center; color:navy;"), style = "text-align: center; color:navy;")),
  dataTableOutput("table_output")
)
</code>```

Body:
I have this sample app to display and download dataTable. But it is also printing HTML script on top of the downloaded attachment. It is printing logo and title HTML but I also want to preserve them on the app.

library(shiny)
library(DT)
ui <- fluidPage(
  titlePanel(title = tags$div(img(src = "test.jpg", width = 170, height = 115, align = "left"))),
  titlePanel(title = tags$div(class = "header" , tags$p("Cars", tags$br(), tags$h4("MTCARS", style = "text-align: center; color:navy;"), style = "text-align: center; color:navy;"))),
  dataTableOutput("table_output")
)

server <- function(input, output, session){
  output$table_output <- renderDataTable(server=FALSE,{
    DT::datatable(head(mtcars), extensions = c('Buttons'),
                  options = list(autoWidth = FALSE, dom = 'lfrtipB',
                                 buttons = list(list(extend = "csv", text = "CSV", filename = "cars",
                                                     exportOptions = list(modifier = list(page = "all"))),
                                                list(extend = "excel", text = "EXCEL", filename = "cars",
                                                     exportOptions = list(modifier = list(page = "all"))),
                                                list(extend = "pdf", text = "PDF", filename = "cars",
                                                     exportOptions = list(modifier = list(page = "all")))
                                 ))) })
}

shinyApp(ui, server)

Body:
I had to change the UI function to get the proper attachment.

ui <- fluidPage(
  img(src = "test.jpg", width = 170, height = 115, align = "left"),
  tags$div(class = "header" , tags$h2("Cars", tags$br(), tags$h4("MTCARS", style = "text-align: center; color:navy;"), style = "text-align: center; color:navy;")),
  dataTableOutput("table_output")
)


问:
Unable to connect to Google Cloud VM via SSH
I've been unable to connect to my VM via SSH since changing persistent disks. I had a VM set up with a Balance Persistent Disk 10gb and wanted to switch to a Standard 30gb. My procedure as been:

Create a disk image

Shutdown current VM and deleted the bootdisk

Loaded the saved disk image and switched to a Standard Persistent Disk

Now I am unable to connect via SSH. In Activity I'm getting this message: Invalid argument (HTTP 400): Supplied fingerprint does not match current metadata fingerprint. I've added the custom Metadata enable-os login: TRUE. Tech is still trying to figure it out.

Has anyone encountered this issue?

答:
Tried on my end changing persistent disk to standard disk and with same metadata you've added and it worked in my end using below steps.

Compute Engine

Disk

Select VM's Disk

Create Image

Location same with seleted VM

Save

VM Instance > Select VM > Down > Edit

Detached Boot Disk

Configure Boot Disk > Custom Images > Select Project > Select Image > Boot disk Type to Standard > Select

Make Sure to check Allow http/https traffic

Worth to try also below:

Recreate image from disk, found some other fingerprint errors due to disk issue and was solve by remounting and fixing fstab key.

Generate/Create SSH Key and add on VM Instance > edit

Guide on Connecting Linux VM using advance method


问:
Capitalize ${NAME} in File and Code Templates
Problem

In Preferences -> Editor -> File and Code Templates I have a template for React with:

```<code>import React from 'react';

class ${NAME} extends React.Component {

  render() {
    return (
      <div>
        #[[$END$]]#
      </div>
    );
  }
}

export default ${NAME};
</code>```

Is there a way to capitalize the ${NAME}?

We have a convention of naming our files starting with a lowercase but in React components are meant to be capitalized.

Additional Information

I'm aware of the IntelliJ's ability to refactor and that you can use a Live Templates to accomplish this but I would like to remove this extra step :).

This is possible in Live Templates where you can define and reference a expression like capitalize(fileNameWithoutExtension()) but I couldn't find anywhere to define expressions in File and Code Templates.

答:
Here is all cases for WebStorm File template:</p>
```<code>#set($NAME_CAP = $NAME.substring(0,1).toUpperCase() + $NAME.substring(1))
#set($NAME_LOW = $NAME.substring(0,1).toLowerCase() + $NAME.substring(1))
#set($NAME_UPPER = $NAME.toUpperCase())
</code>```

Body:
Problem

In Preferences -> Editor -> File and Code Templates I have a template for React with:

import React from 'react';

class ${NAME} extends React.Component {

  render() {
    return (

        #[[$END$]]#

    );
  }
}

export default ${NAME};

Is there a way to capitalize the ${NAME}?

We have a convention of naming our files starting with a lowercase but in React components are meant to be capitalized.

Additional Information

I'm aware of the IntelliJ's ability to refactor and that you can use a Live Templates to accomplish this but I would like to remove this extra step :).

This is possible in Live Templates where you can define and reference a expression like capitalize(fileNameWithoutExtension()) but I couldn't find anywhere to define expressions in File and Code Templates.

Body:
Here is all cases for WebStorm File template:

#set($NAME_CAP = $NAME.substring(0,1).toUpperCase() + $NAME.substring(1))
#set($NAME_LOW = $NAME.substring(0,1).toLowerCase() + $NAME.substring(1))
#set($NAME_UPPER = $NAME.toUpperCase())


问:
Why does the built in python SSL library give "ssl.SSLError: [SSL] internal error (_ssl.c:1129)" on ubuntu, but not mac, with no code changes?
I am attempting to build an IRC bot. To connect to the server, I am using the built in ssl library from python. When I run my code on Mac (MacOS 10.15.6, Python 3.9.10, OpenSSL 1.1.1k  25 Mar 2021), it connects to the server, and works perfectly fine, however, when I run the exact same program on my ubuntu server (Ubuntu 20.04.3 LTS, Python 3.9.5, OpenSSL 1.1.1f  31 Mar 2020) it fails with this error:

```<code>Traceback (most recent call last):
  File "/home/kyodie/IRCbot/bot.py", line 42, in <module>
    main()
  File "/home/kyodie/IRCbot/bot.py", line 11, in main
    client = irc.IRCClient("irc.geekshed.net", 6697, botCredentials)
  File "/home/kyodie/IRCbot/irc.py", line 33, in __init__
    self.__login()
  File "/home/kyodie/IRCbot/irc.py", line 166, in __login
    self.socket.connect((self.hostname, self.port))
  File "/usr/lib/python3.9/ssl.py", line 1342, in connect
    self._real_connect(addr, False)
  File "/usr/lib/python3.9/ssl.py", line 1333, in _real_connect
    self.do_handshake()
  File "/usr/lib/python3.9/ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL] internal error (_ssl.c:1129)
</code>```

Here is the relevent code:

# irc.py
def __login(self):
    self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    self.socket = self.context.wrap_socket(self.socket, server_side=False)

    self.socket.connect((self.hostname, self.port)) # <--- ERROR HERE
    self.__start_listening()
    self.__ident()
```

答:
Solved: I switched from TLS version 1 to TLS v 1.2

# irc.py
def __login(self):
    self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    self.socket = self.context.wrap_socket(self.socket, server_side=False)

    self.socket.connect((self.hostname, self.port)) # <--- ERROR HERE
    self.__start_listening()
    self.__ident()
```

Body:
I am attempting to build an IRC bot. To connect to the server, I am using the built in ssl library from python. When I run my code on Mac (MacOS 10.15.6, Python 3.9.10, OpenSSL 1.1.1k  25 Mar 2021), it connects to the server, and works perfectly fine, however, when I run the exact same program on my ubuntu server (Ubuntu 20.04.3 LTS, Python 3.9.5, OpenSSL 1.1.1f  31 Mar 2020) it fails with this error:

Traceback (most recent call last):
  File "/home/kyodie/IRCbot/bot.py", line 42, in <module>
    main()
  File "/home/kyodie/IRCbot/bot.py", line 11, in main
    client = irc.IRCClient("irc.geekshed.net", 6697, botCredentials)
  File "/home/kyodie/IRCbot/irc.py", line 33, in __init__
    self.__login()
  File "/home/kyodie/IRCbot/irc.py", line 166, in __login
    self.socket.connect((self.hostname, self.port))
  File "/usr/lib/python3.9/ssl.py", line 1342, in connect
    self._real_connect(addr, False)
  File "/usr/lib/python3.9/ssl.py", line 1333, in _real_connect
    self.do_handshake()
  File "/usr/lib/python3.9/ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL] internal error (_ssl.c:1129)

Here is the relevent code:

# irc.py
def __login(self):
    self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    self.socket = self.context.wrap_socket(self.socket, server_side=False)

    self.socket.connect((self.hostname, self.port)) # <--- ERROR HERE
    self.__start_listening()
    self.__ident()


问:
Can we replace every ColdFusion tag by equivalent cfscript statements?
I wanted to know can my cfml page or cfc components with with only cfscript tag?

Can we use it everywhere? Is there any limitation in its usage?

Edit:

I am curious because I read the following line

In addition to variable setting, other operations tend to be slightly
  faster in CFScript than in tags.

Read it here

答:
In coldfusion 8 and below tags like cfmail are not avaiable in cfscript. You can however call them by wrapping it in a cffunction like this:

```<code><cffunction name="myCfEmail">
    <cfmail ...></cfmail>
</cffunction>

<cfscript>
    myCfEmail();
</cfscript>
</code>```

In coldfusion 9 you can actually do this for some tags. See http://www.bennadel.com/blog/1663-Learning-ColdFusion-9-CFScript-Updates-For-Tag-Operators.htm on how to do this.

Body:
In coldfusion 8 and below tags like cfmail are not avaiable in cfscript. You can however call them by wrapping it in a cffunction like this:

<cffunction name="myCfEmail">
    <cfmail ...></cfmail>
</cffunction>

<cfscript>
    myCfEmail();
</cfscript>

In coldfusion 9 you can actually do this for some tags. See http://www.bennadel.com/blog/1663-Learning-ColdFusion-9-CFScript-Updates-For-Tag-Operators.htm on how to do this.


问:
Is there a living R package to execute Heckman model for count data outcome?
Found this https://link.springer.com/article/10.1007/s00180-017-0762-y, which no longer works.</p>

答:
You can always download directly from the GitHub repository with the devtools package:

devtools::install_github("cran/SemiParSampleSel")
```


问:
how to set battery % in android mobile using adb command?
If suppose 40% battery is available in my android device, what is the  adb command to set the battery % to 30?
Using adb command can set battery % only to lower level / higher level also?</p>

答:
Use the following command:

adb shell dumpsys battery set level 30

And use this to reset the level:

adb shell dumpsys battery reset


问:
Find and remove
```

<p>The link above suggests editing core WP files..
Question is, would there be a way to find and remove using jQuery?</p>

<p>Something like below, which didn't work in locating the empty src / script element.</p>

```$('footer script').each(function(){
        if($(this).attr('src') == 'undefined' && $(this).length < 1){
            $(this).remove();
        }
     })
```

Edit : Since asking this question i've come to realise i need to remove the script element using PHP, in order for the page to validate.

答:
I didn't test the solution of Sébastien. I only needed to find the script tags with empty src and do something different with them (copy data-src to src for a privacy guard, where src will be set if consent was given), but removing also works.

```<code>$('footer script[src=""]').each(function () {
    $(this).remove();
});
</code>```

FWIW: To set src by data-src looks like:

```<code>$(this).find('script[src=""]').each(function () {
    var src = $(this).data('src');
    $(this).attr('src', src).show();
});
</code>```

Works also with iframe by replacing script with iframe.

Title: Find and remove <script> element with empty src attribute

Body:
The Facebook Plugin for wordpress has an issue where it adds a script element to the DOM with an empty src attribute.

http://wordpress.org/support/topic/w3c-validation-error-caused-my-empty-src-tag-generated-by-plugin?replies=3

The link above suggests editing core WP files..
Question is, would there be a way to find and remove using jQuery?

Something like below, which didn't work in locating the empty src / script element.

$('footer script').each(function(){
        if($(this).attr('src') == 'undefined' && $(this).length < 1){
            $(this).remove();
        }
     })

Edit : Since asking this question i've come to realise i need to remove the script element using PHP, in order for the page to validate.

Body:
I didn't test the solution of Sébastien. I only needed to find the script tags with empty src and do something different with them (copy data-src to src for a privacy guard, where src will be set if consent was given), but removing also works.

$('footer script[src=""]').each(function () {
    $(this).remove();
});

FWIW: To set src by data-src looks like:

$(this).find('script[src=""]').each(function () {
    var src = $(this).data('src');
    $(this).attr('src', src).show();
});

Works also with iframe by replacing script with iframe.


问:
Action not happening every certain amount of ticks
this code is for the reproduction of an animal. It should happen every 10 ticks, but it is happening instantly and i dont know why.  They also have energy. Reproduction is set to be random to show females.

thanks in advance for the help.

```<code>turtles-own[ energia edad]
breed[perros perro]
to setup
   resize-world 0 80 0 60
  clear-all
  ask patches[
    set pcolor green]

    create-perros 50
 [
    set size 3        ;; easier to see
    set color yellow
setxy (41 + random 39) random 60
    set heading random 360
    set energia 100
    set edad 1
  ]

  reset-ticks
end

to go

  ask perros [ set edad edad + 1]

  ask perros [
    morir-perros
        moverse-perros
    reproducirse
      ]
  tick
end
  to morir-perros

  if edad > 15 [die]
  if energia < 1 [die]

end

to moverse-perros

   set heading random 360 fd 5
  set energia energia - 5

end

 to reproducirse

  if ticks mod 10 = 0 [ if random 100 > 50 [set energia energia - 60
      hatch 1 [ rt random-float 360 fd 2
      set energia (energia + 60) / 3]]]

end

</code>```

答:
Right now you have tick to increment your time step at the end of your go procedure. In any model, ticks start at 0 by default, so your model is evaluating ticks mod 10:

```<code>observer> show 0 mod 10
observer: 0
</code>```

Since that would satisfy the condition in reproducirse, the code is evaluated. You can handle this in a variety of ways. The simplest may be to modify your if statement in reproducirse- for example:

```<code>to reproducirse
  if ticks > 0 and ticks mod 10 = 0 [ if random 100 > 50 [set energia energia - 60
    hatch 1 [ rt random-float 360 fd 2
      set energia (energia + 60) / 3]]]
end
</code>```

Body:
this code is for the reproduction of an animal. It should happen every 10 ticks, but it is happening instantly and i dont know why.  They also have energy. Reproduction is set to be random to show females.

thanks in advance for the help.

turtles-own[ energia edad]
breed[perros perro]
to setup
   resize-world 0 80 0 60
  clear-all
  ask patches[
    set pcolor green]

    create-perros 50
 [
    set size 3        ;; easier to see
    set color yellow
setxy (41 + random 39) random 60
    set heading random 360
    set energia 100
    set edad 1
  ]

  reset-ticks
end

to go

  ask perros [ set edad edad + 1]

  ask perros [
    morir-perros
        moverse-perros
    reproducirse
      ]
  tick
end
  to morir-perros

  if edad > 15 [die]
  if energia < 1 [die]

end

to moverse-perros

   set heading random 360 fd 5
  set energia energia - 5

end

 to reproducirse

  if ticks mod 10 = 0 [ if random 100 > 50 [set energia energia - 60
      hatch 1 [ rt random-float 360 fd 2
      set energia (energia + 60) / 3]]]

end

Body:
Right now you have tick to increment your time step at the end of your go procedure. In any model, ticks start at 0 by default, so your model is evaluating ticks mod 10:

observer> show 0 mod 10
observer: 0

Since that would satisfy the condition in reproducirse, the code is evaluated. You can handle this in a variety of ways. The simplest may be to modify your if statement in reproducirse- for example:

to reproducirse
  if ticks > 0 and ticks mod 10 = 0 [ if random 100 > 50 [set energia energia - 60
    hatch 1 [ rt random-float 360 fd 2
      set energia (energia + 60) / 3]]]
end


问:
How to check inner part of 3D array numpy
I have a 3D array a = np.array([[[1,1],[1,1]],[[1,0],[1,0]]]) and I need to check which members are equal to [1,1] and set all other members to [0,0] How should I approach this?

答:
You can use numpy.where with the appropriate axis to find the subarrays. Given that you can assign a new value:

```<code>import numpy as np

a = np.array([[[1, 1],
            [1, 1]],

           [[1, 0],
            [1, 0]],

           [[1, 1],
            [1, 0]]
])
a[np.where(np.all(a == [1,1], axis=2))] = [0, 0]
</code>```

This will give you an a with:

```<code>array([[[0, 0],
        [0, 0]],

       [[1, 0],
        [1, 0]],

       [[0, 0],
        [1, 0]]])
</code>```

Body:
You can use numpy.where with the appropriate axis to find the subarrays. Given that you can assign a new value:

import numpy as np

a = np.array([[[1, 1],
            [1, 1]],

           [[1, 0],
            [1, 0]],

           [[1, 1],
            [1, 0]]
])
a[np.where(np.all(a == [1,1], axis=2))] = [0, 0]

This will give you an a with:

array([[[0, 0],
        [0, 0]],

       [[1, 0],
        [1, 0]],

       [[0, 0],
        [1, 0]]])


问:
How to round corners in Custom Shapes in SwiftUI?

I want to add round corner (corner radius) in my custom shape. I'm having trouble using path.addCurve or path.addArc

My Custom Shape Image in SwiftUI

```<code>import SwiftUI

struct ProDetails: View {
    var body: some View {
        VStack {
            ThemeShape()
                .frame(height: 450)
                .foregroundColor(.mint)
            Spacer()
        } .edgesIgnoringSafeArea(.top)

    }
}

struct ThemeShape: Shape {
    func path(in rect: CGRect) -> Path {
        Path { path in
            path.move(to: CGPoint(x: rect.minX, y: rect.midY))
            path.addLine(to: CGPoint(x: rect.minX + 80, y: rect.midY))
            path.addLine(to: CGPoint(x: rect.midX + 80, y: rect.maxY))
            path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
            path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
            path.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
        }
    }
}

struct ProDetails_Previews: PreviewProvider {
    static var previews: some View {
        ProDetails()
    }
}
</code>```

答:
struct ThemeShape: Shape {
  func path(in rect: CGRect) -> Path {
    Path { path in
      path.move(to: CGPoint(x: rect.minX, y: rect.midY))
      path.addLine(to: CGPoint(x: rect.minX + 80, y: rect.midY))
      path.addCurve(to: CGPoint(x: rect.midX, y: rect.maxY * 0.75),
                    control1: CGPoint(x: rect.minX + 80 + 30, y: rect.midY),
                    control2: CGPoint(x: rect.minX + 80 + 30, y: rect.midY))
      path.addCurve(to: CGPoint(x: rect.maxX - 80, y: rect.maxY),
                    control1: CGPoint(x: rect.maxX - 80 - 30, y: rect.maxY),
                    control2: CGPoint(x: rect.maxX - 80 - 30, y: rect.maxY))
      path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
      path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
      path.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
    }
  }
}
```

Body:
I want to add round corner (corner radius) in my custom shape. I'm having trouble using path.addCurve or path.addArc

My Custom Shape Image in SwiftUI

import SwiftUI

struct ProDetails: View {
    var body: some View {
        VStack {
            ThemeShape()
                .frame(height: 450)
                .foregroundColor(.mint)
            Spacer()
        } .edgesIgnoringSafeArea(.top)

    }
}

struct ThemeShape: Shape {
    func path(in rect: CGRect) -> Path {
        Path { path in
            path.move(to: CGPoint(x: rect.minX, y: rect.midY))
            path.addLine(to: CGPoint(x: rect.minX + 80, y: rect.midY))
            path.addLine(to: CGPoint(x: rect.midX + 80, y: rect.maxY))
            path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
            path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
            path.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
        }
    }
}

struct ProDetails_Previews: PreviewProvider {
    static var previews: some View {
        ProDetails()
    }
}


答:
```<code>var checkbox = document.getElementById('checkbox');

console.log(checkbox.valueOf());
checkbox.addEventListener('change', themeChange);

function themeChange(){
    if (checkbox.checked == true){
        document.getElementById('body').classList.add('dark-mode');
    } else {
        document.getElementById('body').classList.add('light-mode');
    }
}
</code>```

Title: Checkbox classList Toggle

Body:
I'm trying to use a custom slider with an input type=checkbox to toggle between dark-mode and light-mode. It is not working with the javascript code I have.

var checkbox = document.getElementById('checkbox');
    checkbox.addEventListener('change', themeChange);

    function themeChange(){
      if (checkbox.checked == true){
        document.getElementById('body').classList.toggle('dark-mode');
      } else {
        document.getElementById('body').classList.toggle('light-mode');
      }
    }

.dark-mode {
      background-color: black;
      color: white;
    }

    .light-mode {
      background-color: white;
      color: black;
    }

       <input id="checkbox" type="checkbox" >


问:
one onChange input, wrongly modifies other three tags content
I have the next state:

```<code>const [social_networks, setSocial_networks] = useState([
    {
      social_account_type: "personal",
      social_network: "linkedin",
      handle: "",
      content: ""
    },
    {
      social_account_type: "company",
      social_network: "twitter",
      handle: "",
      content: ""
    },
    {
      social_account_type: "personal",
      social_network: "webpage",
      handle: "",
      content: ""
    }
])
</code>```

In the parent component I declare the function:

```<code>const handleInputChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...social_networks];
    list[index][name] = value;
    setSocial_networks(list);
  };
</code>```

Set this to the children in the next code:

```<code>social_networks.map((social_network, idx) => {
                                  if (social_network.social_account_type == "personal") return <div key={idx}><AccountsPill handle={social_network.handle} social={social_network.social_network} content={social_network.handle} index={idx} handleInputChange={handleInputChange} />  </div>
                                })
</code>```

And into my child component I have the next code:

```<code><div className="row m-0">
    <div className="svg-container col-md-1">
        <BrowserIcon color="#868E96" />
    </div>
    <input type="text" className="col-md-11 set-account-input" placeholder=
    {"www."+props.social+".com"} name="handle" id="handle" defaultValue={props.handle}
    onChange={e => props.handleInputChange(e, props.index)} />
</div>
<div className="row m-0">
       <div className="svg-container col-md-1">
           <AtIcon color="#868E96" />
       </div>
       <input type="text" className="col-md-11 set-account-input" placeholder="MyUsername"
       name="content" id="content" defaultValue={props.content} onChange={e =>
       props.handleInputChange(e, props.index)} />
</div>
</code>```

The page show me like that:
after rendering frontpage

When I change the input.Content works fine:
input.name=content change

But, if I change the input.name=handle , change the other input too:
input.name=handle change

I tried to make two differents handleChange functions, change the props.name, add the props.id, but does'nt works yet.

答:
You passed wrong content props to your AccountsPill component, it should be

```<code><AccountsPill
      handle={social_network.handle}
      social={social_network.social_network}
      content={social_network.content}
      index={idx}
      handleInputChange={handleInputChange}
/>
</code>```

Body:
I have the next state:

const [social_networks, setSocial_networks] = useState([
    {
      social_account_type: "personal",
      social_network: "linkedin",
      handle: "",
      content: ""
    },
    {
      social_account_type: "company",
      social_network: "twitter",
      handle: "",
      content: ""
    },
    {
      social_account_type: "personal",
      social_network: "webpage",
      handle: "",
      content: ""
    }
])

In the parent component I declare the function:

const handleInputChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...social_networks];
    list[index][name] = value;
    setSocial_networks(list);
  };

Set this to the children in the next code:

social_networks.map((social_network, idx) => {
                                  if (social_network.social_account_type == "personal") return
<AccountsPill handle={social_network.handle} social={social_network.social_network} content={social_network.handle} index={idx} handleInputChange={handleInputChange} />

                                })

And into my child component I have the next code:

        <BrowserIcon color="#868E96" />

    <input type="text" className="col-md-11 set-account-input" placeholder=
    {"www."+props.social+".com"} name="handle" id="handle" defaultValue={props.handle}
    onChange={e => props.handleInputChange(e, props.index)} />

           <AtIcon color="#868E96" />

       <input type="text" className="col-md-11 set-account-input" placeholder="MyUsername"
       name="content" id="content" defaultValue={props.content} onChange={e =>
       props.handleInputChange(e, props.index)} />

The page show me like that:
after rendering frontpage

When I change the input.Content works fine:
input.name=content change

But, if I change the input.name=handle , change the other input too:
input.name=handle change

I tried to make two differents handleChange functions, change the props.name, add the props.id, but does'nt works yet.

Body:
You passed wrong content props to your AccountsPill component, it should be

<AccountsPill
      handle={social_network.handle}
      social={social_network.social_network}
      content={social_network.content}
      index={idx}
      handleInputChange={handleInputChange}
/>


问:
Algorithm for slicing a dynamic graph
I am currently working on a project based on graph and I am searching for an algorithm for slicing an dynamic graph. I have already done some research but most algorithms that I have found works only for a static graph. In my environment, the graph is dynamic, it means that users add/delete elements, create/delete dependences at runtime.
(In reality I am working with UML models but UML models can be also represented by typed graphs, wich are composed of typed Vertices and edges)
I also search for the terms graph fragmentation but I did not find anything. And I would like to know if exist such algorithm for slicing a dynamic graph?

[UPDATE]

Sorry for not being clear and I am updating my question.Let me first expose the context.

In MDE (Model Driven Engineering), large-scale industrial systems involve nowadays hundreds of developpers working on hundreds of models representing pars of the whole system specification. In a such context, the approach commonly adopted is to use a central repository. The solution I provide for my project (I am currently working on a research lab), is a solution which is peer-to-peer oriented, that means that every developper has his own replication of the system specification.

My main problem is how to replicate this data, the models.
For instance, imagine Alice and Bob working on this UML diagram and Alice has the whole diagram in his repository. Bob wants to have the elements {FeedOrEntry, Entry}, how can I slice this diagram UML?
I search for the terms of "model Slicing".I have found one paper which gives an approach for slicing UML Class Diagrams but the problem with this algorithm is it only works for a static graph. In our context, developpers add/update/remove elements constantly and the shared elements should be consistent with the other replicas.

Since UML Models can also be seen as a graph, I also search for the terms for "graph slicing" or "graph fragment" but I have found nothing useful.
And I would like to know if exist such algorithm for slicing a dynamic graph

答: What about to normalize the graph to an adjacent tree model? Then you can use a DFS or BFS to slice the graph?</p>

Title: Algorithm for slicing a dynamic graph


问:
What does the multiply operator do relational algebra?
I'm new to relational algebra. I found the * operator in the following expression

What's the different this and one using join

答: In few books natural join is denoted by an astric(*).</p>


问:
UnhandledPromiseRejection
Hello guys i create a website and everything works locally but when i deployed in heroku its not working and i cant find why thanks for the help

heroku error:

2022-02-10T03:13:43.014545+00:00 app[web.1]: (node:22) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
2022-02-10T03:13:43.014570+00:00 app[web.1]: (node:22) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2022-02-10T03:14:13.009344+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/" host=websitechina.herokuapp.com request_id=ab93f3f6-9ccf-49e0-be7b-fe765239c47b fwd="61.219.114.7" dyno=web.1 connect=0ms service=30000ms status=503 bytes=0 protocol=https

index.js:

const express = require('express')
const app = express()
const port = process.env.port || 3000
const nodemailer = require('nodemailer')

//Importer la logique de la page d acceuil
const generatorModele = require('./api/page/page-get')

//ecouter la methode GET et la route
app.get('/', async(req,res) => {
    const indexHtml = await generatorModele('index')

    res.send(indexHtml)

})

app.get ('/tech', async(req,res) => {
    const techHtml = await generatorModele('tech')
    res.send(techHtml)
})

app.get ('/contact', async(req,res) => {
    const contactHtml = await generatorModele('contact')
    res.send(contactHtml)
})

app.get ('/signUp', async(req,res) => {
    const signUpHtml = await generatorModele('signUp')
    res.send(signUpHtml)
})

//ecouter la methode Post et la route
app.post('/', (req,res)=>{
    console.log(req.body)

    //nodemailer

    not working yet i know // const transporter =
      nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '',
            pass: ''
        }
    })

    transporter.sendMail(mailOptions, (error, info)=>{
        if(error){
            console.log(error)
            res.send('error')
        }else{
            console.log('Email sent' + info.response)
            res.send('success')
        }
    })

})

//ecoute les requete du repertoire styles,js,images/
app.use('/styles', express.static('/Users/hi/code/dotfiles/dev/websitechina1/styles'))
app.use('/images', express.static('/Users/hi/code/dotfiles/dev/websitechina1/images/'))
app.use('/js', express.static('/Users/hi/code/dotfiles/dev/websitechina1/js/'))
app.use(express.json())

//demarrer le  serveur et ecouter un port donne
app.listen(process.env.PORT || port,() => {
    console.log
    (`Example app listening on port ${port}`)
})```
</div>
</div>
</p>
<p>app.js</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>const menu = document.querySelector('#mobile-menu');
const menuLinks = document.querySelector('.navbar_menu');

menu.addEventListener('click', function(){
    menu.classList.toggle('is-active');
    menuLinks.classList.toggle('active');
});

const contactForm = document.querySelector('.contact-form')
let fname = document.getElementById('fname')
let lname = document.getElementById('lname')
let email = document.getElementById('email')
let country = document.getElementById('country')
let subject = document.getElementById('subject')

contactForm.addEventListener('submit', (e)=>{
    e.preventDefault();

    let formData = {
        fname: fname.value,
        lname: lname.value,
        email: email.value,
        country: country.value,
        subject: subject.value
    }

    let xhr = new XMLHttpRequest();
    xhr.open('POST', '/')
    xhr.setRequestHeader('content-type','application/json')
    xhr.onload = function(){
        console.log(xhr.responseText)
        if (xhr.responseText == 'success'){
          alert('Email sent');
          fname.value = '';
          lname.value = '';
          email.value =  '';
          country.value = '';
          subject.value = '';
        }else{
            alert('Something went wrong')
        }

    }
    xhr.send(JSON.stringify(formData))
})</code>```

答:
All uses of await that can reject must be handled in some way.  They must either be surrounded by a try/catch or the caller of the async function must handle the rejection.

In this case, app.get() does not pay any attention to a returned/rejected promise from the async callback so you have to catch rejections locally.  So, in this code:

```<code>//ecouter la methode GET et la route
app.get('/', async(req,res) => {
    const indexHtml = await generatorModele('index')

    res.send(indexHtml)

})
</code>```

You aren't catching a rejection from generatorModele().  You can do that like this:

```<code>//ecouter la methode GET et la route
app.get('/', async(req,res) => {
    try {
        const indexHtml = await generatorModele('index');
        res.send(indexHtml);
    } catch(e) {
        console.log(e);
        res.sendStatus(500);
    }
});
</code>```

All, your other uses of await need something similar.

FYI, when you have a problem like this and the error message doesn't point exactly to the problem, the first thing to do is make sure you're catching and logging all possible errors.  This code I show above is one such example.

Title: UnhandledPromiseRejection

Body:
Hello guys i create a website and everything works locally but when i deployed in heroku its not working and i cant find why thanks for the help

heroku error:

2022-02-10T03:13:43.014545+00:00 app[web.1]: (node:22) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
2022-02-10T03:13:43.014570+00:00 app[web.1]: (node:22) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2022-02-10T03:14:13.009344+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/" host=websitechina.herokuapp.com request_id=ab93f3f6-9ccf-49e0-be7b-fe765239c47b fwd="61.219.114.7" dyno=web.1 connect=0ms service=30000ms status=503 bytes=0 protocol=https

index.js:

const express = require('express')
const app = express()
const port = process.env.port || 3000
const nodemailer = require('nodemailer')

//Importer la logique de la page d acceuil
const generatorModele = require('./api/page/page-get')

//ecouter la methode GET et la route
app.get('/', async(req,res) => {
    const indexHtml = await generatorModele('index')

    res.send(indexHtml)

})

app.get ('/tech', async(req,res) => {
    const techHtml = await generatorModele('tech')
    res.send(techHtml)
})

app.get ('/contact', async(req,res) => {
    const contactHtml = await generatorModele('contact')
    res.send(contactHtml)
})

app.get ('/signUp', async(req,res) => {
    const signUpHtml = await generatorModele('signUp')
    res.send(signUpHtml)
})

//ecouter la methode Post et la route
app.post('/', (req,res)=>{
    console.log(req.body)

    //nodemailer

    not working yet i know // const transporter =
      nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '',
            pass: ''
        }
    })

    transporter.sendMail(mailOptions, (error, info)=>{
        if(error){
            console.log(error)
            res.send('error')
        }else{
            console.log('Email sent' + info.response)
            res.send('success')
        }
    })

})

//ecoute les requete du repertoire styles,js,images/
app.use('/styles', express.static('/Users/hi/code/dotfiles/dev/websitechina1/styles'))
app.use('/images', express.static('/Users/hi/code/dotfiles/dev/websitechina1/images/'))
app.use('/js', express.static('/Users/hi/code/dotfiles/dev/websitechina1/js/'))
app.use(express.json())

//demarrer le  serveur et ecouter un port donne
app.listen(process.env.PORT || port,() => {
    console.log
    (`Example app listening on port ${port}`)
})

app.js

const menu = document.querySelector('#mobile-menu');
const menuLinks = document.querySelector('.navbar_menu');

menu.addEventListener('click', function(){
    menu.classList.toggle('is-active');
    menuLinks.classList.toggle('active');
});

const contactForm = document.querySelector('.contact-form')
let fname = document.getElementById('fname')
let lname = document.getElementById('lname')
let email = document.getElementById('email')
let country = document.getElementById('country')
let subject = document.getElementById('subject')

contactForm.addEventListener('submit', (e)=>{
    e.preventDefault();

    let formData = {
        fname: fname.value,
        lname: lname.value,
        email: email.value,
        country: country.value,
        subject: subject.value
    }

    let xhr = new XMLHttpRequest();
    xhr.open('POST', '/')
    xhr.setRequestHeader('content-type','application/json')
    xhr.onload = function(){
        console.log(xhr.responseText)
        if (xhr.responseText == 'success'){
          alert('Email sent');
          fname.value = '';
          lname.value = '';
          email.value =  '';
          country.value = '';
          subject.value = '';
        }else{
            alert('Something went wrong')
        }

    }
    xhr.send(JSON.stringify(formData))
})

Body:
All uses of await that can reject must be handled in some way.  They must either be surrounded by a try/catch or the caller of the async function must handle the rejection.

In this case, app.get() does not pay any attention to a returned/rejected promise from the async callback so you have to catch rejections locally.  So, in this code:

//ecouter la methode GET et la route
app.get('/', async(req,res) => {
    const indexHtml = await generatorModele('index')

    res.send(indexHtml)

})

You aren't catching a rejection from generatorModele().  You can do that like this:

//ecouter la methode GET et la route
app.get('/', async(req,res) => {
    try {
        const indexHtml = await generatorModele('index');
        res.send(indexHtml);
    } catch(e) {
        console.log(e);
        res.sendStatus(500);
    }
});

All, your other uses of await need something similar.

FYI, when you have a problem like this and the error message doesn't point exactly to the problem, the first thing to do is make sure you're catching and logging all possible errors.  This code I show above is one such example.


问:
How delete item from more one lists by using one for loop
I working in employee application. l enter employees _id,employees _name and employees department.l need to delete employee by using one for loop and all information about one employee is deleting just if l enter his name.like this

```<code>Emp_name=[]
Emp_id=[]
Emp_dep=[]
num=5
for n in emp_name:
 x =input("enter the name of employees")
 emp_name.append(x)
for n in emp_id:
 i =input("enter the name of employees")
 emp_name.append(i)

for n in emp_name:
 d =input("enter the name of employees")
 emp_name.append(d)
delete=input(" enter the of employee tou need to delete")
For n in emp_name:
  if delete==emp_name:
   emp_name.remove(n)
   emp_id.remove(n)
   emp_department.remove(n)
</code>```

This is just delete his name ,l need to delete his id and his department if l just enter his name

答:
The code you have given had lots of error, I'm assuming you wanted to use only 1 for loop for inserting elements.
This will be the code</p>
```<code>Emp_name = []
Emp_id = []
Emp_dep = []
num = 5
for i in range(num):
    x = input("enter the name of employees")
    Emp_name.append(x)

    i = input("enter the id of employees")
    Emp_id.append(i)

    d = input("enter the department of employees")
    Emp_dep.append(d)
delete = str(input(" Enter the name of employee you need to delete"))
if delete in Emp_name:
    pos = Emp_name.index(delete)
    Emp_name.pop(pos)
    Emp_id.pop(pos)
    Emp_dep.pop(pos)

print(Emp_name)
print(Emp_id)
print(Emp_dep)
</code>```

Body:
I working in employee application. l enter employees _id,employees _name and employees department.l need to delete employee by using one for loop and all information about one employee is deleting just if l enter his name.like this

Emp_name=[]
Emp_id=[]
Emp_dep=[]
num=5
for n in emp_name:
 x =input("enter the name of employees")
 emp_name.append(x)
for n in emp_id:
 i =input("enter the name of employees")
 emp_name.append(i)

for n in emp_name:
 d =input("enter the name of employees")
 emp_name.append(d)
delete=input(" enter the of employee tou need to delete")
For n in emp_name:
  if delete==emp_name:
   emp_name.remove(n)
   emp_id.remove(n)
   emp_department.remove(n)

This is just delete his name ,l need to delete his id and his department if l just enter his name

Body:
The code you have given had lots of error, I'm assuming you wanted to use only 1 for loop for inserting elements.
This will be the code

Emp_name = []
Emp_id = []
Emp_dep = []
num = 5
for i in range(num):
    x = input("enter the name of employees")
    Emp_name.append(x)

    i = input("enter the id of employees")
    Emp_id.append(i)

    d = input("enter the department of employees")
    Emp_dep.append(d)
delete = str(input(" Enter the name of employee you need to delete"))
if delete in Emp_name:
    pos = Emp_name.index(delete)
    Emp_name.pop(pos)
    Emp_id.pop(pos)
    Emp_dep.pop(pos)

print(Emp_name)
print(Emp_id)
print(Emp_dep)


问:
Heroku successfully deplots node.js + react.js project but I got an "Application error" page
Heroku says it successfully deployed my app but when I visit the page it says "application error" I tested my app in visual studio and it works fine there.
Here is my node.js code

//code based off of:
// https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9

const express = require('express');
const request = require('request');

const app = express();
const apiKey = 'api-key';
const PORT = process.env.PORT || 5000;

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

if(process.env.NODE_ENV === 'production'){
    app.use(express.static('build'));
    app.get('*', (req, res) =>{
        req.sendFile(path.resolve(__dirname, 'build','index.html'))
    })
}

app.get('/getCoinInfo', (req, res) => {
  console.log('The request has been received!!')
  request(
    { url: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=' + apiKey},
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }

      res.json(JSON.parse(body));
    }
  )
});

app.listen(PORT, () => console.log(`listening on ${PORT}`));```
</div>
</div>
</p>
<p>Here is also my Json File</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>{
  "name": "cryptoreactv2",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:5000",
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "cors": "^2.8.5",
    "express": "^4.17.2",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "request": "^2.88.2",
    "serve": "^13.0.2",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "startOLD": "node app",
    "startOLD": "react-scripts start",
    "dev": "react-scripts start",
    "start": "serve -s build",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "heroku-postbuild": "npm run build"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
}</code>```

I tried looking at different tutorials but nothing appears to work. Again, my app works in visual studio but not in Heroku.

答: After taking a short break, I realized that I had a Procfile that was not needed, so I deleted in and pushed the new changes onto Heroku.</p>

Body:
Heroku says it successfully deployed my app but when I visit the page it says "application error" I tested my app in visual studio and it works fine there.
Here is my node.js code

//code based off of:
// https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9

const express = require('express');
const request = require('request');

const app = express();
const apiKey = 'api-key';
const PORT = process.env.PORT || 5000;

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

if(process.env.NODE_ENV === 'production'){
    app.use(express.static('build'));
    app.get('*', (req, res) =>{
        req.sendFile(path.resolve(__dirname, 'build','index.html'))
    })
}

app.get('/getCoinInfo', (req, res) => {
  console.log('The request has been received!!')
  request(
    { url: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=' + apiKey},
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }

      res.json(JSON.parse(body));
    }
  )
});

app.listen(PORT, () => console.log(`listening on ${PORT}`));

Here is also my Json File

{
  "name": "cryptoreactv2",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:5000",
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "cors": "^2.8.5",
    "express": "^4.17.2",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "request": "^2.88.2",
    "serve": "^13.0.2",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "startOLD": "node app",
    "startOLD": "react-scripts start",
    "dev": "react-scripts start",
    "start": "serve -s build",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "heroku-postbuild": "npm run build"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
}

I tried looking at different tutorials but nothing appears to work. Again, my app works in visual studio but not in Heroku.


问:
Examples of compiled programming languages with modern features for the real world [please vote for reopen]
Apart from C, C++, Delphi, VB, can you put an example of a relatively "modern" COMPILED* programming language* supporting things like OO, collections, GUI libraries?
Please do not mention experimental or academic only languages, I'm looking for something used in the real world, for PCs 80x86, and I don't mind about the OS.

Thanks!

*UPDATED: Compiled to native code.

*DISCLAIMER:

For language understand language implementation.

For compiled to native code understand not interpreted.

答:
Cython. Compiles to native code, is used in high performance computing, both academic and commercial, and is used to implement LXML. GUI libraries include all those available for Python.

Also, Objective-C. That's now one of the most popular programming languages.


问:
What could be the reason for a webscraping timeout error?
I am trying to webscrape some legislative data using 'rvest' in R. I am trying to scrape data over several legislative sessions and so I have built code that has been running smoothly up until recent legislative sessions. Here is the code I have been using:

```<code>summary2 <- data.frame(matrix(nrow=2, ncol=4))
colnames(summary2) <- c("billnum", "sum", "type", "name_dis_part")
k <- sprintf('%0.4d', 2:9046)

for (i in k) {
  webpage <- read_html(paste0("https://www.hcdn.gob.ar/proyectos/textoCompleto.jsp?exp=", i, "-D-2016"))
  billno <- html_nodes(webpage, 'h1')
  billno_text <- html_text(billno)

  billsum <- html_nodes(webpage, '.interno')
  billsum_text <- html_text(billsum)

  billsum_text <- gsub("\n", "", billsum_text)
  billsum_text <- gsub("\t", "", billsum_text)
  billsum_text <- gsub("    ", "", billsum_text)

  link <- read_html(paste0("https://www.hcdn.gob.ar/proyectos/proyectoTP.jsp?exp=", i, "-D-2016"))
  type <- html_nodes(link, 'h3')
  type_text <- html_text(type)

  table <-html_node(link, "table.table.table-bordered tbody")

  table_text <- html_text(table)

  table_text <- gsub("\n", "", table_text)
  table_text <- gsub("\t", "", table_text)
  table_text <- gsub("", "", table_text)

  summary2[i, 1] <- billno_text
  summary2[i, 2] <- billsum_text
  summary2[i, 3] <- type_text
  summary2[i, 4] <- table_text
}

summary2$year <- 2016

write.csv(summary2,'2016-bills_cong_17.csv')
</code>```

I am running this as a loop to loop over individual pieces of legislation and it seems like randomly the code will stop working and I get the following error (or some variation of this error depending):

```<code>Error in open.connection(x, "rb") :
  Timeout was reached: [www.hcdn.gob.ar] Operation timed out after 1875835 milliseconds with 0 out of 0 bytes received
</code>```

It doesn't seem to be systematically stopping at a particular point or piece of legislation in the loop. I'm assuming this has something to do with the connection being lost to the website, although I've run this code on a computer with an Ethernet connection as well. I would really appreciate any help in debugging this and getting this code to work!

答: Its likely that you are hitting the website's servers to fast and you are getting blocked as a result for requesting too quickly. Try adding a Sys.sleep() between iterations and requests.

Body:
I am trying to webscrape some legislative data using 'rvest' in R. I am trying to scrape data over several legislative sessions and so I have built code that has been running smoothly up until recent legislative sessions. Here is the code I have been using:

summary2 <- data.frame(matrix(nrow=2, ncol=4))
colnames(summary2) <- c("billnum", "sum", "type", "name_dis_part")
k <- sprintf('%0.4d', 2:9046)

for (i in k) {
  webpage <- read_html(paste0("https://www.hcdn.gob.ar/proyectos/textoCompleto.jsp?exp=", i, "-D-2016"))
  billno <- html_nodes(webpage, 'h1')
  billno_text <- html_text(billno)

  billsum <- html_nodes(webpage, '.interno')
  billsum_text <- html_text(billsum)

  billsum_text <- gsub("\n", "", billsum_text)
  billsum_text <- gsub("\t", "", billsum_text)
  billsum_text <- gsub("    ", "", billsum_text)

  link <- read_html(paste0("https://www.hcdn.gob.ar/proyectos/proyectoTP.jsp?exp=", i, "-D-2016"))
  type <- html_nodes(link, 'h3')
  type_text <- html_text(type)

  table <-html_node(link, "table.table.table-bordered tbody")

  table_text <- html_text(table)

  table_text <- gsub("\n", "", table_text)
  table_text <- gsub("\t", "", table_text)
  table_text <- gsub("", "", table_text)

  summary2[i, 1] <- billno_text
  summary2[i, 2] <- billsum_text
  summary2[i, 3] <- type_text
  summary2[i, 4] <- table_text
}

summary2$year <- 2016

write.csv(summary2,'2016-bills_cong_17.csv')

I am running this as a loop to loop over individual pieces of legislation and it seems like randomly the code will stop working and I get the following error (or some variation of this error depending):

Error in open.connection(x, "rb") :
  Timeout was reached: [www.hcdn.gob.ar] Operation timed out after 1875835 milliseconds with 0 out of 0 bytes received

It doesn't seem to be systematically stopping at a particular point or piece of legislation in the loop. I'm assuming this has something to do with the connection being lost to the website, although I've run this code on a computer with an Ethernet connection as well. I would really appreciate any help in debugging this and getting this code to work!


问:
How to add custom tooltip to nivo chart?
I'm doing a stream chart with Nivo (nivo(.dot)rocks)) in react.js. How to customize the tooltip? The documentation doesn't talk about this point.</p>

答:
Maybe you can kick start by something like this</p>
```<code><ResponsiveLine
    data={data}
    tooltip={({ point }) => {
        return (
            <div
                style={{
                    background: 'white',
                    padding: '9px 12px',
                    border: '1px solid #ccc',
                }}
            >
                <div>x: {point.x}</div>
                <div>y: {point.y}</div>
            </div>
        )
    }}
/>
</code>```

Body:
Maybe you can kick start by something like this

<ResponsiveLine
    data={data}
    tooltip={({ point }) => {
        return (
            <div
                style={{
                    background: 'white',
                    padding: '9px 12px',
                    border: '1px solid #ccc',
                }}
            >
                <div>x: {point.x}</div>
                <div>y: {point.y}</div>
            </div>
        )
    }}
/>


问:
Checkbox classList Toggle
I'm trying to use a custom slider with an input type=checkbox to toggle between dark-mode and light-mode. It is not working with the javascript code I have.

var checkbox = document.getElementById('checkbox');
    checkbox.addEventListener('change', themeChange);

    function themeChange(){
      if (checkbox.checked == true){
        document.getElementById('body').classList.toggle('dark-mode');
      } else {
        document.getElementById('body').classList.toggle('light-mode');
      }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dark-mode {
      background-color: black;
      color: white;
    }

    .light-mode {
      background-color: white;
      color: black;
    }</code>```

       <input id="checkbox" type="checkbox" >

    ```

答:
toggle won't remove different the classes, you have to add and remove, please check the working code below.

var checkbox = document.getElementById('checkbox');
checkbox.addEventListener('change', themeChange);

function themeChange(){

  if (checkbox.checked == true){
    document.getElementById('body').classList.add('dark-mode');
    document.getElementById('body').classList.remove('light-mode');
  } else {
    document.getElementById('body').classList.add('light-mode');
    document.getElementById('body').classList.remove('dark-mode');
  }
} ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dark-mode {
  background-color: black;
  color: white;
}

.light-mode {
  background-color: white;
  color: black;
}</code>```

   <input id="checkbox" type="checkbox" >

    Theme switcher
```

Title: Checkbox classList Toggle

Body:
toggle won't remove different the classes, you have to add and remove, please check the working code below.

var checkbox = document.getElementById('checkbox');
checkbox.addEventListener('change', themeChange);

function themeChange(){

  if (checkbox.checked == true){
    document.getElementById('body').classList.add('dark-mode');
    document.getElementById('body').classList.remove('light-mode');
  } else {
    document.getElementById('body').classList.add('light-mode');
    document.getElementById('body').classList.remove('dark-mode');
  }
}

.dark-mode {
  background-color: black;
  color: white;
}

.light-mode {
  background-color: white;
  color: black;
}

<label class="switch">
   <input id="checkbox" type="checkbox" >
   <span class="slider round"></span>
</label>

<body id='body'>
    Theme switcher
</body>


问:
Why does mongoose.exec() not contain data from the query
I'm really confused what's going on here:

when I use the following code I get my expected product

```<code>  const newProd = await models.Product.findOne({_id: new Buffer(util.HexUUIDToBase64(newProductData._id), 'base64').toString('hex')})
    .populate({
      path: 'SellerID',
      populate: { path: 'UserID' }})
      console.log(newProd)
</code>```

However when I use this code then I get nothing for my product:

```<code> const newProd = await models.Product.findOne({_id: new Buffer(util.HexUUIDToBase64(newProductData._id), 'base64').toString('hex')})
    .populate({
      path: 'SellerID',
      populate: { path: 'UserID' }}).exec(function (err, product) {
        console.log(err)
        console.log(product)
      })
      console.log(newProd)
</code>```

I would expect my product to be passed to the callback but it's not. What exactly is going on here and how can I fix it?

答:
find() and exec() serve two different purposes.

The find() method is a database READ operation enabling function. It is present in both the native mongodb driver for node, as well as the Mongoose library which internally uses the mongodb drivers and is especially useful for imposing a fixed schema.

Now, in mongodb driver, if you use find(query), the query is automatically executed where as in mongoose it wouldn't. We need helper functions/ callbacks to get the operation to execute. exec is one such helper function. It goes something like:
myPlaylist.findOne({'singer':'Adam Levine'}).exec()

Mongoose queries are not promises. They have a .then() function for convenience.

If you need a fully-fledged promise, use the .exec() function.

So, you could do a myPlaylist.findOne({'singer':'Adam Levine'}).then() but that would return a Mongoose/BlueBird (yet another library) promise and a typical JavaScript one.

Note: exec() takes an optional callback function. It's only when you do not use a callback that you get back a Promise.

Body:
I'm really confused what's going on here:

when I use the following code I get my expected product

  const newProd = await models.Product.findOne({_id: new Buffer(util.HexUUIDToBase64(newProductData._id), 'base64').toString('hex')})
    .populate({
      path: 'SellerID',
      populate: { path: 'UserID' }})
      console.log(newProd)

However when I use this code then I get nothing for my product:

 const newProd = await models.Product.findOne({_id: new Buffer(util.HexUUIDToBase64(newProductData._id), 'base64').toString('hex')})
    .populate({
      path: 'SellerID',
      populate: { path: 'UserID' }}).exec(function (err, product) {
        console.log(err)
        console.log(product)
      })
      console.log(newProd)

I would expect my product to be passed to the callback but it's not. What exactly is going on here and how can I fix it?


问:
Assertion testing a void function
I am writing a code with multiple void methods within a class, I am tasked with testing all of my methods using the assert from the c++ header <cassert>.  Here is one of my methods, that goes through the array in the class and trims the leading and trailing blank spaces. How would I write a function to test this method using assert? I am confused because there is no return value.

```<code>void trim_all() {
    // Iterate through all strings
    for (int i = 0; i < strSize; i++) {
        // Initialize variables
        int begin = 0;
        int end = arr[i].size() - 1;
        // While loops to check how many spaces in front and back
        while (begin < arr[i].size() && arr[i][begin] == ' ') {
            begin++;
        }
        while (end >= 0 && arr[i][end] == ' ') {
            end--;
        }
        // Update string to trimmed version
        arr[i] = arr[i].substr(begin, end - begin + 1);
    }
}
</code>```

答:
based on the code's implementation,
you can check a result to fit with what the trim_all function do
in your case the function delete all space at begin and end or the arr var.
ex:
input :</p>
```<code>arr = "   abc  d  "
trim_all();
assert(arr == "abc  d");
</code>```

Title: Assertion testing a void function

Body:
I am writing a code with multiple void methods within a class, I am tasked with testing all of my methods using the assert from the c++ header <cassert>.  Here is one of my methods, that goes through the array in the class and trims the leading and trailing blank spaces. How would I write a function to test this method using assert? I am confused because there is no return value.

void trim_all() {
    // Iterate through all strings
    for (int i = 0; i < strSize; i++) {
        // Initialize variables
        int begin = 0;
        int end = arr[i].size() - 1;
        // While loops to check how many spaces in front and back
        while (begin < arr[i].size() && arr[i][begin] == ' ') {
            begin++;
        }
        while (end >= 0 && arr[i][end] == ' ') {
            end--;
        }
        // Update string to trimmed version
        arr[i] = arr[i].substr(begin, end - begin + 1);
    }
}

Body:
based on the code's implementation,
you can check a result to fit with what the trim_all function do
in your case the function delete all space at begin and end or the arr var.
ex:
input :

arr = "   abc  d  "
trim_all();
assert(arr == "abc  d");