问:
Getting Teams Calls returns Application not registered in our store
I'm struggling with Microsft Graph. I want to fetch Teams Calls from the graph API to throw them against our ticket software. Sounds easy at first. And I think it is but I don't get why it won't work.

Edit:
Just a heads up. I ended up using the Microsoft Graph subscription model.

To be clear, I don't want to create a teams app, I just want to fetch Teams Calls/Meetings.

This is my code (removed ID's for obvious reasons):

```<code>class Program
{
    // (Company IDs)
    static string tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    static string servicePrincipal = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    static string servicePrincipalKey = "keyyyyy";

    // Admin consent if not already applied
    // https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/adminconsent?client_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&state=randomState
    // In my case admin consent was given via azure portal for the following permissions:
    // Yes, it's too much. But I'm desperate...
    /* Microsoft Graph (10)
        CallRecords.Read.All
        Calls.AccessMedia.All
        ChannelMessage.Read.All
        Chat.Read.All
        IdentityProvider.Read.All
        OnlineMeetings.Read.All
        TeamsActivity.Read.All
        TeamsApp.Read.All
        User.Read.All
    */

    static string[] scopes = {
        "https://graph.microsoft.com/.default",
        //"https://graph.microsoft.com/CallRecords.Read.All" // doesn't work
        //"https://graph.microsoft.com/TeamsApp.Read.All" // doesn't work
        //"https://graph.microsoft.com/Chat.ReadWrite.All" // doesn't work
    };
    static async Task Main(string[] args)
    {

        var authority = $"https://login.microsoftonline.com/" + "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + "/v2.0";

        var clientConf = ConfidentialClientApplicationBuilder
            .Create(servicePrincipal)
            .WithAuthority(authority, true)
            .WithClientSecret(servicePrincipalKey)
            .Build();

        GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(async(requestMessage) =>
        {
            var authResult = await clientConf
                .AcquireTokenForClient(scopes)
                .ExecuteAsync();
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        }));

        //_ = graphClient.Teams.Request().GetAsync(); // Debug test

        // Trying to fetch all calls or meetings
        var onlineMeetings = await graphClient
            .Communications.Calls.Request().GetAsync(); // Doesn't work
        //.Users.Request().GetAsync(); // This works!
        //.Communications.OnlineMeetings.Request().GetAsync(); // Doesn't work

        Console.WriteLine(onlineMeetings);
        // If requesting users, this works without issues
        /*
        var count = 0;
        foreach (var user in onlineMeetings) {
            Console.WriteLine(count);
            Console.WriteLine(user.UserPrincipalName);
            count++;
        }
        */

    }
}
</code>```

When I run this mess I get the follwing error:

```<code>"Microsoft.Graph.ServiceException in System.Private.CoreLib.dll"
Code: UnknownError
{
  "errorCode":"7503",
   "message":"`**Application is not registered in our store.**`",
   "instanceAnnotations":[]
}
</code>```

Does anyone have an idea on what I'm doing wrong here?

Stacktrace

```<code>ClientRequestId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
    at Microsoft.Graph.HttpProvider.<SendAsync>d__18.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
    at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__35.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
    at Microsoft.Graph.BaseRequest.<SendAsync>d__31`1.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
    at Microsoft.Graph.CloudCommunicationsCallsCollectionRequest.<GetAsync>d__4.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
    at Teams_Graph.Program.<Main>d__4.MoveNext() in c:\Users\<user.name>\Documents\Development\C#\Teams-Graph\Program.cs: Line50
</code>```

答:
There isn't an API for listing all Calls or Meetings in an organization. You need to specify the id of the Call/Meeting you want:

```<code>var Calls = await graphClient
    .Communications
    .Calls["{call id}"]
    .Request()
    .GetAsync();

var onelineMeeting = await graphClient
    .Communications
    .OnlineMeetings["{meeting id"]
    .Request()
    .GetAsync();
</code>```

Body:
I'm struggling with Microsft Graph. I want to fetch Teams Calls from the graph API to throw them against our ticket software. Sounds easy at first. And I think it is but I don't get why it won't work.

Edit:
Just a heads up. I ended up using the Microsoft Graph subscription model.

To be clear, I don't want to create a teams app, I just want to fetch Teams Calls/Meetings.

This is my code (removed ID's for obvious reasons):

class Program
{
    // (Company IDs)
    static string tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    static string servicePrincipal = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    static string servicePrincipalKey = "keyyyyy";

    // Admin consent if not already applied
    // https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/adminconsent?client_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&state=randomState
    // In my case admin consent was given via azure portal for the following permissions:
    // Yes, it's too much. But I'm desperate...
    /* Microsoft Graph (10)
        CallRecords.Read.All
        Calls.AccessMedia.All
        ChannelMessage.Read.All
        Chat.Read.All
        IdentityProvider.Read.All
        OnlineMeetings.Read.All
        TeamsActivity.Read.All
        TeamsApp.Read.All
        User.Read.All
    */

    static string[] scopes = {
        "https://graph.microsoft.com/.default",
        //"https://graph.microsoft.com/CallRecords.Read.All" // doesn't work
        //"https://graph.microsoft.com/TeamsApp.Read.All" // doesn't work
        //"https://graph.microsoft.com/Chat.ReadWrite.All" // doesn't work
    };
    static async Task Main(string[] args)
    {

        var authority = $"https://login.microsoftonline.com/" + "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + "/v2.0";

        var clientConf = ConfidentialClientApplicationBuilder
            .Create(servicePrincipal)
            .WithAuthority(authority, true)
            .WithClientSecret(servicePrincipalKey)
            .Build();

        GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(async(requestMessage) =>
        {
            var authResult = await clientConf
                .AcquireTokenForClient(scopes)
                .ExecuteAsync();
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        }));

        //_ = graphClient.Teams.Request().GetAsync(); // Debug test

        // Trying to fetch all calls or meetings
        var onlineMeetings = await graphClient
            .Communications.Calls.Request().GetAsync(); // Doesn't work
        //.Users.Request().GetAsync(); // This works!
        //.Communications.OnlineMeetings.Request().GetAsync(); // Doesn't work

        Console.WriteLine(onlineMeetings);
        // If requesting users, this works without issues
        /*
        var count = 0;
        foreach (var user in onlineMeetings) {
            Console.WriteLine(count);
            Console.WriteLine(user.UserPrincipalName);
            count++;
        }
        */

    }
}

When I run this mess I get the follwing error:

"Microsoft.Graph.ServiceException in System.Private.CoreLib.dll"
Code: UnknownError
{
  "errorCode":"7503",
   "message":"`**Application is not registered in our store.**`",
   "instanceAnnotations":[]
}

Does anyone have an idea on what I'm doing wrong here?

Stacktrace

ClientRequestId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
    at Microsoft.Graph.HttpProvider.<SendAsync>d__18.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
    at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__35.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
    at Microsoft.Graph.BaseRequest.<SendAsync>d__31`1.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
    at Microsoft.Graph.CloudCommunicationsCallsCollectionRequest.<GetAsync>d__4.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
    at Teams_Graph.Program.d__4.MoveNext() in c:\Users\<user.name>\Documents\Development\C#\Teams-Graph\Program.cs: Line50

Body:
There isn't an API for listing all Calls or Meetings in an organization. You need to specify the id of the Call/Meeting you want:

var Calls = await graphClient
    .Communications
    .Calls["{call id}"]
    .Request()
    .GetAsync();

var onelineMeeting = await graphClient
    .Communications
    .OnlineMeetings["{meeting id"]
    .Request()
    .GetAsync();


来源: stackexchange

问:
ASP.NET Core SaveChangesAsync does not save everything
PROBLEM:

If I put SaveChangesAsync outside of the loop, it changes only the last data which was put with _context.Add(attdef);

Why is that so?

First I thought it's because I have autoIncrement, but when I disabled it, It still did not work.

Using  SaveChanges instead of SaveChangesAsync does not fix problem aswell.

But updating data works well.

GameController.cs

```<code>for (int i = 0; i < editViewModel.TowerAttack.Count; i++)
{
    tower = _context.Tower.First(m => m.TowerId == editViewModel.TowerId[i]);
    tower.Attack -= editViewModel.TowerAttack[i];
    _context.Update(tower);
    attdef.Id = 0; // AutoIncrement
    attdef.Amount = attackSum;
    _context.Add(attdef);
}

await _context.SaveChangesAsync();
</code>```

答:
Is attdef declared outside the loop?  Are you just updating the same object with each loop?  I would expect only the latest version of that object to be added if that's the case.

If you're trying to add several new objects, try declaring attdef within the loop so you're working with a new object each time.

ContentLicense: CC BY-SA 4.0

Body:
PROBLEM:

If I put SaveChangesAsync outside of the loop, it changes only the last data which was put with _context.Add(attdef);

Why is that so?

First I thought it's because I have autoIncrement, but when I disabled it, It still did not work.

Using  SaveChanges instead of SaveChangesAsync does not fix problem aswell.

But updating data works well.

GameController.cs

for (int i = 0; i < editViewModel.TowerAttack.Count; i++)
{
    tower = _context.Tower.First(m => m.TowerId == editViewModel.TowerId[i]);
    tower.Attack -= editViewModel.TowerAttack[i];
    _context.Update(tower);
    attdef.Id = 0; // AutoIncrement
    attdef.Amount = attackSum;
    _context.Add(attdef);
}

await _context.SaveChangesAsync();


问:
API Request from dictionary to CSV, line by line Python
This works for my issue below! If someone can help me, is there a better way to read the headers instead of hard-coding it. Since this is an API call, I'm thinking the request headers can change in API updates as its a fieldname.

```<code>#
class Csv:

    def __init__(self, JSONDict):
        self.JSONDict= JSONDict

    def json2csv(self):
        try:
            with open('test' + '.csv', 'w', newline='') as csv_file:
                fieldnames=['icao_address', 'timestamp', 'latitude', "longitude", "altitude_baro", "heading",
                "ground_speed", "vertical_rate",'squawk_code' ,"on_ground", "callsign",  "tail_number", "collection_type",
                "flight_number", "origin_airport_iata", "destination_airport_iata"]
                csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
                csv_writer.writeheader()
                for key in self.JSONDict:
                    for item in key:
                        csv_writer.writerow(key)
        except json.decoder.JSONDecodeError:
            pass

</code>```

In my return object from the API request I have 5,000 more of this, so this is an example.

```<code>{
  "target": {
    "icao_address": "0C208E",
    "timestamp": "2020-02-14T17:58:32Z",
    "latitude": -6.016251,
    "longitude": -60.300743,
    "altitude_baro": 36000,
    "heading": 300.0,
    "ground_speed": 480.0,
    "vertical_rate": 0,
    "on_ground": false,
    "callsign": "CMP215",
    "tail_number": "HP-1831CMP",
    "collection_type": "terrestrial",
    "flight_number": "CM215",
    "origin_airport_iata": "GIG",
    "destination_airport_iata": "PTY"
  }
}{
  "target": {
    "icao_address": "345042",
    "timestamp": "2020-02-14T17:58:35Z",
    "latitude": 43.70636,
    "longitude": 1.31352,
    "altitude_baro": 36000,
    "heading": 350.0,
    "ground_speed": 460.0,
    "vertical_rate": 0,
    "on_ground": false,
    "callsign": "VLG83WG",
    "tail_number": "EC-MHB",
    "collection_type": "terrestrial",
    "flight_number": "VY8306",
    "origin_airport_iata": "BCN",
    "destination_airport_iata": "AMS"
  }
}{
  "target": {
    "icao_address": "0200FB",
    "timestamp": "2020-02-14T17:58:35Z",
    "latitude": 38.503961,
    "longitude": -2.120789,
    "altitude_baro": 35000,
    "heading": 230.0,
    "ground_speed": 440.0,
    "vertical_rate": 0,
    "squawk_code": "5764",
    "on_ground": false,
    "callsign": "RAM931G",
    "tail_number": "CN-RGK",
    "collection_type": "terrestrial",
    "flight_number": "AT931",
    "origin_airport_iata": "GVA",
    "destination_airport_iata": "CMN"
  }
}{
  "target": {
    "icao_address": "E07246",
    "timestamp": "2020-02-14T17:58:37Z",
    "latitude": 40.860528,
    "longitude": 9.897371,
    "altitude_baro": 28475,
    "heading": 240.0,
    "ground_speed": 470.0,
    "vertical_rate": 640,
    "on_ground": false,
    "callsign": "ARG1141",
    "tail_number": "LV-GIF",
    "collection_type": "terrestrial",
    "flight_number": "AR1141",
    "origin_airport_iata": "FCO",
    "destination_airport_iata": "EZE"
  }
}{
  "target": {
    "icao_address": "AD1C11",
    "timestamp": "2020-02-14T17:58:37Z",
    "latitude": 40.209449,
    "longitude": -76.836631,
    "altitude_baro": 34000,
    "heading": 240.0,
    "ground_speed": 330.0,
    "on_ground": false,
    "callsign": "AAL1382",
    "tail_number": "N944AN",
    "collection_type": "terrestrial",
    "flight_number": "AA1382",
    "origin_airport_iata": "EWR",
    "destination_airport_iata": "DFW"
  }
}
</code>```

答:
You are close. Since you already have a list of dicts you can use csv.DictWriter.writerows for most of the work. You just need to pull the "target" subdictionary out of each. I trimmed your data down a bit for the example.

```<code>import csv

data = [{
  "target": {
    "icao_address": "0C208E",
    "timestamp": "2020-02-14T17:58:32Z",
    "latitude": -6.016251,
    "longitude": -60.300743,
  }
},{
  "target": {
    "icao_address": "345042",
    "timestamp": "2020-02-14T17:58:35Z",
    "latitude": 43.70636,
    "longitude": 1.31352,
  }
},{
  "target": {
    "icao_address": "0200FB",
    "timestamp": "2020-02-14T17:58:35Z",
    "latitude": 38.503961,
    "longitude": -2.120789,
  }
}
]

fieldnames = ["icao_address", "timestamp", "latitude", "longitude"]

with open("test.csv", "w", newline="") as csv_f:
    csv_writer = csv.DictWriter(csv_f, cols)
    csv_writer.writeheader()
    csv_writer.writerows(datum["target"] for datum in data)

print(open("test.csv").read())
</code>```

Body:
This works for my issue below! If someone can help me, is there a better way to read the headers instead of hard-coding it. Since this is an API call, I'm thinking the request headers can change in API updates as its a fieldname.

#
class Csv:

    def __init__(self, JSONDict):
        self.JSONDict= JSONDict

    def json2csv(self):
        try:
            with open('test' + '.csv', 'w', newline='') as csv_file:
                fieldnames=['icao_address', 'timestamp', 'latitude', "longitude", "altitude_baro", "heading",
                "ground_speed", "vertical_rate",'squawk_code' ,"on_ground", "callsign",  "tail_number", "collection_type",
                "flight_number", "origin_airport_iata", "destination_airport_iata"]
                csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
                csv_writer.writeheader()
                for key in self.JSONDict:
                    for item in key:
                        csv_writer.writerow(key)
        except json.decoder.JSONDecodeError:
            pass

In my return object from the API request I have 5,000 more of this, so this is an example.

{
  "target": {
    "icao_address": "0C208E",
    "timestamp": "2020-02-14T17:58:32Z",
    "latitude": -6.016251,
    "longitude": -60.300743,
    "altitude_baro": 36000,
    "heading": 300.0,
    "ground_speed": 480.0,
    "vertical_rate": 0,
    "on_ground": false,
    "callsign": "CMP215",
    "tail_number": "HP-1831CMP",
    "collection_type": "terrestrial",
    "flight_number": "CM215",
    "origin_airport_iata": "GIG",
    "destination_airport_iata": "PTY"
  }
}{
  "target": {
    "icao_address": "345042",
    "timestamp": "2020-02-14T17:58:35Z",
    "latitude": 43.70636,
    "longitude": 1.31352,
    "altitude_baro": 36000,
    "heading": 350.0,
    "ground_speed": 460.0,
    "vertical_rate": 0,
    "on_ground": false,
    "callsign": "VLG83WG",
    "tail_number": "EC-MHB",
    "collection_type": "terrestrial",
    "flight_number": "VY8306",
    "origin_airport_iata": "BCN",
    "destination_airport_iata": "AMS"
  }
}{
  "target": {
    "icao_address": "0200FB",
    "timestamp": "2020-02-14T17:58:35Z",
    "latitude": 38.503961,
    "longitude": -2.120789,
    "altitude_baro": 35000,
    "heading": 230.0,
    "ground_speed": 440.0,
    "vertical_rate": 0,
    "squawk_code": "5764",
    "on_ground": false,
    "callsign": "RAM931G",
    "tail_number": "CN-RGK",
    "collection_type": "terrestrial",
    "flight_number": "AT931",
    "origin_airport_iata": "GVA",
    "destination_airport_iata": "CMN"
  }
}{
  "target": {
    "icao_address": "E07246",
    "timestamp": "2020-02-14T17:58:37Z",
    "latitude": 40.860528,
    "longitude": 9.897371,
    "altitude_baro": 28475,
    "heading": 240.0,
    "ground_speed": 470.0,
    "vertical_rate": 640,
    "on_ground": false,
    "callsign": "ARG1141",
    "tail_number": "LV-GIF",
    "collection_type": "terrestrial",
    "flight_number": "AR1141",
    "origin_airport_iata": "FCO",
    "destination_airport_iata": "EZE"
  }
}{
  "target": {
    "icao_address": "AD1C11",
    "timestamp": "2020-02-14T17:58:37Z",
    "latitude": 40.209449,
    "longitude": -76.836631,
    "altitude_baro": 34000,
    "heading": 240.0,
    "ground_speed": 330.0,
    "on_ground": false,
    "callsign": "AAL1382",
    "tail_number": "N944AN",
    "collection_type": "terrestrial",
    "flight_number": "AA1382",
    "origin_airport_iata": "EWR",
    "destination_airport_iata": "DFW"
  }
}

Body:
You are close. Since you already have a list of dicts you can use csv.DictWriter.writerows for most of the work. You just need to pull the "target" subdictionary out of each. I trimmed your data down a bit for the example.

import csv

data = [{
  "target": {
    "icao_address": "0C208E",
    "timestamp": "2020-02-14T17:58:32Z",
    "latitude": -6.016251,
    "longitude": -60.300743,
  }
},{
  "target": {
    "icao_address": "345042",
    "timestamp": "2020-02-14T17:58:35Z",
    "latitude": 43.70636,
    "longitude": 1.31352,
  }
},{
  "target": {
    "icao_address": "0200FB",
    "timestamp": "2020-02-14T17:58:35Z",
    "latitude": 38.503961,
    "longitude": -2.120789,
  }
}
]

fieldnames = ["icao_address", "timestamp", "latitude", "longitude"]

with open("test.csv", "w", newline="") as csv_f:
    csv_writer = csv.DictWriter(csv_f, cols)
    csv_writer.writeheader()
    csv_writer.writerows(datum["target"] for datum in data)

print(open("test.csv").read())


问:
Taking the last five digits of a number from user input in REACT.jsx
Basically, I am currently using this.props.x (which is the user input) to get information from another page. So this.props.x is a number, for example "12345 12345 54321" in three groups of 5 digits. I want to replace the first 10 digits with asterisks and keep the last 5 digits. How do I manipulate this.props.x in such a way that I can make this possible?

Thanks.

This is what I've tried.

```<code>{this.props.x ? (
              <p>
                Card number: <br />
                {"***** *****" + this.props.x}
              </p>
            ) : (
              ""
            )
</code>```

I want the end result to look like
***** ***** 54321

答:
you can use fill function too :

```<code>let arr = "123451234554321".split("");
 arr = arr.fill("*" , 0 , 10).join("");

console.log(res);
</code>```

and the output is :

```<code>**********54321
</code>```

Body:
Basically, I am currently using this.props.x (which is the user input) to get information from another page. So this.props.x is a number, for example "12345 12345 54321" in three groups of 5 digits. I want to replace the first 10 digits with asterisks and keep the last 5 digits. How do I manipulate this.props.x in such a way that I can make this possible?

Thanks.

This is what I've tried.

{this.props.x ? (

                Card number:

                {"***** *****" + this.props.x}

            ) : (
              ""
            )

I want the end result to look like
***** ***** 54321

Body:
you can use fill function too :

let arr = "123451234554321".split("");
 arr = arr.fill("*" , 0 , 10).join("");

console.log(res);

and the output is :

**********54321


问:
How to authenticate React Native user by React Web page?
In our company we decided that we will not use separate Login/Register/ChangePassword forms for React Weband React Native and we will rather make React Web forms once and them reuse them in React Native.

This means that user of Native app clicks on Login button and default browser is opened to log in. After successfull login, user is redirected back into Native app as alrady logged.

I think this is very common in Hybrid Native apps, but I not found any docs how to achieve this in React Native.

Can anybody help me with quick example or redirect me to some docs/post?

答:
You could use react-native-webview to open the company login url, and pass a injectedJavascript props to WebView component that when the user is logged in you get the elements with user's data(Ex: getElementById("userName")) and close WebView redirecting user back to the app.

Extra Information here;

WebView props here so you can know how to control it.


问:
Call a function from within another function in Python without using class
I'm stuck at calling one function from within other function. I know this question was asked many time here but I couldnt find the right answer.

Here's an example:

Make a function shout(word) that accepts a string and returns that string in capital letters.

```<code>def shout(word):

    return word.upper()

shout("bob")
</code>```

Make a function introduce() to ask the user for their name and shout it back to them. Call your function shout to make this happen.

```<code>def introduce():

    name = input("What's your name: ")
    print(f"Hello {name}")

introduce()
</code>```

My question is: How can I call shout() func from within introduce() func without using class? So the result looks like this:

```<code>What's your name?
Bob

HELLO BOB
</code>```

Thank you for your time and answers.

答:
You can just call shout() function inside introduce():</p>

```<code>def shout(word):
    return word.upper()

def introduce():
    name = input("What's your name: ")
    print(shout(f"Hello {name}")) << just like this.
</code>```

Body:
I'm stuck at calling one function from within other function. I know this question was asked many time here but I couldnt find the right answer.

Here's an example:

Make a function shout(word) that accepts a string and returns that string in capital letters.

def shout(word):

    return word.upper()

shout("bob")

Make a function introduce() to ask the user for their name and shout it back to them. Call your function shout to make this happen.

def introduce():

    name = input("What's your name: ")
    print(f"Hello {name}")

introduce()

My question is: How can I call shout() func from within introduce() func without using class? So the result looks like this:

What's your name?
Bob

HELLO BOB

Thank you for your time and answers.

Body:
You can just call shout() function inside introduce():

def shout(word):
    return word.upper()

def introduce():
    name = input("What's your name: ")
    print(shout(f"Hello {name}")) << just like this.


问:
How to Specify an IP Address for TcpClient to use
During development, we usually use localhost as the hostname, like the following

```<code> Dim serverListener As New TcpClient("localhost", 8585)
</code>```

I want the user to be able to enter their IP address via a TextBox instead, like

```<code>Dim serverListener As New TcpClient(textbox1.text, 8585)
</code>```

However, this is not working for me. Any ideas? Thanks!

答:
Perhaps this will help?

You can also use IPAdress.TryParse() to check if its a valid adress

ContentLicense: CC BY-SA 3.0

Body:
During development, we usually use localhost as the hostname, like the following

 Dim serverListener As New TcpClient("localhost", 8585)

I want the user to be able to enter their IP address via a TextBox instead, like

Dim serverListener As New TcpClient(textbox1.text, 8585)

However, this is not working for me. Any ideas? Thanks!


问:
How to query date with a column name in SQL?
how do I query just the date and not the time from the stored data?
I have tried the following:

```<code>select FirstName, dob from table1 where rno='123';
</code>```

What I require is dob returns just the date along with a column name, so I can use the value later in a c# .net project. Also, is it possible to change the format of the date? How do I customize it to DD-MM-YYYY or YYYY-MM-DD?

答:
If you want to remove the time for privacy issues (which I don't think is the case), you can cast it to DATE.

```<code>select FirstName, CAST(dob as DATE) AS dob from table1 where rno='123';
</code>```

If not, I would take the date as-is from SQL to C#, and only do the formatting in the View. Avoid DATE_FORMAT and converting to string. This way, you can:

Do date manipulation: e.g. date add

Do date comparison or calculation: e.g. older than x?

Sort

Convert to users' local format.

etc.

If you convert it to string in SQL, in most instances, you will end up converting it back to DateTime class from the string, if not right now, in 5 years when the scope of your project increases.

Body:
how do I query just the date and not the time from the stored data?
I have tried the following:

select FirstName, dob from table1 where rno='123';

What I require is dob returns just the date along with a column name, so I can use the value later in a c# .net project. Also, is it possible to change the format of the date? How do I customize it to DD-MM-YYYY or YYYY-MM-DD?

Body:
If you want to remove the time for privacy issues (which I don't think is the case), you can cast it to DATE.

select FirstName, CAST(dob as DATE) AS dob from table1 where rno='123';

If not, I would take the date as-is from SQL to C#, and only do the formatting in the View. Avoid DATE_FORMAT and converting to string. This way, you can:

Do date manipulation: e.g. date add

Do date comparison or calculation: e.g. older than x?

Sort

Convert to users' local format.

etc.

If you convert it to string in SQL, in most instances, you will end up converting it back to DateTime class from the string, if not right now, in 5 years when the scope of your project increases.


问:
Cannot execute Python script via Jenkins
I'm trying to execute a script via Jenkins,but getting the below error.

```<code>17:11:49 Started by user jenkins_admin
17:11:49 Running as SYSTEM
17:11:49 Building in workspace /Users/it/.jenkins/workspace/pla
17:11:49 [pla] $ /bin/sh -xe /var/folders/t2/sk1vw_mn7mz7ncjw75lzh7r40000gn/T/jenkins414219605931315887.sh
17:11:49 + export PYTHONPATH=:/Users/it/Downloads/
17:11:49 + PYTHONPATH=:/Users/it/Downloads/
17:11:49 + cd /Users/it/Downloads/
17:11:49 + python3 P_execution.py
17:11:49 /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'P_execution.py': [Errno 1] Operation not permitted
17:11:49 Build step 'Execute shell' marked build as failure
17:11:49 Finished: FAILURE
</code>```

Below is the statement given in JENKINS build section

```<code>export PYTHONPATH=$PYTHONPATH:/Users/it/Downloads/
cd /Users/it/Downloads/
python3 P_execution.py
</code>```

Can anyone please let me know how i can resolve it.

答:
Your shell export statement has a syntax error. You want this:

```<code>export PYTHONPATH=${PYTHONPATH:-"/Users/it/Downloads/"}
</code>```

This will use the default PYTHONPATH if set, or will set it to "/Users/it/Downloads/".

Body:
I'm trying to execute a script via Jenkins,but getting the below error.

17:11:49 Started by user jenkins_admin
17:11:49 Running as SYSTEM
17:11:49 Building in workspace /Users/it/.jenkins/workspace/pla
17:11:49 [pla] $ /bin/sh -xe /var/folders/t2/sk1vw_mn7mz7ncjw75lzh7r40000gn/T/jenkins414219605931315887.sh
17:11:49 + export PYTHONPATH=:/Users/it/Downloads/
17:11:49 + PYTHONPATH=:/Users/it/Downloads/
17:11:49 + cd /Users/it/Downloads/
17:11:49 + python3 P_execution.py
17:11:49 /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'P_execution.py': [Errno 1] Operation not permitted
17:11:49 Build step 'Execute shell' marked build as failure
17:11:49 Finished: FAILURE

Below is the statement given in JENKINS build section

export PYTHONPATH=$PYTHONPATH:/Users/it/Downloads/
cd /Users/it/Downloads/
python3 P_execution.py

Can anyone please let me know how i can resolve it.

Body:
Your shell export statement has a syntax error. You want this:

export PYTHONPATH=${PYTHONPATH:-"/Users/it/Downloads/"}

This will use the default PYTHONPATH if set, or will set it to "/Users/it/Downloads/".


问:
text-file manipulation in bash
so I have this file that contains some data. that I use to create a graph using graphviz.
the problem is that I need to open a file and put a curly braces at the end and beginning of the file. I also write digraph before the opening braces.

than run my script to create the graph.

```<code>cat data.txt | dot -Tpng > image.png
</code>```

The problem is that I would like to automate the first step and add digraph { at the begining and }  at the end withing my script that create the graph.

答:
Using sed:

```<code>printf 'digraph {\n}\n' | sed '1r data.txt' | dot -Tpng > image.png
</code>```

Rather than adding text around your files contents, you inject your files contents into the wrapper.

Title: text-file manipulation in bash

Body:
so I have this file that contains some data. that I use to create a graph using graphviz.
the problem is that I need to open a file and put a curly braces at the end and beginning of the file. I also write digraph before the opening braces.

than run my script to create the graph.

cat data.txt | dot -Tpng > image.png

The problem is that I would like to automate the first step and add digraph { at the begining and }  at the end withing my script that create the graph.

Body:
Using sed:

printf 'digraph {\n}\n' | sed '1r data.txt' | dot -Tpng > image.png

Rather than adding text around your files contents, you inject your files contents into the wrapper.


问:
void is an invalid type for the variable onListItemClick?
I've been trying to set up a simple onClickListener on an android activity which extends ListActivity.

Within this classes on create method, I create a spinner object which when a user selects an item, an arrayAdapter list item is created, depending on what the user selected (populated from a cursor request). This is generated within another method within the same class.

```<code>ArrayAdapter<String> playerAdapter = new ArrayAdapter<String>(this,
            R.layout.match_update_rows, R.id.player_name, playerItems);

    setListAdapter(playerAdapter);
</code>```

I'm trying to add a click listener on this new list. I have added:

```<code>    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, PlayerFixtureScore.class);
        i.putExtra("RowId", id);
        startActivity(i);
    }
</code>```

However, I'm getting an error on the protected void onListItemClick line.

```<code>Multiple markers at this line
- Syntax error on token ")", ; expected
- Syntax error on token ",", ; expected
- Duplicate local variable position
- Syntax error on token ",", ; expected
- Duplicate local variable id
- Duplicate local variable l
- Syntax error on token "(", ; expected
- Duplicate local variable v
- Syntax error on token ",", ; expected
- void is an invalid type for the variable
 onListItemClick
</code>```

Also, if I select the onListItemClick line, Eclipse says 'void is an invalid type for the variable onListItemClick'?

All works if I remove the click listener code, just cannot work out how to add the listener on the arrayAdapter item so I can tell which item the user has clicked on -- any help appreciated!

As requested by MyD - here is the complete class listing:
    Thanks for your prompt responses. In reply to MByD here is the complete code listing for this class. Any suggestions appreciated!

```<code>public class MatchUpdate extends ListActivity {
/** Called when the activity is first created. */
private int cursorCounter = 0;
private int spinnerSelected;
/** Set up the db for inital use */
DataBaseHelper myDbHelper = new DataBaseHelper(this);
Match match;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.match_update);

    try {
        myDbHelper.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }
    try {
        myDbHelper.openDataBase();
    } catch (SQLException sqle) {
        throw sqle;
    }

    // create a spinner for fixture selection
    Spinner fixtureSpin = (Spinner) findViewById(R.id.fixtures);

    // Get all fixtures for Spinner...
    Cursor cur = myDbHelper.getFixtures();

    // create match object for cursor results
    match = new Match(cur.getCount());

    // Populate match object with Cursor results
    for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
        match.setFixtureId(cursorCounter, cur.getInt(0));
        match.setHomeId(cursorCounter, cur.getInt(1));
        match.setHomeTeam(cursorCounter, cur.getString(2));
        match.setAwayId(cursorCounter, cur.getInt(3));
        match.setAwayTeam(cursorCounter, cur.getString(4));
        match.setDate(cursorCounter, cur.getString(5));
        cursorCounter++;
    }

    // Set up adapters for fixture spinner
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, match.getFixtureList());

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Set up fixture spinner
    fixtureSpin.setAdapter(adapter);

    // Set fixture spinner listener
    fixtureSpin.setOnItemSelectedListener(new MyOnItemSelectedListener());

}

public class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos,
            long id) {
        spinnerSelected = parent.getSelectedItemPosition();
        updatePlayers(match);
    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Do nothing.
    }
}

public void updatePlayers(Match thisMatch) {

    // Get players for selected fixture based on Spinner selection
    Cursor playerCur = myDbHelper.getFixturePlayers(
            thisMatch.getHomeId(spinnerSelected),
            thisMatch.getAwayId(spinnerSelected));

    // set up simple ArrayAdapter to hold player names
    String[] playerItems;
    playerItems = new String[playerCur.getCount()];
    int cnt = 0;

    // pull player data from cursor, into a simple array
    for (playerCur.moveToFirst(); !playerCur.isAfterLast(); playerCur
            .moveToNext()) {
        playerItems[cnt] = playerCur.getString(0);
        cnt++;

    }

    ArrayAdapter<String> playerAdapter = new ArrayAdapter<String>(this,
            R.layout.match_update_rows, R.id.player_name, playerItems);

    setListAdapter(playerAdapter);

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, PlayerFixtureScore.class);
        i.putExtra("RowId", id);
        startActivity(i);
    }
}

}
</code>```

答: Method declarations need to be made in the context of a class definition.  When trying to declare a method inside another method, errors similar to this are reported.</p>

Body:
I've been trying to set up a simple onClickListener on an android activity which extends ListActivity.

Within this classes on create method, I create a spinner object which when a user selects an item, an arrayAdapter list item is created, depending on what the user selected (populated from a cursor request). This is generated within another method within the same class.

ArrayAdapter<String> playerAdapter = new ArrayAdapter<String>(this,
            R.layout.match_update_rows, R.id.player_name, playerItems);

    setListAdapter(playerAdapter);

I'm trying to add a click listener on this new list. I have added:

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, PlayerFixtureScore.class);
        i.putExtra("RowId", id);
        startActivity(i);
    }

However, I'm getting an error on the protected void onListItemClick line.

Multiple markers at this line
- Syntax error on token ")", ; expected
- Syntax error on token ",", ; expected
- Duplicate local variable position
- Syntax error on token ",", ; expected
- Duplicate local variable id
- Duplicate local variable l
- Syntax error on token "(", ; expected
- Duplicate local variable v
- Syntax error on token ",", ; expected
- void is an invalid type for the variable
 onListItemClick

Also, if I select the onListItemClick line, Eclipse says 'void is an invalid type for the variable onListItemClick'?

All works if I remove the click listener code, just cannot work out how to add the listener on the arrayAdapter item so I can tell which item the user has clicked on -- any help appreciated!

As requested by MyD - here is the complete class listing:
    Thanks for your prompt responses. In reply to MByD here is the complete code listing for this class. Any suggestions appreciated!

public class MatchUpdate extends ListActivity {
/** Called when the activity is first created. */
private int cursorCounter = 0;
private int spinnerSelected;
/** Set up the db for inital use */
DataBaseHelper myDbHelper = new DataBaseHelper(this);
Match match;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.match_update);

    try {
        myDbHelper.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }
    try {
        myDbHelper.openDataBase();
    } catch (SQLException sqle) {
        throw sqle;
    }

    // create a spinner for fixture selection
    Spinner fixtureSpin = (Spinner) findViewById(R.id.fixtures);

    // Get all fixtures for Spinner...
    Cursor cur = myDbHelper.getFixtures();

    // create match object for cursor results
    match = new Match(cur.getCount());

    // Populate match object with Cursor results
    for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
        match.setFixtureId(cursorCounter, cur.getInt(0));
        match.setHomeId(cursorCounter, cur.getInt(1));
        match.setHomeTeam(cursorCounter, cur.getString(2));
        match.setAwayId(cursorCounter, cur.getInt(3));
        match.setAwayTeam(cursorCounter, cur.getString(4));
        match.setDate(cursorCounter, cur.getString(5));
        cursorCounter++;
    }

    // Set up adapters for fixture spinner
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, match.getFixtureList());

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Set up fixture spinner
    fixtureSpin.setAdapter(adapter);

    // Set fixture spinner listener
    fixtureSpin.setOnItemSelectedListener(new MyOnItemSelectedListener());

}

public class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos,
            long id) {
        spinnerSelected = parent.getSelectedItemPosition();
        updatePlayers(match);
    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Do nothing.
    }
}

public void updatePlayers(Match thisMatch) {

    // Get players for selected fixture based on Spinner selection
    Cursor playerCur = myDbHelper.getFixturePlayers(
            thisMatch.getHomeId(spinnerSelected),
            thisMatch.getAwayId(spinnerSelected));

    // set up simple ArrayAdapter to hold player names
    String[] playerItems;
    playerItems = new String[playerCur.getCount()];
    int cnt = 0;

    // pull player data from cursor, into a simple array
    for (playerCur.moveToFirst(); !playerCur.isAfterLast(); playerCur
            .moveToNext()) {
        playerItems[cnt] = playerCur.getString(0);
        cnt++;

    }

    ArrayAdapter<String> playerAdapter = new ArrayAdapter<String>(this,
            R.layout.match_update_rows, R.id.player_name, playerItems);

    setListAdapter(playerAdapter);

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, PlayerFixtureScore.class);
        i.putExtra("RowId", id);
        startActivity(i);
    }
}

}


问:
@ViewChild not working after upgrading to Angular 9
After upgrading to Angular 9, basically all my @ViewChild references are not initialized anymore.

No matter what,

<app-menu-editor #menuEditor>
</app-menu-editor>

```

<pre class="lang-js prettyprint-override"><code>@ViewChild('menuEditor', {read: MenuEditorComponent}) menuEditor: MenuEditorComponent;

@ViewChild('cardBody', {read: ElementRef}) cardBody: ElementRef;
</code>```

I keep getting exceptions telling me that e.g. menuEditor is undefined.

Any idea why this is not working anymore?

答:
Try

```<code>@ViewChild('menuEditor', {static: true, read: MenuEditorComponent}) menuEditor: MenuEditorComponent;

@ViewChild('cardBody', {static: true, read: ElementRef}) cardBody: ElementRef;
</code>```

Like PierreDuc said, maybe you're referring to them in the ngOnInit.

Body:
After upgrading to Angular 9, basically all my @ViewChild references are not initialized anymore.

No matter what,

<app-menu-editor #menuEditor>
</app-menu-editor>

@ViewChild('menuEditor', {read: MenuEditorComponent}) menuEditor: MenuEditorComponent;

@ViewChild('cardBody', {read: ElementRef}) cardBody: ElementRef;

I keep getting exceptions telling me that e.g. menuEditor is undefined.

Any idea why this is not working anymore?

Body:
Try

@ViewChild('menuEditor', {static: true, read: MenuEditorComponent}) menuEditor: MenuEditorComponent;

@ViewChild('cardBody', {static: true, read: ElementRef}) cardBody: ElementRef;

Like PierreDuc said, maybe you're referring to them in the ngOnInit.


问:
Flutter json Decoding _TypeError (type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>')
So this error I understand kind of what it is, and WHAT I need to do, but I don't understands HOW to do what I'm trying to do.

So I'm using an html api server-call, which returns a jsonEncoded List of Map objects.

The size of each list CAN (and will) change, so I cannot have a function that just checks and decodes the first few or something.  Also each Map object may contain different information, so I can't go making it parse statically.  I need to jsonDecode the entire list, and convert it BACK into a list of separate Map objects so I can use the information contained within the Map objects within the rest of my program.

For privacy reasons, I CANNOT provide an example of the type of object I'm receiving, (Or anything similar) and I apologize for the inconvenience, and increased difficulty of attempting to answer the question.

That said, I do know I just need to have a function that checks how many objects are in the list, splits the response.body into that many pieces, decodes each into a Map  object, and adds it to a list, or array.

Any information you can provide (Even if not specific code) would help, even if just telling me what commands I should look into.  (Preferably with an example of their syntax, but not mandatory of course).

If you need any information that I CAN provide, I'll be happy to do so. Thank you in advance.

答:
The problem with your question is that we do not know even the general structure of your incoming data. We as a community do not need to know an actual example. Even faked data would suffice.

That being said, I will try to give you some examples of what your incoming data may be, and how you do what you are trying to do.

Incoming JSON Object

Lets say your incoming data looks like this:

```<code>{
  "data1": {
    "subdata1":"subvalue1",
    "subdata2":"subvalue2",
    "subdata3":3,
    "subdata4":{
      "subsubdata1":"subvalue1"
    }
  },
  "data2": {
    "subdata1":"subvalue1",
    "subdata2":"subvalue2",
    "subdata3":3,
    "subdata4":{
      "subsubdata1":"subvalue1"
    }
  }
}
</code>```

In this case you can use jsonDecode, and still be able to count the keys and return the associated list of objects like this:

```<code>void consumeResponse(http.Response response) {
  // decode the entire response string
  final Map<String, dynamic> rawObject = jsonDecode(response.body);

  // count the records in the response
  final int recordCount = rawObject.keys.length;

  // create an array of the data in each top level object key (but you lose the top level key name)
  final List<dynamic> records = List<dynamic>.from(rawObject.values);
}
</code>```

Incoming JSON Array of Objects

Lets say your json is actually in a json array already, and that your response looks like this:

```<code>[
  {
    "data1": {
      "subdata1":"subvalue1",
      "subdata2":"subvalue2",
      "subdata3":3,
      "subdata4":{
        "subsubdata1":"subvalue1"
      }
    }
  },
  {
    "data2": {
      "subdata1":"subvalue1",
      "subdata2":"subvalue2",
      "subdata3":3,
      "subdata4":{
        "subsubdata1":"subvalue1"
      }
    }
  }
]
</code>```

Then you can accomplish the same thing with this function:

```<code>void consumeResponse(http.Response response) {
  // decode the entire response string. this will auto-magically produce a List<dynamic>
  final List<dynamic> records = jsonDecode(response.body);

  // count the records in the response
  final int recordCount = records.length;
}
</code>```

Incoming JSON Object with sub-list of data

In some cases, you may have a list of results embedded in a wrapping json object that also contains some additional meta about your query. In that case your data might look like this:

```<code>{
  "meta": {
    "limit": 2,
    "offset": 1,
    "total": 47
  },
  "results": [
    {
      "data1": {
        "subdata1":"subvalue1",
        "subdata2":"subvalue2",
        "subdata3":3,
        "subdata4":{
          "subsubdata1":"subvalue1"
        }
      }
    },
    {
      "data2": {
        "subdata1":"subvalue1",
        "subdata2":"subvalue2",
        "subdata3":3,
        "subdata4":{
          "subsubdata1":"subvalue1"
        }
      }
    }
  ]
}
</code>```

In this case you may want to run the same function on the sub-list in the key results. You can use a similar function to do that too:

```<code>void consumeResponse(http.Response response) {
  // decode the entire response string
  final Map<String, dynamic> rawObject = jsonDecode(response.body);

  // create the List<dynamic> from the results list in the sub object
  final List<dynamic> records = rawObject['results'];

  // count the records in the response
  final int recordCount = records.length;
}
</code>```

Closing

Hopefully, even though your question is quite vague, at least one of these scenarios is something that you can use. It is always better, if you can, to create some "mock data" and/or "mock code" that you can share. This community uses all available data to build their answers. The more data you provide us, the better of an answer you will get.

Body:
The problem with your question is that we do not know even the general structure of your incoming data. We as a community do not need to know an actual example. Even faked data would suffice.

That being said, I will try to give you some examples of what your incoming data may be, and how you do what you are trying to do.

Incoming JSON Object

Lets say your incoming data looks like this:

{
  "data1": {
    "subdata1":"subvalue1",
    "subdata2":"subvalue2",
    "subdata3":3,
    "subdata4":{
      "subsubdata1":"subvalue1"
    }
  },
  "data2": {
    "subdata1":"subvalue1",
    "subdata2":"subvalue2",
    "subdata3":3,
    "subdata4":{
      "subsubdata1":"subvalue1"
    }
  }
}

In this case you can use jsonDecode, and still be able to count the keys and return the associated list of objects like this:

void consumeResponse(http.Response response) {
  // decode the entire response string
  final Map<String, dynamic> rawObject = jsonDecode(response.body);

  // count the records in the response
  final int recordCount = rawObject.keys.length;

  // create an array of the data in each top level object key (but you lose the top level key name)
  final List<dynamic> records = List<dynamic>.from(rawObject.values);
}

Incoming JSON Array of Objects

Lets say your json is actually in a json array already, and that your response looks like this:

[
  {
    "data1": {
      "subdata1":"subvalue1",
      "subdata2":"subvalue2",
      "subdata3":3,
      "subdata4":{
        "subsubdata1":"subvalue1"
      }
    }
  },
  {
    "data2": {
      "subdata1":"subvalue1",
      "subdata2":"subvalue2",
      "subdata3":3,
      "subdata4":{
        "subsubdata1":"subvalue1"
      }
    }
  }
]

Then you can accomplish the same thing with this function:

void consumeResponse(http.Response response) {
  // decode the entire response string. this will auto-magically produce a List<dynamic>
  final List<dynamic> records = jsonDecode(response.body);

  // count the records in the response
  final int recordCount = records.length;
}

Incoming JSON Object with sub-list of data

In some cases, you may have a list of results embedded in a wrapping json object that also contains some additional meta about your query. In that case your data might look like this:

{
  "meta": {
    "limit": 2,
    "offset": 1,
    "total": 47
  },
  "results": [
    {
      "data1": {
        "subdata1":"subvalue1",
        "subdata2":"subvalue2",
        "subdata3":3,
        "subdata4":{
          "subsubdata1":"subvalue1"
        }
      }
    },
    {
      "data2": {
        "subdata1":"subvalue1",
        "subdata2":"subvalue2",
        "subdata3":3,
        "subdata4":{
          "subsubdata1":"subvalue1"
        }
      }
    }
  ]
}

In this case you may want to run the same function on the sub-list in the key results. You can use a similar function to do that too:

void consumeResponse(http.Response response) {
  // decode the entire response string
  final Map<String, dynamic> rawObject = jsonDecode(response.body);

  // create the List<dynamic> from the results list in the sub object
  final List<dynamic> records = rawObject['results'];

  // count the records in the response
  final int recordCount = records.length;
}

Closing

Hopefully, even though your question is quite vague, at least one of these scenarios is something that you can use. It is always better, if you can, to create some "mock data" and/or "mock code" that you can share. This community uses all available data to build their answers. The more data you provide us, the better of an answer you will get.


问:
How to export a mySql database to a embedded database (for example H2)?
We have been working on a project. In the beginning we had some database issues, so we used a mySQL-server database to work around this.

Now we really should get back to an embedded database, access is out of the question (has to be cross-platform)

Our mentor suggested using an H2 embedded database, but we our sql-dump is getting syntax errors if we try to run it in the console of H2.

Any thoughts?
Thanks in advance!

答:
The SQL script generated by MySQL is made to run against MySQL. It contains options and features that other databases don't support. </p>

<p>As described in a related question, you could try creating the dump using the compatibility option. But you may still need to fix problems manually. </p>

Body:
The SQL script generated by MySQL is made to run against MySQL. It contains options and features that other databases don't support.

As described in a related question, you could try creating the dump using the compatibility option. But you may still need to fix problems manually.


问:
Using Scripting Dictionary to store Objects in MS Access to avoid circular references and allow forms to know their owner objects
I’m building an Access database with classes e.g clsOrder, clsCustomer etc which manage the interface with tables. These classes create instances of forms when displaying their data. I found that once the execution of code was within one of these forms I couldn’t refer to the parent object that created it (so is there a better way of doing this? would be part of my question).

To deal with this I’m using a scripting dictionary to store instances of classes with a key using the ID of the class and a unique identifier for the class (e.g Order-3265). I then store a reference to the owner object in the form itself.

So when an object is created and its ID is known it puts a pointer to itself in the dictionary and gives that pointer to its form (hope that’s clear enough).

This then allows the form to interact with its owner class.

I’m using another class clsManager to do the adding of items to the Dictionary or retrieval or removal (with destruction).

Examples of classes - seriously cut down..

clsManager:

```<code>Public WorkingObjects As New Scripting.Dictionary

Public Function AddWorkingObject(key As String, ObjectType As Object) As Boolean
    If Me.WorkingObjects.Exists(key) Then
        Me.WorkingObjects.Remove key
        Me.WorkingObjects.Add key, ObjectType
    Else
        Me.WorkingObjects.Add key, ObjectType
    End If
End Function

Public Function GetWorkingObject(key As String) As Object
    If Me.WorkingObjects.Exists(key) Then
        Set GetWorkingObject = Me.WorkingObjects(key)
    Else
        Set GetWorkingObject = Nothing
    End If
End Function

Public Function DestroyObject(obj As Object) As Boolean
Dim key As String
    If Not obj Is Nothing Then
        key = obj.DictionaryKey
        If Me.WorkingObjects.Exists(key) Then
            Me.WorkingObjects.Remove (key)
            Set obj = Nothing
            If obj Is Nothing Then
                Debug.Print key & " destroyed"
            Else
                Debug.Print obj.DictionaryKey & " NOT destroyed"
            End If
        End If
        Set obj = Nothing
    End If
End Function
</code>```

clsQuote:

```<code>Option Compare Database
    Option Explicit

'use a form using an instance of this class to control manipulation of Quote records
'Loading and saving set default values if a null value is detected

Private Const scTABLE As String = "tblQuote"

Private intID As Long 'unique identifier
Private intCustomerID As Long
Private intSiteID As Long
Private rsQuoteTotalValues As DAO.Recordset
Private oCustomer As clsCustomer
Const ObjectType = "Quote-"
Private oEditForm As Form_frmQuote

Property Get EditForm() As Form_frmQuote
    Set EditForm = oEditForm
End Property

Property Get ID() As Long
    ID = intID
End Property
Property Let ID(QuoteID As Long)
    intID = QuoteID
    Me.EditForm.ID = QuoteID
End Property

Property Get Customer() As clsCustomer
    Set Customer = oCustomer
End Property

Property Let CustomerID(ID As Long)
    intCustomerID = ID
    oCustomer.Load (ID)
    EditForm.SiteID.RowSource = oCustomer.AddressSQL
    EditForm.SiteID.Requery
    EditForm.ContactID.RowSource = oCustomer.ContactsSQL
    EditForm.ContactID.Requery
    EditForm.CustomerID = ID
End Property

Property Get DictionaryKey() As String
    DictionaryKey = ObjectType & CStr(Me.ID)
End Property
'END PROPERTIES//////////////////////////////////

Public Sub DisplayForm(Visibility As Boolean)
    With Me.EditForm
        .Visible = False
        .subFrmQuoteSectionsSummary.SourceObject = ""
        If Visibility = True Then
            ...some stuff...
            .Visible = True
        End If
    End With
End Sub

Public Function Load(ID As Long) As Boolean
'On Error GoTo HandleError
Dim RS As DAO.Recordset
Dim sQry As String
    Load = False
    If Nz(ID, 0) <> 0 Then
        sQry = "SELECT * FROM " & scTABLE & " WHERE ([ID]=" & ID & ");"
        Set RS = Manager.DB().OpenRecordset(sQry, dbOpenForwardOnly)
            With RS
                If .RecordCount = 0 Then
                    MsgBox "Cannot find Quote with ID = " & ID, vbCritical
                    GoTo Done
                End If
                Me.ID = Nz(!ID, 0)
                Me.CustomerID = Nz(!CustomerID, 0)
                Manager.AddWorkingObject Me.DictionaryKey, Me
                Me.EditForm.SetOwnerObject (Me.DictionaryKey)
                .Close
            End With
        Set RS = Nothing
        Load = True
    End If
Done:
    Exit Function
HandleError:
    MsgBox "Error in Customer Load: " & vbCrLf & Err.Description, vbCritical
    Resume Done
End Function

Private Sub Class_Initialize()
    Debug.Print "Quote class initialized"
    Set oCustomer = New clsCustomer
    Set oEditForm = New Form_frmQuote
    Me.ID = 0
    Set oQuoteTidier = New clsClassTidier
    Me.DisplayForm (False)
End Sub

Private Sub Class_Terminate()
    Set oCustomer = Nothing
    Set oEditForm = Nothing
    Debug.Print "Quote class terminated"
End Sub
</code>```

From the EditForm:

```<code>Option Compare Database
Option Explicit

'necessary for the object to have a reference to its owner in this manner to prevent circular reference
Private OwnerObject As clsQuote

Public Function SetOwnerObject(OwnerKey As String) As Boolean
    SetOwnerObject = False
    Set OwnerObject = Manager.GetWorkingObject(OwnerKey)
    SetOwnerObject = True
End Function

Private Sub cmdClose_Click()
    OwnerObject.EditForm.Visible = False
    Manager.DestroyObject OwnerObject
    DoCmd.Close acForm, Me.Name
End Sub
</code>```

Each business object class (like ClsOrder) has an editForm instance which is loaded and hidden until required and a up to 3 DAO Recordsets that it keeps open.

I think all references to the business objects that are interrelated are pointers to the objects in the dictionary.

My problem is error 3035 exceeding system resources. I’ve checked objects are destroyed when not in use but repeatedly opening and closing objects gets me to error 3035.

So the question is- am I just asking Access to do stuff it can’t or would better programming fix it?

答:
I see ZERO reasons to write all that code. Why not let a form handle all of this? Remember, each form is in fact a "class" instance. You can even launch multiple copies of a single form, each with their own code, own data and each instance of the SAME form can operate 100% independent of other working copies of that same form.

If you attempting to look at this problem and wanting to have a class object for a form, then just use the form object - that's what it does for you!

I see zero benefits from writing all that code. While .net has the dataset manager and system (and now the very similar entity framework, this is MUCH done since .net does not have data bound forms.

In Access, each form is in fact a class object. And that includes any public sub or function for that form (so functions become methods of that form, and public vars become properties of that form). In addition to the bound form having a truckload events, these events work as actions against any data editing. So, unlike most systems, you have "on change" event, before update event, after update event. So, by simply adoptiing a bound form, then you get:
A class object is automatic created for you.
You can have multiple instances of that class, and hence multiple instances of that same form open at the same time.
You get all of those data events that can be used for verifiction of data input (or have the user not save the record until such time your critera is met.
You have full use of all data columns, even if controls are NOT placed on the form bound to those columns. So, you even get intel-sense for all of the data columns - that is you map.

I am not aware that there is some big huge circular reference problem here. This is like stubbing your toe, but then going to the doctor for some huge open heart by-pass operation. So to go on some huge massive coding spree, and chew up huge amounts of developer dollars for some "rare" issue of some kind of rare and un-seen circular reference issue is essentially a huge wild goose chase that will only have you chewing up huge amounts of developer code and time when NONE is required at all.

I mean, if you have say 3 instances of the SAME form open? Then how does the code know and refernce what insance of that form? Well, the EXACT same approac used in typical OO programming can and should be used here. That approach means you don't HARD CODE the forms! name or referances in code EVER. You never want to do this.

So, if you are in a sub form, and need to referacne say data or controls in the parent form?

You could do this:

strLastName = forms!frmCustomer!LastName

In above, we have hard coded the forms name. You don't want to do that.

In that subform, the correct way to write this code is:

strLastName = me.Parent.form!LastName

Now, note how the above referances the parent form. So, that code will work EVEN if we have 3 copies of the frmCustomer active at the same time. You can full refernce ANYTHING in a form by its object "instance". So, in JavaScrip, or c#, you often see "this.SomProperty" as a refeance to that object.

In access, you can do the same thing, and use "me". Or me.Parent.From to reference the parent form. So, as a general approach here, you should NEVER have to hard code forms reference. If you take this approach, then all issues of circular referencing will not only be eliminated, but then you are using a classic and traditional approach to object programming, and object referencing. While Access is not full OO, it certainly follows a lot of OO design concepts, and how forms work in Access are most certainly instances of a object.

Attempting to write truckloads of code when the forms object model already exists as a "single" class object instance of that form makes no sense, and is not required, and the road you going down will likely hamper and reduce your abilities to deal with the fantastic instance of that form you already have.

As noted, the form already has the dictionaly and columns attached, and Access EVEN generates the members for your automatic. The result is you can reference any column of the table that the form is bound to with

me.LastName
me!LastName

While the above two formats are allowed, the first (me + dot + column name) is in fact a member of the forms class. You will find that if you use code to set the forms data source, then often these members are NOT generated for you, and thus you have to use the ! (bang) to reference columns from the table for that form.

So, I don't grasp while you attempting all that extra code when the form has all of the abilities you are asking for in a class object.

Body:
I’m building an Access database with classes e.g clsOrder, clsCustomer etc which manage the interface with tables. These classes create instances of forms when displaying their data. I found that once the execution of code was within one of these forms I couldn’t refer to the parent object that created it (so is there a better way of doing this? would be part of my question).

To deal with this I’m using a scripting dictionary to store instances of classes with a key using the ID of the class and a unique identifier for the class (e.g Order-3265). I then store a reference to the owner object in the form itself.

So when an object is created and its ID is known it puts a pointer to itself in the dictionary and gives that pointer to its form (hope that’s clear enough).

This then allows the form to interact with its owner class.

I’m using another class clsManager to do the adding of items to the Dictionary or retrieval or removal (with destruction).

Examples of classes - seriously cut down..

clsManager:

Public WorkingObjects As New Scripting.Dictionary

Public Function AddWorkingObject(key As String, ObjectType As Object) As Boolean
    If Me.WorkingObjects.Exists(key) Then
        Me.WorkingObjects.Remove key
        Me.WorkingObjects.Add key, ObjectType
    Else
        Me.WorkingObjects.Add key, ObjectType
    End If
End Function

Public Function GetWorkingObject(key As String) As Object
    If Me.WorkingObjects.Exists(key) Then
        Set GetWorkingObject = Me.WorkingObjects(key)
    Else
        Set GetWorkingObject = Nothing
    End If
End Function

Public Function DestroyObject(obj As Object) As Boolean
Dim key As String
    If Not obj Is Nothing Then
        key = obj.DictionaryKey
        If Me.WorkingObjects.Exists(key) Then
            Me.WorkingObjects.Remove (key)
            Set obj = Nothing
            If obj Is Nothing Then
                Debug.Print key & " destroyed"
            Else
                Debug.Print obj.DictionaryKey & " NOT destroyed"
            End If
        End If
        Set obj = Nothing
    End If
End Function

clsQuote:

Option Compare Database
    Option Explicit

'use a form using an instance of this class to control manipulation of Quote records
'Loading and saving set default values if a null value is detected

Private Const scTABLE As String = "tblQuote"

Private intID As Long 'unique identifier
Private intCustomerID As Long
Private intSiteID As Long
Private rsQuoteTotalValues As DAO.Recordset
Private oCustomer As clsCustomer
Const ObjectType = "Quote-"
Private oEditForm As Form_frmQuote

Property Get EditForm() As Form_frmQuote
    Set EditForm = oEditForm
End Property

Property Get ID() As Long
    ID = intID
End Property
Property Let ID(QuoteID As Long)
    intID = QuoteID
    Me.EditForm.ID = QuoteID
End Property

Property Get Customer() As clsCustomer
    Set Customer = oCustomer
End Property

Property Let CustomerID(ID As Long)
    intCustomerID = ID
    oCustomer.Load (ID)
    EditForm.SiteID.RowSource = oCustomer.AddressSQL
    EditForm.SiteID.Requery
    EditForm.ContactID.RowSource = oCustomer.ContactsSQL
    EditForm.ContactID.Requery
    EditForm.CustomerID = ID
End Property

Property Get DictionaryKey() As String
    DictionaryKey = ObjectType & CStr(Me.ID)
End Property
'END PROPERTIES//////////////////////////////////

Public Sub DisplayForm(Visibility As Boolean)
    With Me.EditForm
        .Visible = False
        .subFrmQuoteSectionsSummary.SourceObject = ""
        If Visibility = True Then
            ...some stuff...
            .Visible = True
        End If
    End With
End Sub

Public Function Load(ID As Long) As Boolean
'On Error GoTo HandleError
Dim RS As DAO.Recordset
Dim sQry As String
    Load = False
    If Nz(ID, 0) <> 0 Then
        sQry = "SELECT * FROM " & scTABLE & " WHERE ([ID]=" & ID & ");"
        Set RS = Manager.DB().OpenRecordset(sQry, dbOpenForwardOnly)
            With RS
                If .RecordCount = 0 Then
                    MsgBox "Cannot find Quote with ID = " & ID, vbCritical
                    GoTo Done
                End If
                Me.ID = Nz(!ID, 0)
                Me.CustomerID = Nz(!CustomerID, 0)
                Manager.AddWorkingObject Me.DictionaryKey, Me
                Me.EditForm.SetOwnerObject (Me.DictionaryKey)
                .Close
            End With
        Set RS = Nothing
        Load = True
    End If
Done:
    Exit Function
HandleError:
    MsgBox "Error in Customer Load: " & vbCrLf & Err.Description, vbCritical
    Resume Done
End Function

Private Sub Class_Initialize()
    Debug.Print "Quote class initialized"
    Set oCustomer = New clsCustomer
    Set oEditForm = New Form_frmQuote
    Me.ID = 0
    Set oQuoteTidier = New clsClassTidier
    Me.DisplayForm (False)
End Sub

Private Sub Class_Terminate()
    Set oCustomer = Nothing
    Set oEditForm = Nothing
    Debug.Print "Quote class terminated"
End Sub

From the EditForm:

Option Compare Database
Option Explicit

'necessary for the object to have a reference to its owner in this manner to prevent circular reference
Private OwnerObject As clsQuote

Public Function SetOwnerObject(OwnerKey As String) As Boolean
    SetOwnerObject = False
    Set OwnerObject = Manager.GetWorkingObject(OwnerKey)
    SetOwnerObject = True
End Function

Private Sub cmdClose_Click()
    OwnerObject.EditForm.Visible = False
    Manager.DestroyObject OwnerObject
    DoCmd.Close acForm, Me.Name
End Sub

Each business object class (like ClsOrder) has an editForm instance which is loaded and hidden until required and a up to 3 DAO Recordsets that it keeps open.

I think all references to the business objects that are interrelated are pointers to the objects in the dictionary.

My problem is error 3035 exceeding system resources. I’ve checked objects are destroyed when not in use but repeatedly opening and closing objects gets me to error 3035.

So the question is- am I just asking Access to do stuff it can’t or would better programming fix it?


答:
I am guessing that you are getting undefined either within the ngOnInit hook or inside of the class constructor. If my guess is correct then here's your problem:

A view child becomes available within ngOnInit if you use the static: true option inside the @ViewChild decorator. If static: true option is not set, then your view child only becomes available in ngAfterViewInit. The static options is set to false by default.

This SO answer may also be of help.

Title: @ViewChild not working after upgrading to Angular 9


问:
Screening for duplicates in a tuple - Python
I am trying to create a function, non_duplicates(), that screens for duplicates for a given tuple x, and returns False if there is a duplicate, or returns True if there isn't any.

I am doing this by a for loop nested within another to iterate over the items twice to compare all the items with each other. I added a conditional that checks if the two items are equal, while their indices are not.

The problem is that the code is giving an equal index for different items for some reason, where I made sure that the index is linked with the iteration.

The answer for non_duplicates(((0,0),(0,0))) is the same as non_duplicates(((0,0),(5,5))), both are giving True while it should not for the former.

When I checked ((0,0),(0,0)), the indices are "0,0    0,0    0,0    0,0", while for ((0,0),(5,5)), the indices are "0,0    0,1    1,0    1,1".

That is why the condition are not being met.

def non_duplicates(x):
    y = 0
    for i, j in x:
        x1 = (i,j)
        for k, l in x:
            x2 = (k,l)
            if (x1 == x2 and x.index(x1) != x.index(x2)):
                y = y + 1
    y = y/len(x)
    if y == 0:
        answer = True
    if y > 0:
        answer = False
    return answer
```

答:
Here is an answer that uses the same logic as @Matt Shin's answer but also works for a tuple of tuples like your example show's you checking.

```<code>def non_duplicates(x):
    sorted_tuples = []
    for item in x:
        # sort every tuple in a tuple of tuples and returns a list of sorted tuples
        sorted_tuples.append(tuple(sorted(item)))

    # checks for duplicates using set
    return len(set(sorted_tuples)) == len(sorted_tuples)

print(non_duplicates(((0,0),(0,0))))

print(non_duplicates(((0,0),(5,5))))
</code>```

Or if your tuple of tuples is really large and you care deeply about computation time. You could check after every element you add.

```<code>def non_duplicates(x):
    sorted_tuples = set()
    for count, item in enumerate(x, 1):
        sorted_tuples.add(tuple(sorted(item)))
        if len(sorted_tuples) != count:
            return False

    return True
</code>```

Body:
Here is an answer that uses the same logic as @Matt Shin's answer but also works for a tuple of tuples like your example show's you checking.

def non_duplicates(x):
    sorted_tuples = []
    for item in x:
        # sort every tuple in a tuple of tuples and returns a list of sorted tuples
        sorted_tuples.append(tuple(sorted(item)))

    # checks for duplicates using set
    return len(set(sorted_tuples)) == len(sorted_tuples)

print(non_duplicates(((0,0),(0,0))))

print(non_duplicates(((0,0),(5,5))))

Or if your tuple of tuples is really large and you care deeply about computation time. You could check after every element you add.

def non_duplicates(x):
    sorted_tuples = set()
    for count, item in enumerate(x, 1):
        sorted_tuples.add(tuple(sorted(item)))
        if len(sorted_tuples) != count:
            return False

    return True


问:
Recursive data in JSON object
```<code>{
"groups": [
    {
        "name": "Event",
        "groups": [
            {
                "name": "Service",
                "subscriptions": [
                    {
                        "topic": "SERVICE_STATUS_PRESETS"
                    },
                    {
                        "topic": "AIRCRAFT_ACTIVATION",

                    },
                    {
                        "topic": "OUT_OF_SERVICE",

                    }
                ]
            }
        ]
    },
    {
        "name": "Enquiries",
        "groups": [
            {
                "name": "Service-related",
                "subscriptions": [
                    {

                        "topic": "PROMO_CODES_REQUESTS",

                    }
                ]
            }
        ]
    }
],
"subscriptions": [
    {
        "topic": "BANNERS",
    },
    {
        "topic": "DOCUMENTS",
    },
    {
        "topic": "USER",
    }
]
</code>```

}

OK guys I have such JSON structure what I need is to: return all topics in array, in this example it will be:

["SERVICE_STATUS_PRESETS", "AIRCRAFT_ACTIVATION", "OUT_OF_SERVICE", "PROMO_CODES_REQUESTS", "BANNERS", "DOCUMENTS", "USER"]

I try recursive calls like this, though I only get last three records:

```<code>getRecursive() {
if (Array.isArray(data)) {
       for (let i = 0; i < data.length; i++) {
         if (data[i].subscriptions) {
           return data[i].subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
         } else if (data[i].groups) {
           return this.getAllTopics(data[i].groups);
         }
       }
     }
     if (data && data.groups) {
      return this.getAllTopics(data.groups);
     }
     return data.subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
}
</code>```

答:
This version that takes a functional approach if you are interested. There are others above but this is just another way to look at it.</p>

```<code>const recursion = object => Object.entries(object).map(([a, b]) => {
  if (a === 'topic') return b;
  if (Array.isArray(b)) return b.map(recursion);
  return [];
}).flat(Infinity);

recursion(obj);
</code>```

Title: Recursive data in JSON object

Body:
{
"groups": [
    {
        "name": "Event",
        "groups": [
            {
                "name": "Service",
                "subscriptions": [
                    {
                        "topic": "SERVICE_STATUS_PRESETS"
                    },
                    {
                        "topic": "AIRCRAFT_ACTIVATION",

                    },
                    {
                        "topic": "OUT_OF_SERVICE",

                    }
                ]
            }
        ]
    },
    {
        "name": "Enquiries",
        "groups": [
            {
                "name": "Service-related",
                "subscriptions": [
                    {

                        "topic": "PROMO_CODES_REQUESTS",

                    }
                ]
            }
        ]
    }
],
"subscriptions": [
    {
        "topic": "BANNERS",
    },
    {
        "topic": "DOCUMENTS",
    },
    {
        "topic": "USER",
    }
]

}

OK guys I have such JSON structure what I need is to: return all topics in array, in this example it will be:

["SERVICE_STATUS_PRESETS", "AIRCRAFT_ACTIVATION", "OUT_OF_SERVICE", "PROMO_CODES_REQUESTS", "BANNERS", "DOCUMENTS", "USER"]

I try recursive calls like this, though I only get last three records:

getRecursive() {
if (Array.isArray(data)) {
       for (let i = 0; i < data.length; i++) {
         if (data[i].subscriptions) {
           return data[i].subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
         } else if (data[i].groups) {
           return this.getAllTopics(data[i].groups);
         }
       }
     }
     if (data && data.groups) {
      return this.getAllTopics(data.groups);
     }
     return data.subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
}

Body:
This version that takes a functional approach if you are interested. There are others above but this is just another way to look at it.

const recursion = object => Object.entries(object).map(([a, b]) => {
  if (a === 'topic') return b;
  if (Array.isArray(b)) return b.map(recursion);
  return [];
}).flat(Infinity);

recursion(obj);


问:
Get Selected Value of html dropdown in razor page dotnet
With the below code how can I get the value of the dropdown list using page handlers or tag helpers?

One way I've been reading is using OnChange on the dropdown, I can set the value of a hidden field with javascript then get value of hidden field from code behind. Should I even be using page handlers/tag helpers to get the dropdown value?

I have tried using Request.Form["networks"] but this just gives the ID and not the Value.

```<code><form method="post">
     @Html.DropDownList("networks",
     Model.GetNetworks().Select(s => new SelectListItem()
     {
         Text = s.networks,
         Value = s.id.ToString(),
     }),
     new
     {
        @class = "dropdown form-control",
     })
     <input type="hidden" id="selectedwifivalue" />
     <br />
     <input type="text" placeholder="enter wifi password" asp-for="Password" class="input-sm form-control" />
     <br />
     <button asp-page-handler="submit" class="btn btn-primary btn-sm form-control">Submit</button>
</form>
</code>```

Model is

```<code>public class WifiNetworks
{
    public int id { get; set; }
    public string networks { get; set; }
    public IEnumerable<SelectListItem> UserNetworks { get; set; }
}
</code>```

Code behind in cshtml file

```<code>[BindProperty]
public string Password { get; set; }
public string networks { get; set; }
public void OnPostSubmit()
{
    {
        var password = Request.Form["password"];
        var network = Request.Form["networks"]; <--this just gives the ID and not the value
        var wifi = networks;  <---this is blank
    }
}
</code>```

答:
In the end I could have done it using ajax but using the hidden field approach it works fine like below no idea if this is a good/bad/better way to do this (I seemed to be asking those questions quite alot)

get value of dropdown using jquery "change" function (keep this outside of the

$(document).ready function as it wont fire)

```<code>    $('#dnetworks').change(function () {

        var selectedwifi = $('#networks option:selected').text();

        $('#hiddenselectedwifivalue').val(selectedwifi); //set value of hidden field

});
</code>```

Razor page

```<code><input type="hidden" id="hiddenselectedwifivalue" asp-for="WifiNetworks.networks" />
</code>```

.cshtml file

```<code>  var selectedwififromdd = WifiNetworks.networks;
</code>```

I used the bind for the whole class in the model page (.cshtml file)

```<code>  public class WifiModel : PageModel
    {
        [BindProperty] public WifiNetworks WifiNetworks { get; set; }
</code>```

Body:
With the below code how can I get the value of the dropdown list using page handlers or tag helpers?

One way I've been reading is using OnChange on the dropdown, I can set the value of a hidden field with javascript then get value of hidden field from code behind. Should I even be using page handlers/tag helpers to get the dropdown value?

I have tried using Request.Form["networks"] but this just gives the ID and not the Value.

<form method="post">
     @Html.DropDownList("networks",
     Model.GetNetworks().Select(s => new SelectListItem()
     {
         Text = s.networks,
         Value = s.id.ToString(),
     }),
     new
     {
        @class = "dropdown form-control",
     })
     <input type="hidden" id="selectedwifivalue" />

     <input type="text" placeholder="enter wifi password" asp-for="Password" class="input-sm form-control" />

     <button asp-page-handler="submit" class="btn btn-primary btn-sm form-control">Submit</button>
</form>

Model is

public class WifiNetworks
{
    public int id { get; set; }
    public string networks { get; set; }
    public IEnumerable<SelectListItem> UserNetworks { get; set; }
}

Code behind in cshtml file

[BindProperty]
public string Password { get; set; }
public string networks { get; set; }
public void OnPostSubmit()
{
    {
        var password = Request.Form["password"];
        var network = Request.Form["networks"]; <--this just gives the ID and not the value
        var wifi = networks;  <---this is blank
    }
}

Body:
In the end I could have done it using ajax but using the hidden field approach it works fine like below no idea if this is a good/bad/better way to do this (I seemed to be asking those questions quite alot)

get value of dropdown using jquery "change" function (keep this outside of the

$(document).ready function as it wont fire)

    $('#dnetworks').change(function () {

        var selectedwifi = $('#networks option:selected').text();

        $('#hiddenselectedwifivalue').val(selectedwifi); //set value of hidden field

});

Razor page

<input type="hidden" id="hiddenselectedwifivalue" asp-for="WifiNetworks.networks" />

.cshtml file

  var selectedwififromdd = WifiNetworks.networks;

I used the bind for the whole class in the model page (.cshtml file)

  public class WifiModel : PageModel
    {
        [BindProperty] public WifiNetworks WifiNetworks { get; set; }


问:
signalling inside php
hi when implementing a connection that stays open for a long time ( comet ),
how would i implement signalling between php proses(outstanding requests)??

example timeline:

request 1 start

request 1 makes action

request 1 sleeps

request 2 start

request 2 makes action

request 2 notifies request 1 and go's to sleep

request 1 wakes up and sends the new data

request 1 sleeps agen

i was wandering if ther was a methode whitch use less(noting?) cpu prosessing

答:
ideally, I would write this with the requests or "jobs" for the purposes of this being written to a database.

script 1 does something and writes a "job" to the DB

script 1 sleeps for an interval, then checkes to see if there is a returncode for that job in the DB, if so then

act

else sleep/repeat

script 2 checks for uncompleted jobs in the DB

if so then

act and write returncode

else sleep/repeat

Title: signalling inside php


问:
React hook Search on button click not working
I need to get a list of repositories using GitHub API, search has to work on button click and on change selectBox with licences

```<code>import React, { useState, useEffect, useCallback } from "react";
import axios from "axios";
import moment from "moment";
import { Layout } from "./../Layout";
import { List } from "./../List";
import { Loader } from "./../Loader";
import { Header } from "./../Header";
import { Search } from "./../Search";
import { Licenses } from "./../Licenses";

import "./App.css";

export const App = () => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState(false);
  const [nameSearch, setNameSearch] = useState("");
  const [license, setLicense] = useState({});

  const fetchData = useCallback(async () => {
    setHasError(false);
    setIsLoading(true);

    try {
      const prevMonth = moment()
        .subtract(30, "days")
        .format("YYYY-MM-DD");

      const licenseKey = (license && license.key) || "";

      const response = await axios(
        `https://api.github.com/search/repositories?q=${nameSearch}+in:name+language:javascript+created:${prevMonth}${
          licenseKey ? `+license:${licenseKey}` : ""
        }&sort=stars&order=desc`
      );
      setData(response.data.items);
    } catch (error) {
      setHasError(true);
      setData([]);
    }
    setIsLoading(false);
  }, [license]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return (
    <Layout>
      <Header>
        <Search
          handleSearchChange={setNameSearch}
          nameSearch={nameSearch}
          isLoading={isLoading}
          onSearch={fetchData}
        />
        <Licenses license={license} handleLicenseChange={setLicense} />
      </Header>

      <main>
        {hasError && <div>Error</div>}

        {isLoading ? <Loader /> : <List data={data} />}
      </main>
    </Layout>
  );
};
</code>```

First of all, I get warning

Compiled with warnings.

./src/components/App/App.js

  Line 42:6:  React Hook useCallback has a missing dependency: 'nameSearch'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

And my search is not working because nameSearch is always empty in the query string.

How to make search work?

答:
Try adding nameSearch to the list of dependencies for useCallback:

```<code>const fetchData = useCallback(async () => {
  ...
}, [license, nameSearch]);
</code>```

and make sure setNameSearch is actually used inside Search.js so that it will have a value.

Body:
I need to get a list of repositories using GitHub API, search has to work on button click and on change selectBox with licences

import React, { useState, useEffect, useCallback } from "react";
import axios from "axios";
import moment from "moment";
import { Layout } from "./../Layout";
import { List } from "./../List";
import { Loader } from "./../Loader";
import { Header } from "./../Header";
import { Search } from "./../Search";
import { Licenses } from "./../Licenses";

import "./App.css";

export const App = () => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState(false);
  const [nameSearch, setNameSearch] = useState("");
  const [license, setLicense] = useState({});

  const fetchData = useCallback(async () => {
    setHasError(false);
    setIsLoading(true);

    try {
      const prevMonth = moment()
        .subtract(30, "days")
        .format("YYYY-MM-DD");

      const licenseKey = (license && license.key) || "";

      const response = await axios(
        `https://api.github.com/search/repositories?q=${nameSearch}+in:name+language:javascript+created:${prevMonth}${
          licenseKey ? `+license:${licenseKey}` : ""
        }&sort=stars&order=desc`
      );
      setData(response.data.items);
    } catch (error) {
      setHasError(true);
      setData([]);
    }
    setIsLoading(false);
  }, [license]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return (
    <Layout>

        <Search
          handleSearchChange={setNameSearch}
          nameSearch={nameSearch}
          isLoading={isLoading}
          onSearch={fetchData}
        />
        <Licenses license={license} handleLicenseChange={setLicense} />

        {hasError &&
Error
}

        {isLoading ? <Loader /> : <List data={data} />}

    </Layout>
  );
};

First of all, I get warning

Compiled with warnings.

./src/components/App/App.js

  Line 42:6:  React Hook useCallback has a missing dependency: 'nameSearch'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

And my search is not working because nameSearch is always empty in the query string.

How to make search work?

Body:
Try adding nameSearch to the list of dependencies for useCallback:

const fetchData = useCallback(async () => {
  ...
}, [license, nameSearch]);

and make sure setNameSearch is actually used inside Search.js so that it will have a value.


问:
Get Computed Height - Javascript - Not jQuery
I have two divs side by side set to height auto. I want them to have equal height, so i combined them as members of an array.

I recurse through the array and set the not-tallest ones to the height of the tallest. Problem is everything i have tried to get the COMPUTED height has resulted in the incorrect value.

I have tried the following:

```<code>(els[x].currentStyle) ? h=els[x].currentStyle.height : h=window.getComputedStyle(els[x],null).height;

h =  el.clientHeight || el.offsetHeight || el.scrollHeight;
</code>```

Both of these are yielding 640 px'ish while the computed is 751.8 in my particular showing.

Is there possbily a constant I can use to get the correct height. Like maybe the number im getting would be on a standard size screen (like 960 pixels high or such) then multiple that by the window size?

答:
If you have the DOM document, you can try the below code:</p>

```<code>let divElement = document.getElementById('divId');
let height = document.defaultView.getComputedStyle(divElement).height;
</code>```

<p>'height' will have the exact height of the element with 'divId' once it is computed. </p>

Body:
I have two divs side by side set to height auto. I want them to have equal height, so i combined them as members of an array.

I recurse through the array and set the not-tallest ones to the height of the tallest. Problem is everything i have tried to get the COMPUTED height has resulted in the incorrect value.

I have tried the following:

(els[x].currentStyle) ? h=els[x].currentStyle.height : h=window.getComputedStyle(els[x],null).height;

h =  el.clientHeight || el.offsetHeight || el.scrollHeight;

Both of these are yielding 640 px'ish while the computed is 751.8 in my particular showing.

Is there possbily a constant I can use to get the correct height. Like maybe the number im getting would be on a standard size screen (like 960 pixels high or such) then multiple that by the window size?

Body:
If you have the DOM document, you can try the below code:

let divElement = document.getElementById('divId');
let height = document.defaultView.getComputedStyle(divElement).height;

'height' will have the exact height of the element with 'divId' once it is computed.


问:
Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?
I have applied every solution available on internet but still I cannot run Docker.

I want to use Scrapy Splash on my server.

Here is history of commands I ran.

```<code>docker run -p 8050:8050 scrapinghub/splash
sudo docker run -p 8050:8050 scrapinghub/splash
sudo usermod -aG docker $(whoami)
sudo docker run -p 8050:8050 scrapinghub/splash
newgrp docker
sudo docker run -p 8050:8050 scrapinghub/splash
reboot
sudo docker run -p 8050:8050 scrapinghub/splash
docker run -p 8050:8050 scrapinghub/splash
</code>```

You can see I tried to restart my server as well, but it didnt help.

see output of ps -aux | grep docker

```<code>root@mani:/var/www/html# ps aux | grep docker
root      8524  0.0  0.8 127904 13964 ?        Ssl  17:21   0:00 /usr/bin/dockerd --raw-logs
root      8534  0.0  0.3  90588  5012 ?        Ssl  17:21   0:00 docker-containerd -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containerd --shim docker-containerd-shim --runtime docker-runc
root      8543  0.0  0.0   8812   764 pts/1    S+   17:21   0:00 grep --color=auto docker
root     16356  0.0  0.0  17200   964 pts/1    S    17:14   0:00 newgrp docker
root     20080  0.0  0.0  17200   964 pts/1    S    17:06   0:00 newgrp docker
root     30221  0.0  0.0  17200   964 pts/1    S    17:09   0:00 newgrp docker
</code>```

but it gives the error:

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.

答:
None of the current answers worked for my version of this error. I'm using the desktop version of Ubuntu 18. The following two commands fixed the issue.

sudo snap connect docker:home :home

sudo snap start docker

Body:
I have applied every solution available on internet but still I cannot run Docker.

I want to use Scrapy Splash on my server.

Here is history of commands I ran.

docker run -p 8050:8050 scrapinghub/splash
sudo docker run -p 8050:8050 scrapinghub/splash
sudo usermod -aG docker $(whoami)
sudo docker run -p 8050:8050 scrapinghub/splash
newgrp docker
sudo docker run -p 8050:8050 scrapinghub/splash
reboot
sudo docker run -p 8050:8050 scrapinghub/splash
docker run -p 8050:8050 scrapinghub/splash

You can see I tried to restart my server as well, but it didnt help.

see output of ps -aux | grep docker

root@mani:/var/www/html# ps aux | grep docker
root      8524  0.0  0.8 127904 13964 ?        Ssl  17:21   0:00 /usr/bin/dockerd --raw-logs
root      8534  0.0  0.3  90588  5012 ?        Ssl  17:21   0:00 docker-containerd -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containerd --shim docker-containerd-shim --runtime docker-runc
root      8543  0.0  0.0   8812   764 pts/1    S+   17:21   0:00 grep --color=auto docker
root     16356  0.0  0.0  17200   964 pts/1    S    17:14   0:00 newgrp docker
root     20080  0.0  0.0  17200   964 pts/1    S    17:06   0:00 newgrp docker
root     30221  0.0  0.0  17200   964 pts/1    S    17:09   0:00 newgrp docker

but it gives the error:

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.