问:
How to Serialize circular referenced object using JSON-B (Java API for JSON Binding)
I am using JSON-B for output object to json and there is a circular reference in the object (please do not ask me to remove the circular reference), sample code as follows

The Person class contains a list of Property
and the Property class reference back the person which form a circular reference.

In the first print the json can be output, however in the second print statement, stack overflow error due to touch the circular reference of the object, I do not want to use @JsonbTransient to ignore any of them, how can I solve this?

I am expecting the json output as

```<code>{"id":1,"name":"Jhon","propertyList":[{"person":1, "propertyName":"Palace"},{"person":1, "propertyName":"Apartment"}]}
</code>```

Sample Code:

```<code>import java.util.ArrayList;
import java.util.List;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;

public class JsonTest {

    public static void main(String[] args) throws InterruptedException {
        Person person = new Person(1, "Jhon");

        Jsonb jsonb = JsonbBuilder.create();

        //no error as no property is added
        System.out.println("jsonPerson without property: " + jsonb.toJson(person));

        Property p1 = new Property();
        p1.setPropertyName("Palace");
        p1.setPerson(person);

        Property p2 = new Property();
        p2.setPropertyName("Apartment");
        p2.setPerson(person);

        person.getPropertyList().add(p1);
        person.getPropertyList().add(p2);

        /**
         * stackoverflow here
         */
        System.out.println("jsonPerson with property: " + jsonb.toJson(person));
    }

    public static class Property {
        private Person person;
        private String propertyName;
        public Person getPerson() {
            return person;
        }
        public void setPerson(Person person) {
            this.person = person;
        }
        public String getPropertyName() {
            return propertyName;
        }
        public void setPropertyName(String propertyName) {
            this.propertyName = propertyName;
        }
    }

    public static class Person {

        private int id;

        public Person() {
            super();
        }

        public Person(int id, String name) {
            super();
            this.id = id;
            this.name = name;
        }

        private String name;

        private List<Property> propertyList = new ArrayList<>();

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<Property> getPropertyList() {
            return propertyList;
        }

        public void setPropertyList(List<Property> propertyList) {
            this.propertyList = propertyList;
        }

    }

}
</code>```

答:
Finally I give up using JSON-B and instead use Jackson, use the annotation @JsonIdentityInfo here is my solution for information:

```<code>import java.util.ArrayList;
import java.util.List;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonTest {

    private static Person person = null;
    private static List<Property> propertyList = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        person = new Person(1, "Jhon");
        propertyList.add(new Property(1, person, "Palace"));
        propertyList.add(new Property(2, person, "Apartment"));

        person.setPropertyList(propertyList);

        jacksonTest();
        //jsonbTest();
    }

    private static void jacksonTest()
    throws Exception
    {
        String result = new ObjectMapper().writeValueAsString(person);

        System.out.println("result: " + result);
    }

    private static void jsonbTest()
    throws Exception
    {
        Jsonb jsonb = JsonbBuilder.create();
        /**
         * stackoverflow here
         */
        System.out.println("jsonPerson with property: " + jsonb.toJson(person));
    }

    public static class Property extends BaseEntity {
        private Person person;
        private String propertyName;

        public Property(int id, Person person, String propertyName) {
            super();
            setId(id);
            this.person = person;
            this.propertyName = propertyName;
        }

        public Person getPerson() {
            return person;
        }
        public void setPerson(Person person) {
            this.person = person;
        }
        public String getPropertyName() {
            return propertyName;
        }
        public void setPropertyName(String propertyName) {
            this.propertyName = propertyName;
        }
    }

    public static class Person extends BaseEntity {
        public Person() {
            super();
        }

        public Person(int id, String name) {
            super();
            setId(id);
            this.name = name;
        }

        private String name;

        private List<Property> propertyList = new ArrayList<>();

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<Property> getPropertyList() {
            return propertyList;
        }

        public void setPropertyList(List<Property> propertyList) {
            this.propertyList = propertyList;
        }

    }

    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
    public static abstract class BaseEntity {
        private int id;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

    }
}
</code>```

Jackson output:

```<code>result: {"id":1,"name":"Jhon","propertyList":[{"id":1,"person":1,"propertyName":"Palace"},{"id":2,"person":1,"propertyName":"Apartment"}]}
</code>```

Body:
I am using JSON-B for output object to json and there is a circular reference in the object (please do not ask me to remove the circular reference), sample code as follows

The Person class contains a list of Property
and the Property class reference back the person which form a circular reference.

In the first print the json can be output, however in the second print statement, stack overflow error due to touch the circular reference of the object, I do not want to use @JsonbTransient to ignore any of them, how can I solve this?

I am expecting the json output as

{"id":1,"name":"Jhon","propertyList":[{"person":1, "propertyName":"Palace"},{"person":1, "propertyName":"Apartment"}]}

Sample Code:

import java.util.ArrayList;
import java.util.List;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;

public class JsonTest {

    public static void main(String[] args) throws InterruptedException {
        Person person = new Person(1, "Jhon");

        Jsonb jsonb = JsonbBuilder.create();

        //no error as no property is added
        System.out.println("jsonPerson without property: " + jsonb.toJson(person));

        Property p1 = new Property();
        p1.setPropertyName("Palace");
        p1.setPerson(person);

        Property p2 = new Property();
        p2.setPropertyName("Apartment");
        p2.setPerson(person);

        person.getPropertyList().add(p1);
        person.getPropertyList().add(p2);

        /**
         * stackoverflow here
         */
        System.out.println("jsonPerson with property: " + jsonb.toJson(person));
    }

    public static class Property {
        private Person person;
        private String propertyName;
        public Person getPerson() {
            return person;
        }
        public void setPerson(Person person) {
            this.person = person;
        }
        public String getPropertyName() {
            return propertyName;
        }
        public void setPropertyName(String propertyName) {
            this.propertyName = propertyName;
        }
    }

    public static class Person {

        private int id;

        public Person() {
            super();
        }

        public Person(int id, String name) {
            super();
            this.id = id;
            this.name = name;
        }

        private String name;

        private List<Property> propertyList = new ArrayList<>();

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<Property> getPropertyList() {
            return propertyList;
        }

        public void setPropertyList(List<Property> propertyList) {
            this.propertyList = propertyList;
        }

    }

}

Body:
Finally I give up using JSON-B and instead use Jackson, use the annotation @JsonIdentityInfo here is my solution for information:

import java.util.ArrayList;
import java.util.List;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonTest {

    private static Person person = null;
    private static List<Property> propertyList = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        person = new Person(1, "Jhon");
        propertyList.add(new Property(1, person, "Palace"));
        propertyList.add(new Property(2, person, "Apartment"));

        person.setPropertyList(propertyList);

        jacksonTest();
        //jsonbTest();
    }

    private static void jacksonTest()
    throws Exception
    {
        String result = new ObjectMapper().writeValueAsString(person);

        System.out.println("result: " + result);
    }

    private static void jsonbTest()
    throws Exception
    {
        Jsonb jsonb = JsonbBuilder.create();
        /**
         * stackoverflow here
         */
        System.out.println("jsonPerson with property: " + jsonb.toJson(person));
    }

    public static class Property extends BaseEntity {
        private Person person;
        private String propertyName;

        public Property(int id, Person person, String propertyName) {
            super();
            setId(id);
            this.person = person;
            this.propertyName = propertyName;
        }

        public Person getPerson() {
            return person;
        }
        public void setPerson(Person person) {
            this.person = person;
        }
        public String getPropertyName() {
            return propertyName;
        }
        public void setPropertyName(String propertyName) {
            this.propertyName = propertyName;
        }
    }

    public static class Person extends BaseEntity {
        public Person() {
            super();
        }

        public Person(int id, String name) {
            super();
            setId(id);
            this.name = name;
        }

        private String name;

        private List<Property> propertyList = new ArrayList<>();

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<Property> getPropertyList() {
            return propertyList;
        }

        public void setPropertyList(List<Property> propertyList) {
            this.propertyList = propertyList;
        }

    }

    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
    public static abstract class BaseEntity {
        private int id;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

    }
}

Jackson output:

result: {"id":1,"name":"Jhon","propertyList":[{"id":1,"person":1,"propertyName":"Palace"},{"id":2,"person":1,"propertyName":"Apartment"}]}


来源: stackexchange

问:
How do I simplify for and if statements?
How do I simplify this? Thanks in advance :)

a_list = []

for a, blah in enumerate(bunch_of_As.blahs):
    if a.name == "WHATEVER":
        for msg in a:
            if msg.type == "value 1":
                a_list.append(a)
            elif msg.type == "value 2":
                if msg.time != 0:
                    do_something(a)
                a_list.remove(a)
```

答:
Its possible to simplify this, because your add and remove the a element on the a_list unnecesary a lot of times

```<code>for a in bunch_of_As:
    if a.name == "WHATEVER":
        counter1 = 0
        counter2 = 0
        for msg in a:
            if msg.type == "value 1":
               counter1 += 1
            elif msg.type == "value 2":
               counter1 += -1
               if msg.time != 0:
                  counter2 += 1
       for n in range(counter1):
           a_list.append(a)

       for n in range(counter2):
           do_something(a)
</code>```

Only i have two question or hypo,
i suppose that the number of "value 1" => (more or equal) num "value 2"
and the do_something(a) effect on a is null

Its clearly that are more lines of codes, but reduces the unnecessary proccess of the append remove

ContentLicense: CC BY-SA 4.0

Body:
Its possible to simplify this, because your add and remove the a element on the a_list unnecesary a lot of times

for a in bunch_of_As:
    if a.name == "WHATEVER":
        counter1 = 0
        counter2 = 0
        for msg in a:
            if msg.type == "value 1":
               counter1 += 1
            elif msg.type == "value 2":
               counter1 += -1
               if msg.time != 0:
                  counter2 += 1
       for n in range(counter1):
           a_list.append(a)

       for n in range(counter2):
           do_something(a)

Only i have two question or hypo,
i suppose that the number of "value 1" => (more or equal) num "value 2"
and the do_something(a) effect on a is null

Its clearly that are more lines of codes, but reduces the unnecessary proccess of the append remove


问:
How do I print a line in one file based on a corresponding value in a second file?
I have two files:
File1:

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

File2:

```<code>2
4
3
</code>```

I would like to print each line in file1 the number of times found on the corresponding line of file2, and then append each line to a separate file.

Desired output:

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

Here is one of the approaches I have tried:

```<code>touch output.list
paste file1 file2 > test.dict
cat test.dict
</code>```

```<code>A       2
B       4
C       3
</code>```

```<code>while IFS="\t" read -r f1 f2
do
   yes "$f1" | head -n "$f2" >> output.list
done < test.dict
</code>```

For my output I get a bunch of lines that read:

```<code>head: : invalid number of lines
</code>```

Any guidance would be greatly appreciated. Thanks!

答:
You could loop through the output of paste and use a c-style for loop in replacement of yes and head.

#!/usr/bin/env bash

while read -r first second; do
  for ((i=1;i<=second;i++)); do
    printf '%s\n' "$first"
  done
done < <(paste file1.txt file2.txt)
```

<p>If you think that the output is correct add</p>

```| tee file3.txt
```

<p>with a white space in between the command substitution to redirect the output to a <code>stdout</code> and the output file which is file3.txt</p>

```done < <(paste file1.txt file2.txt) | tee file3.txt
```

Body:
I have two files:
File1:

A
B
C

File2:

2
4
3

I would like to print each line in file1 the number of times found on the corresponding line of file2, and then append each line to a separate file.

Desired output:

A
A
B
B
B
B
C
C
C

Here is one of the approaches I have tried:

touch output.list
paste file1 file2 > test.dict
cat test.dict

A       2
B       4
C       3

while IFS="\t" read -r f1 f2
do
   yes "$f1" | head -n "$f2" >> output.list
done < test.dict

For my output I get a bunch of lines that read:

head: : invalid number of lines

Any guidance would be greatly appreciated. Thanks!

Body:
You could loop through the output of paste and use a c-style for loop in replacement of yes and head.

#!/usr/bin/env bash

while read -r first second; do
  for ((i=1;i<=second;i++)); do
    printf '%s\n' "$first"
  done
done < <(paste file1.txt file2.txt)

If you think that the output is correct add

| tee file3.txt

with a white space in between the command substitution to redirect the output to a stdout and the output file which is file3.txt

done < <(paste file1.txt file2.txt) | tee file3.txt


问:
ASP.NET Core debugging not working for OnGetAsync
My page model calls a method that executes a query.

```<code>// Retrieve financials
var details = await (from detail in dbContext.StorageDetails
                        where (detail.ArrivalDate != null && detail.ArrivalDate <= dateRange.EndDate &&
                        (detail.DepartureDate == null || detail.DepartureDate >= dateRange.StartDate)) ||
                        (detail.TakeOrPayStartDate != null && detail.TakeOrPayStartDate <= dateRange.EndDate &&
                        (detail.TakeOrPayEndDate == null || detail.TakeOrPayEndDate >= dateRange.StartDate))
                        orderby detail.Location.City, detail.Location.State, detail.ArrivalDate
                        select new
                        {
                            Location = new
                            {
                                Id = detail.LocationId,
                                detail.Location.Name,
                                detail.Location.City,
                                detail.Location.State
                            },
                            detail.RailcarNumber,
                            detail.TakeOrPayId,
                            detail.TakeOrPayStartDate,
                            detail.TakeOrPayEndDate,
                            detail.ArrivalDate,
                            detail.DepartureDate,
                            detail.CherryPickDate,
                            detail.DailyStorageRate,
                            detail.SwitchInRate,
                            detail.SwitchOutRate,
                            detail.CherryPickRate,
                            detail.DailyStorageCost,
                            detail.SwitchInCost,
                            detail.SwitchOutCost,
                            detail.CherryPickCost,
                        })
                        .ToListAsync();
</code>```

I set a breakpoint at the start of this query. When I step over it my code stops in my page's CSHTML file, complaining that the variable that would've held the result of this query is null!

If instead of stepping over this query, I step into it, I find myself stepping through ApplicationDbContact.OnModelCreating().

I thought OnModelCreating() was just used for generating the database schema. So this doesn't make any sense at all to me.

Is there anyone that can see something here, or have I completely broke ASP.NET Core? How would anyone begin to troubleshoot something like this?

This is my page model handler. The query above is in helper.GetFinancialsByLocation().

```<code>public async void OnGetAsync()
{
    DateTime date = DateTime.Today;
    DateRange = new DateRange
    {
        StartDate = new DateTime(date.Year, date.Month, 1),
    };
    DateRange.EndDate = DateRange.StartDate.AddMonths(1).AddMilliseconds(-1);

    try
    {
        FinancialsHelper helper = new FinancialsHelper();
        FinancialsLocations = await helper.GetFinancialsByLocation(DbContext, DateRange);
    }
    catch (Exception ex)
    {
        string s = ex.Message;
    }
}
</code>```

Here's my startup.cs.

```<code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddRazorPages();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}
</code>```

答:
As per the docs you should be using:

```<code>public async Task OnGetAsync()
</code>```

rather than:

```<code>public async void OnGetAsync()
</code>```

Body:
My page model calls a method that executes a query.

// Retrieve financials
var details = await (from detail in dbContext.StorageDetails
                        where (detail.ArrivalDate != null && detail.ArrivalDate <= dateRange.EndDate &&
                        (detail.DepartureDate == null || detail.DepartureDate >= dateRange.StartDate)) ||
                        (detail.TakeOrPayStartDate != null && detail.TakeOrPayStartDate <= dateRange.EndDate &&
                        (detail.TakeOrPayEndDate == null || detail.TakeOrPayEndDate >= dateRange.StartDate))
                        orderby detail.Location.City, detail.Location.State, detail.ArrivalDate
                        select new
                        {
                            Location = new
                            {
                                Id = detail.LocationId,
                                detail.Location.Name,
                                detail.Location.City,
                                detail.Location.State
                            },
                            detail.RailcarNumber,
                            detail.TakeOrPayId,
                            detail.TakeOrPayStartDate,
                            detail.TakeOrPayEndDate,
                            detail.ArrivalDate,
                            detail.DepartureDate,
                            detail.CherryPickDate,
                            detail.DailyStorageRate,
                            detail.SwitchInRate,
                            detail.SwitchOutRate,
                            detail.CherryPickRate,
                            detail.DailyStorageCost,
                            detail.SwitchInCost,
                            detail.SwitchOutCost,
                            detail.CherryPickCost,
                        })
                        .ToListAsync();

I set a breakpoint at the start of this query. When I step over it my code stops in my page's CSHTML file, complaining that the variable that would've held the result of this query is null!

If instead of stepping over this query, I step into it, I find myself stepping through ApplicationDbContact.OnModelCreating().

I thought OnModelCreating() was just used for generating the database schema. So this doesn't make any sense at all to me.

Is there anyone that can see something here, or have I completely broke ASP.NET Core? How would anyone begin to troubleshoot something like this?

This is my page model handler. The query above is in helper.GetFinancialsByLocation().

public async void OnGetAsync()
{
    DateTime date = DateTime.Today;
    DateRange = new DateRange
    {
        StartDate = new DateTime(date.Year, date.Month, 1),
    };
    DateRange.EndDate = DateRange.StartDate.AddMonths(1).AddMilliseconds(-1);

    try
    {
        FinancialsHelper helper = new FinancialsHelper();
        FinancialsLocations = await helper.GetFinancialsByLocation(DbContext, DateRange);
    }
    catch (Exception ex)
    {
        string s = ex.Message;
    }
}

Here's my startup.cs.

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddRazorPages();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}

Body:
As per the docs you should be using:

public async Task OnGetAsync()

rather than:

public async void OnGetAsync()


问:
How do you collect specific information from DownloadString?
So I'm trying to gather information from a website API link, the API displays the information in plaintext, so for example creation date is:

"created_at":"2013-11-13T16:02:49.071386Z"

Now in my program I want to display only certain parts of that information in a TextBox. So I'm going to have a Label saying what the information is, in this case it will be "Creation Date:" and then next to it I want the TextBox to display only "2013-11-13" in this example.

Currently I can display all the information at once using a function, which is messy and all in one TextBox and it looks like this:

```<code> Public Function Information()
    Dim blank As String = TextBox1.Text
    Dim browser As New WebClient
    Dim info As String = browser.DownloadString("API")
    If info.Contains("display_name") Then
        TextBox2.AppendText(blank + " = " + info + vbCrLf)
    Else

    End If
End Function
</code>```

I'm new to all this, so sorry if it sounds stupid. Thanks!

答:
Having looked again, I'm guessing that the data you're downloading is actually JSON. In that case, you probably ought to be treating it as JSON rather than just plain text. That probably means using JSON.NET, which you can add as a NuGet package. You would feed the JSON text in and get access to objects containing the parsed data. I've left my original answer below for completeness though.

ORIGINAL:

DownloadString downloads a String. That's it, that's all. What you do with that String is completely up to you. It's just like any other String. That means that the DownloadString method is irrelevant to the question.

If the actual text you get is indeed this:

"created_at":"2013-11-13T16:02:49.071386Z"

i.e. the double-quotes are part of the text, then you can do this to get the two substrings of interest:

Dim parts = info.Split({":"c}, 2)

For i = 0 To parts.GetUpperBound(0)
    parts(i) = parts(i).Trim(ControlChars.Quote)
Next
```

<p>How you then want to go about converting the "created_at" to "Creation Date" is up to you. As for the date part, there are two ways you could go about it. You could just call <code>String.Split</code> again, e.g.</p>

<pre class="lang-vb prettyprint-override"><code>Dim [date] = parts(1).Split("T"c)(0)
</code>```

Alternatively, you could use Date.ParseExact to convert the text to an actual Date and then format that however you want, e.g.

Dim dt = Date.ParseExact(parts(1), "yyyy-MM-ddTHH:mm:ss.ffffffZ", Nothing)
Dim [date] = dt.ToString("yyyy-MM-dd")
```

The first option is easier if you just want the date in the same format but the second option will allow you to use a different format if you want and you've also got the time if you need for something else.

Body:
So I'm trying to gather information from a website API link, the API displays the information in plaintext, so for example creation date is:

"created_at":"2013-11-13T16:02:49.071386Z"

Now in my program I want to display only certain parts of that information in a TextBox. So I'm going to have a Label saying what the information is, in this case it will be "Creation Date:" and then next to it I want the TextBox to display only "2013-11-13" in this example.

Currently I can display all the information at once using a function, which is messy and all in one TextBox and it looks like this:

 Public Function Information()
    Dim blank As String = TextBox1.Text
    Dim browser As New WebClient
    Dim info As String = browser.DownloadString("API")
    If info.Contains("display_name") Then
        TextBox2.AppendText(blank + " = " + info + vbCrLf)
    Else

    End If
End Function

I'm new to all this, so sorry if it sounds stupid. Thanks!

Body:
Having looked again, I'm guessing that the data you're downloading is actually JSON. In that case, you probably ought to be treating it as JSON rather than just plain text. That probably means using JSON.NET, which you can add as a NuGet package. You would feed the JSON text in and get access to objects containing the parsed data. I've left my original answer below for completeness though.

ORIGINAL:

DownloadString downloads a String. That's it, that's all. What you do with that String is completely up to you. It's just like any other String. That means that the DownloadString method is irrelevant to the question.

If the actual text you get is indeed this:

"created_at":"2013-11-13T16:02:49.071386Z"

i.e. the double-quotes are part of the text, then you can do this to get the two substrings of interest:

Dim parts = info.Split({":"c}, 2)

For i = 0 To parts.GetUpperBound(0)
    parts(i) = parts(i).Trim(ControlChars.Quote)
Next

How you then want to go about converting the "created_at" to "Creation Date" is up to you. As for the date part, there are two ways you could go about it. You could just call String.Split again, e.g.

Dim [date] = parts(1).Split("T"c)(0)

Alternatively, you could use Date.ParseExact to convert the text to an actual Date and then format that however you want, e.g.

Dim dt = Date.ParseExact(parts(1), "yyyy-MM-ddTHH:mm:ss.ffffffZ", Nothing)
Dim [date] = dt.ToString("yyyy-MM-dd")

The first option is easier if you just want the date in the same format but the second option will allow you to use a different format if you want and you've also got the time if you need for something else.


问:
A chatbot in Azure's myapps portal for B2B users
We have rolled out a enterprise wide portal using Azure's myapps where all the enterprise applications are registered. All the B2B users login to this portal and access the application using SSO feature(i.e it uses user's email registered in Azure AD).

i am looking to provide a simple chatbot application in the myapps portal that can resolve any issues related to login to the applications.

Chatbot can be built using powerapps platform.

But how do we integrate or make them available in the myapps portal  ?

答:
You can refer this Documation on how to add application into Azure AD which would appear automatically in myapps portal.

Can try making this setting.
 portal.azure.com -> Enterprise Application -> <<Your Application>> -> Self-service

Set Yes to "Allow users to request access to this application?"

Assign the group "To which group should assigned users be added?"

Save the changes and navigate to https://myapplications.microsoft.com/

Troubleshooting links:

Access panel troubleshoot application not appearing.

Access panel troubleshoot unexpected application.


问:
Angular subscribe function not firing on http 404 error
I've been struggling with some angular code. The thing is, I make a request with angular http client to http://myapi.com/something/1. If the api does not find something with id 1 then it returns a 404 error. Thats fine. But, for some reason, when I subscribe to the http call and get the 404 error, the error function of the subscribe is not firing:

certificatesService
      .getDetail(id)
      .subscribe({
        next: (data) => {
          console.log(data);
        },
        error: (error) => console.log ('error', error) // never reaches this point
      });
```

I've already tried with catchError inside pipe and all sort of things. Nothing happens and don't know what else can I try.

答:
try it like this</p>

```<code>certificatesService
      .getDetail(id)
      .subscribe(
        (data) => {
          console.log(data);
        },
        (error) => console.log ('error', error)
      );
</code>```

Body:
I've been struggling with some angular code. The thing is, I make a request with angular http client to http://myapi.com/something/1. If the api does not find something with id 1 then it returns a 404 error. Thats fine. But, for some reason, when I subscribe to the http call and get the 404 error, the error function of the subscribe is not firing:

certificatesService
      .getDetail(id)
      .subscribe({
        next: (data) => {
          console.log(data);
        },
        error: (error) => console.log ('error', error) // never reaches this point
      });

I've already tried with catchError inside pipe and all sort of things. Nothing happens and don't know what else can I try.

Body:
try it like this

certificatesService
      .getDetail(id)
      .subscribe(
        (data) => {
          console.log(data);
        },
        (error) => console.log ('error', error)
      );


问:
Set rootViewController iOS 13
After upgrading Xcode a critical part of my application has stopped working.

When my app launches I run a function to check boolean flags and set the correct rootViewController.

But the code I have been using to set this has now stopped working

```<code>class func setLoginAsInitialViewContoller(window:UIWindow) {
    print("SET LOGIN")
    let storyboard = UIStoryboard(name: "Login", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
    controller.modalPresentationStyle = .overFullScreen
    window.rootViewController = controller
    window.makeKeyAndVisible()
}
</code>```

Specifically when the app gets the the second last line window.rootViewController = controller it crashes with a libc++abi.dylib: terminating with uncaught exception of type NSException error.

The above function is in a class called Utilities.swift and I am calling the function from within my AppDelegate.swift as shown below:

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var storyboard: UIStoryboard? = nil

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        UIApplication.shared.isIdleTimerDisabled = true
        Utilities.decideInitialViewController(window: self.window!)

        return true
    }
</code>```

Any solutions or fixes on how I can set the root controller is much appreciated.

Thank!

答:
If you want to use ScenceDelegate. In scene(_:willConnectTo:options:, creates a new UIWindow, sets the window’s rootViewController and makes this window the key window.

If you don't want to use ScenceDelegate, you can try to remove it by following this.

Title: Set rootViewController iOS 13

Body:
After upgrading Xcode a critical part of my application has stopped working.

When my app launches I run a function to check boolean flags and set the correct rootViewController.

But the code I have been using to set this has now stopped working

class func setLoginAsInitialViewContoller(window:UIWindow) {
    print("SET LOGIN")
    let storyboard = UIStoryboard(name: "Login", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
    controller.modalPresentationStyle = .overFullScreen
    window.rootViewController = controller
    window.makeKeyAndVisible()
}

Specifically when the app gets the the second last line window.rootViewController = controller it crashes with a libc++abi.dylib: terminating with uncaught exception of type NSException error.

The above function is in a class called Utilities.swift and I am calling the function from within my AppDelegate.swift as shown below:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var storyboard: UIStoryboard? = nil

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        UIApplication.shared.isIdleTimerDisabled = true
        Utilities.decideInitialViewController(window: self.window!)

        return true
    }

Any solutions or fixes on how I can set the root controller is much appreciated.

Thank!


问:
Excel VBA adding new row in table (excel crashing)
I have been building a workbook to store all my recipes, and I am trying to have inputs in a userform be added to the next row in a table from the recipeInfo object that contains all the data.

The Debug.print statements give the correct outputs as far as I can tell, but the lines below that are supposed to add the info into the row after the last one in the table causes excel to crash whenever I run it.

Am I doing something wrong with the recipeSheet.cells commands?

```<code>Sub addData(newRecipe As recipeInfo)

Dim col As Integer
Dim recipeSheet As Worksheet
Dim lastRow As Integer

Set recipeSheet = ActiveWorkbook.Sheets("Recipes")
lastRow = recipeSheet.UsedRange.Rows.Count

'MsgBox (recipeSheet.Name & ", " & lastRow)

'add data into range

Debug.Print (newRecipe.item)
Debug.Print (newRecipe.cost)
Debug.Print (newRecipe.servings)
Debug.Print (newRecipe.cost / newRecipe.servings)
Debug.Print (newRecipe.ingredients)
Debug.Print (newRecipe.instructions)

recipeSheet.Cells(lastRow + 1, 1) = newRecipe.item
recipeSheet.Cells(lastRow + 1, 2) = newRecipe.cost
recipeSheet.Cells(lastRow + 1, 3) = newRecipe.servings
recipeSheet.Cells(lastRow + 1, 4) = newRecipe.cost / newRecipe.servings
recipeSheet.Cells(lastRow + 1, 5) = newRecipe.ingredients
recipeSheet.Cells(lastRow + 1, 6) = newRecipe.instructions

End Sub
</code>```

答: I noticed that when you set the object list or table as a rowsource to a listbox you get this kind of error specially after you save the workbook and start adding again, check if you have in your project a listbox attached to that table and instead of making it on the proprieties of the listbox , code it when the userform initialize for me it worked that way I hope It helps someone </p>

ContentLicense: CC BY-SA 3.0

Body:
I have been building a workbook to store all my recipes, and I am trying to have inputs in a userform be added to the next row in a table from the recipeInfo object that contains all the data.

The Debug.print statements give the correct outputs as far as I can tell, but the lines below that are supposed to add the info into the row after the last one in the table causes excel to crash whenever I run it.

Am I doing something wrong with the recipeSheet.cells commands?

Sub addData(newRecipe As recipeInfo)

Dim col As Integer
Dim recipeSheet As Worksheet
Dim lastRow As Integer

Set recipeSheet = ActiveWorkbook.Sheets("Recipes")
lastRow = recipeSheet.UsedRange.Rows.Count

'MsgBox (recipeSheet.Name & ", " & lastRow)

'add data into range

Debug.Print (newRecipe.item)
Debug.Print (newRecipe.cost)
Debug.Print (newRecipe.servings)
Debug.Print (newRecipe.cost / newRecipe.servings)
Debug.Print (newRecipe.ingredients)
Debug.Print (newRecipe.instructions)

recipeSheet.Cells(lastRow + 1, 1) = newRecipe.item
recipeSheet.Cells(lastRow + 1, 2) = newRecipe.cost
recipeSheet.Cells(lastRow + 1, 3) = newRecipe.servings
recipeSheet.Cells(lastRow + 1, 4) = newRecipe.cost / newRecipe.servings
recipeSheet.Cells(lastRow + 1, 5) = newRecipe.ingredients
recipeSheet.Cells(lastRow + 1, 6) = newRecipe.instructions

End Sub


问:
Decent approach to time OkHttpClient events for metrics?
I'd like to gather connection and request timing metrics for an OkHttpClient instance that calls a particular service. I'm wondering if this approach is correct, and whether my interpretation of the event types makes sense?

Timer callTimer = <new codahale timer>;
Timer connectTimer = <new codahale timer>;
Timer secureConnectTimer = <new codahale timer>;
Timer requestTimer = <new codahale timer>;

# this gets registered with my client
new EventListener() {
      // see https://square.github.io/okhttp/events/#eventlistener for info on the ordering of these events
      private final Map<Call, Timer.Context> secureConnectTimerContexts = Maps.newConcurrentMap();
      private final Map<Call, Timer.Context> connectTimerContexts = Maps.newConcurrentMap();
      private final Map<Call, Timer.Context> callTimerContexts = Maps.newConcurrentMap();
      private final Map<Call, Timer.Context> requestTimerContexts = Maps.newConcurrentMap();

      @Override
      public void secureConnectStart(Call call) {
        secureConnectTimerContexts.put(call, secureConnectTimer.time());
      }

      @Override
      public void secureConnectEnd(Call call, @Nullable Handshake handshake) {
        Timer.Context context = secureConnectTimerContexts.remove(call);
        if (Objects.nonNull(context)) {
          context.stop();
        }
      }

      @Override
      public void connectStart(Call call, InetSocketAddress inetSocketAddress, Proxy proxy) {
        connectTimerContexts.put(call, connectTimer.time());
      }

      @Override
      public void connectEnd(Call call, InetSocketAddress inetSocketAddress, Proxy proxy, @Nullable Protocol protocol) {
        Timer.Context context = connectTimerContexts.remove(call);
        if (Objects.nonNull(context)) {
          context.stop();
        }
      }

      @Override
      public void connectionAcquired(Call call, Connection connection) {
        requestTimerContexts.put(call, requestTimer.time());
      }

      @Override
      public void connectionReleased(Call call, Connection connection) {
        Timer.Context context = requestTimerContexts.remove(call);
        if (context != null) {
          context.stop();
        }
      }

      @Override
      public void connectFailed(Call call, InetSocketAddress inetSocketAddress, Proxy proxy,
                                @Nullable Protocol protocol, IOException ioe) {
        Timer.Context context = connectTimerContexts.remove(call);
        if (Objects.nonNull(context)) {
          context.stop();
        }
      }

      @Override
      public void callStart(Call call) {
        callTimerContexts.put(call, callTimer.time());
      }

      @Override
      public void callEnd(Call call) {
        callFinishedForMetrics(call);
      }

      @Override
      public void callFailed(Call call, IOException ioe) {
        callFinishedForMetrics(call);
      }

      private void callFinishedForMetrics(Call call) {
        Timer.Context callTimerContext = callTimerContexts.remove(call);
        if (callTimerContext != null) {
          callTimerContext.stop();
        }

        requestTimerContexts.remove(call);
        secureConnectTimerContexts.remove(call);
        connectTimerContexts.remove(call);
      }
    }
```

答: You can use EventListener.Factory to create a unique listener instance for each Call. That way you don't need all the maps; the Timer.Context objects can just be instance fields of the call-bound EventListener.


问:
Why is access to the path denied?
I am having a problem where I am trying to delete my file but I get an exception.

```<code>if (result == "Success")
{
     if (FileUpload.HasFile)
     {
         try
         {
              File.Delete(Request.PhysicalApplicationPath + app_settings.login_images + txtUploadStatus.Text);
              string filename = Path.GetFileName(btnFileUpload.FileName);
              btnFileUpload.SaveAs(Request.PhysicalApplicationPath + app_settings.login_images + filename);
         }
         catch (Exception ex)
         {
               Message(ex.ToString());
         }
      }
}
</code>```

Also I should note that the folder I am trying to delete from has full control to network services.

The full exception message is:

System.UnauthorizedAccessException: Access to the path 'C:\Users\gowdyn\Documents\Visual Studio 2008\Projects\hybrid\hybrid\temp_loginimages\enviromental.jpg' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.Delete(String path) at hybrid.User_Controls.Imgloader_Add_Edit_Tbl.btnUpdate_Click(Object sender, EventArgs e) in C:\Users\gowdyn\Documents\Visual Studio 2008\Projects\hybrid\hybrid\User_Controls\Imgloader_Add_Edit_Tbl.ascx.cs:line 242

Any ideas?

答:
To solve this problem, I follow the Scot Hanselman approach at Debugging System.UnauthorizedAccessException (often followed by: Access to the path is denied) article, the code with example is bellow:</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        var path = "c:\\temp\\notfound.txt";
        try
        {
            File.Delete(path);
        }
        catch (UnauthorizedAccessException)
        {
            FileAttributes attributes = File.GetAttributes(path);
            if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            {
                attributes &= ~FileAttributes.ReadOnly;
                File.SetAttributes(path, attributes);
                File.Delete(path);
            }
            else
            {
                throw;
            }
        }
    }
}
</code>```

Title: Why is access to the path denied?

Body:
I am having a problem where I am trying to delete my file but I get an exception.

if (result == "Success")
{
     if (FileUpload.HasFile)
     {
         try
         {
              File.Delete(Request.PhysicalApplicationPath + app_settings.login_images + txtUploadStatus.Text);
              string filename = Path.GetFileName(btnFileUpload.FileName);
              btnFileUpload.SaveAs(Request.PhysicalApplicationPath + app_settings.login_images + filename);
         }
         catch (Exception ex)
         {
               Message(ex.ToString());
         }
      }
}

Also I should note that the folder I am trying to delete from has full control to network services.

The full exception message is:

System.UnauthorizedAccessException: Access to the path 'C:\Users\gowdyn\Documents\Visual Studio 2008\Projects\hybrid\hybrid\temp_loginimages\enviromental.jpg' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.Delete(String path) at hybrid.User_Controls.Imgloader_Add_Edit_Tbl.btnUpdate_Click(Object sender, EventArgs e) in C:\Users\gowdyn\Documents\Visual Studio 2008\Projects\hybrid\hybrid\User_Controls\Imgloader_Add_Edit_Tbl.ascx.cs:line 242

Any ideas?

Body:
To solve this problem, I follow the Scot Hanselman approach at Debugging System.UnauthorizedAccessException (often followed by: Access to the path is denied) article, the code with example is bellow:

class Program
{
    static void Main(string[] args)
    {
        var path = "c:\\temp\\notfound.txt";
        try
        {
            File.Delete(path);
        }
        catch (UnauthorizedAccessException)
        {
            FileAttributes attributes = File.GetAttributes(path);
            if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            {
                attributes &= ~FileAttributes.ReadOnly;
                File.SetAttributes(path, attributes);
                File.Delete(path);
            }
            else
            {
                throw;
            }
        }
    }
}


问:
Convert all the columns of a spark dataframe into a json format and then include the json formatted data as a column in another/parent dataframe
Converted dataframe(say child dataframe) into json using df.toJSON

After json conversion the schema looks like this :

```<code>root
 |-- value: string (nullable = true)
</code>```

I used the following suggestion to get child dataframe into the intermediate parent schema/dataframe:

```<code>scala> parentDF.toJSON.select(struct($"value").as("data")).printSchema
root
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)
</code>```

Now I still need to build the parentDF schema further to make it look like:

```<code>root
 |-- id
 |-- version
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)
</code>```

Q1) How can I build the id column using the id from value(i.e value.id needs to be represented as id)

Q2) I need to bring version from a different dataframe(say versionDF) where version is a constant(in all columns). Do I fetch one row from this versionDF to read value of version column and then populate it as literal in the parentDF ?

please help with any code snippets on this.

答:
Instead of toJSON use to_json in select statement & select required columns along with to_json function.

Check below code.

```<code>val version =  // Get version value from versionDF
parentDF.select($"id",struct(to_json(struct($"*")).as("value")).as("data"),lit(version).as("version"))

scala> parentDF.select($"id",struct(to_json(struct($"*")).as("value")).as("data"),lit(version).as("version")).printSchema
root
 |-- id: integer (nullable = false)
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)
 |-- version: double (nullable = false)

</code>```

Updated

```<code>scala> df.select($"id",to_json(struct(struct($"*").as("value"))).as("data"),lit(version).as("version")).printSchema
root
 |-- id: integer (nullable = false)
 |-- data: string (nullable = true)
 |-- version: integer (nullable = false)

scala> df.select($"id",to_json(struct(struct($"*").as("value"))).as("data"),lit(version).as("version")).show(false)
+---+------------------------------------------+-------+
|id |data                                      |version|
+---+------------------------------------------+-------+
|1  |{"value":{"id":1,"col1":"a1","col2":"b1"}}|1      |
|2  |{"value":{"id":2,"col1":"a2","col2":"b2"}}|1      |
|3  |{"value":{"id":3,"col1":"a3","col2":"b3"}}|1      |
+---+------------------------------------------+-------+
</code>```

Update-1

```<code>scala> df.select($"id",to_json(struct($"*").as("value")).as("data"),lit(version).as("version")).printSchema
root
 |-- id: integer (nullable = false)
 |-- data: string (nullable = true)
 |-- version: integer (nullable = false)

scala> df.select($"id",to_json(struct($"*").as("value")).as("data"),lit(version).as("version")).show(false)
+---+--------------------------------+-------+
|id |data                            |version|
+---+--------------------------------+-------+
|1  |{"id":1,"col1":"a1","col2":"b1"}|1      |
|2  |{"id":2,"col1":"a2","col2":"b2"}|1      |
|3  |{"id":3,"col1":"a3","col2":"b3"}|1      |
+---+--------------------------------+-------+

</code>```

Body:
Converted dataframe(say child dataframe) into json using df.toJSON

After json conversion the schema looks like this :

root
 |-- value: string (nullable = true)

I used the following suggestion to get child dataframe into the intermediate parent schema/dataframe:

scala> parentDF.toJSON.select(struct($"value").as("data")).printSchema
root
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)

Now I still need to build the parentDF schema further to make it look like:

root
 |-- id
 |-- version
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)

Q1) How can I build the id column using the id from value(i.e value.id needs to be represented as id)

Q2) I need to bring version from a different dataframe(say versionDF) where version is a constant(in all columns). Do I fetch one row from this versionDF to read value of version column and then populate it as literal in the parentDF ?

please help with any code snippets on this.

Body:
Instead of toJSON use to_json in select statement & select required columns along with to_json function.

Check below code.

val version =  // Get version value from versionDF
parentDF.select($"id",struct(to_json(struct($"*")).as("value")).as("data"),lit(version).as("version"))

scala> parentDF.select($"id",struct(to_json(struct($"*")).as("value")).as("data"),lit(version).as("version")).printSchema
root
 |-- id: integer (nullable = false)
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)
 |-- version: double (nullable = false)

Updated

scala> df.select($"id",to_json(struct(struct($"*").as("value"))).as("data"),lit(version).as("version")).printSchema
root
 |-- id: integer (nullable = false)
 |-- data: string (nullable = true)
 |-- version: integer (nullable = false)

scala> df.select($"id",to_json(struct(struct($"*").as("value"))).as("data"),lit(version).as("version")).show(false)
+---+------------------------------------------+-------+
|id |data                                      |version|
+---+------------------------------------------+-------+
|1  |{"value":{"id":1,"col1":"a1","col2":"b1"}}|1      |
|2  |{"value":{"id":2,"col1":"a2","col2":"b2"}}|1      |
|3  |{"value":{"id":3,"col1":"a3","col2":"b3"}}|1      |
+---+------------------------------------------+-------+

Update-1

scala> df.select($"id",to_json(struct($"*").as("value")).as("data"),lit(version).as("version")).printSchema
root
 |-- id: integer (nullable = false)
 |-- data: string (nullable = true)
 |-- version: integer (nullable = false)

scala> df.select($"id",to_json(struct($"*").as("value")).as("data"),lit(version).as("version")).show(false)
+---+--------------------------------+-------+
|id |data                            |version|
+---+--------------------------------+-------+
|1  |{"id":1,"col1":"a1","col2":"b1"}|1      |
|2  |{"id":2,"col1":"a2","col2":"b2"}|1      |
|3  |{"id":3,"col1":"a3","col2":"b3"}|1      |
+---+--------------------------------+-------+


问:
'<' not supported between instances of 'function' and 'int'
New to Python, and have been given the following task by my teacher at school.

Trying to get average from 3x temperature inputs, and then to compare to a set value of 20 degrees, to return a message if average is < 20, or another message if >=20, but getting the following error message;

Traceback (most recent call last):
  File "main.py", line 18, in
    if avg < 20:
TypeError: '<' not supported between instances of 'function' and 'int'

My coding is as follows;

```<code># Ask for Temperature in Art Department
arttemp = input('Please Enter Art Department Temperature: ')

# Ask for Temperature in English Department
engtemp = input('Please Enter English Department Temperature: ')

# Ask for Temperature in Music Department
mustemp = input('Please Enter Music Department Temperature: ')

# This block calculates the average temperature
def avg(arttemp, engtemp, mustemp):
  avg=(arttemp + engtemp + mustemp)/3

# This block displays the calculated average temperature
print ('The average temperature across the 3 departments is', avg)

# This decides if average temperature is less than 20 or not
if avg < 20:
  print ('The Heating Should Be Turned On')
else:
  print ('The Heating Should Be Turned Off')
</code>```

Could anyone point out where I have gone wrong?

Thanks.

答:
There are a few issues, but it's an easy fix.

First, input() always returns a string. Since you're doing a numerical computation, you probably want to cast the input as a float.

arttemp = float(input('Please Enter Art Department Temperature: '))
```

<p>Second, the function <code>avg()</code> doesn't actually return anything unless you use the keyword <code>return</code>. Without a <code>return</code>, a function returns the constant <code>None</code> by default. Assigning the variable <code>avg</code> within the function does not act as a return statement (like it sort of does in MATLAB, etc.). So you probably want the function to be</p>

<pre class="lang-py prettyprint-override"><code>def avg(arttemp, engtemp, mustemp):
    return (arttemp + engtemp + mustemp) / 3
</code>```

Next, you need to make sure you call the function avg() appropriately, for which you use parentheses. Using avg without parentheses just refers to the function, but it doesn't ask the function to actually do anything (this is where the original error is coming from, you're trying to compare a function handle to an integer).

if avg(arttemp, engtemp, mustemp) < 20:
    print ('The Heating Should Be Turned On')
```

<p>Finally, you really don't need to write a function to compute the average (unless that was the point of the exercise) since you only call the function once. You can also use standard library functions to do this for you, like <code>statistics.mean()</code>. Here's one way to put it all together.</p>

<pre class="lang-py prettyprint-override"><code># Get temperatures from the user.
arttemp = float(input('Please Enter Art Department Temperature: '))
engtemp = float(input('Please Enter English Department Temperature: '))
mustemp = float(input('Please Enter Music Department Temperature: '))

# Calculate and report the average.
avg_temp = (arttemp + engtemp + mustemp) / 3
print('The average temperature across the 3 departments is', avg_temp)

# Make a decision for the heating based on the average temperature.
if avg_temp < 20:
    print('The Heating Should Be Turned On')
else:
    print('The Heating Should Be Turned Off')
</code>```

And, if you would like the names / number of departments to be a little more flexible, you could use a loop or list comprehension.

import statistics

departments = ["Art", "English", "Music"]
temperatures = [float(input(f"Please enter {d} department temperature: ")) for d in departments]
avg_temp = statistics.mean(temperatures)

print(f'The average temperature across the {len(departments)} departments is', avg_temp)
if avg_temp < 20:
    print('The Heating Should Be Turned On')
else:
    print('The Heating Should Be Turned Off')
```

OwnerDisplayName: Dave

Body:
New to Python, and have been given the following task by my teacher at school.

Trying to get average from 3x temperature inputs, and then to compare to a set value of 20 degrees, to return a message if average is < 20, or another message if >=20, but getting the following error message;

Traceback (most recent call last):
  File "main.py", line 18, in
    if avg < 20:
TypeError: '<' not supported between instances of 'function' and 'int'

My coding is as follows;

# Ask for Temperature in Art Department
arttemp = input('Please Enter Art Department Temperature: ')

# Ask for Temperature in English Department
engtemp = input('Please Enter English Department Temperature: ')

# Ask for Temperature in Music Department
mustemp = input('Please Enter Music Department Temperature: ')

# This block calculates the average temperature
def avg(arttemp, engtemp, mustemp):
  avg=(arttemp + engtemp + mustemp)/3

# This block displays the calculated average temperature
print ('The average temperature across the 3 departments is', avg)

# This decides if average temperature is less than 20 or not
if avg < 20:
  print ('The Heating Should Be Turned On')
else:
  print ('The Heating Should Be Turned Off')

Could anyone point out where I have gone wrong?

Thanks.

Body:
There are a few issues, but it's an easy fix.

First, input() always returns a string. Since you're doing a numerical computation, you probably want to cast the input as a float.

arttemp = float(input('Please Enter Art Department Temperature: '))

Second, the function avg() doesn't actually return anything unless you use the keyword return. Without a return, a function returns the constant None by default. Assigning the variable avg within the function does not act as a return statement (like it sort of does in MATLAB, etc.). So you probably want the function to be

def avg(arttemp, engtemp, mustemp):
    return (arttemp + engtemp + mustemp) / 3

Next, you need to make sure you call the function avg() appropriately, for which you use parentheses. Using avg without parentheses just refers to the function, but it doesn't ask the function to actually do anything (this is where the original error is coming from, you're trying to compare a function handle to an integer).

if avg(arttemp, engtemp, mustemp) < 20:
    print ('The Heating Should Be Turned On')

Finally, you really don't need to write a function to compute the average (unless that was the point of the exercise) since you only call the function once. You can also use standard library functions to do this for you, like statistics.mean(). Here's one way to put it all together.

# Get temperatures from the user.
arttemp = float(input('Please Enter Art Department Temperature: '))
engtemp = float(input('Please Enter English Department Temperature: '))
mustemp = float(input('Please Enter Music Department Temperature: '))

# Calculate and report the average.
avg_temp = (arttemp + engtemp + mustemp) / 3
print('The average temperature across the 3 departments is', avg_temp)

# Make a decision for the heating based on the average temperature.
if avg_temp < 20:
    print('The Heating Should Be Turned On')
else:
    print('The Heating Should Be Turned Off')

And, if you would like the names / number of departments to be a little more flexible, you could use a loop or list comprehension.

import statistics

departments = ["Art", "English", "Music"]
temperatures = [float(input(f"Please enter {d} department temperature: ")) for d in departments]
avg_temp = statistics.mean(temperatures)

print(f'The average temperature across the {len(departments)} departments is', avg_temp)
if avg_temp < 20:
    print('The Heating Should Be Turned On')
else:
    print('The Heating Should Be Turned Off')


问:
Is list-column a concept in the R language?
Is list-column data structure  a concept in the R language or not?

What is a list column? When viewing a dataframe as a list of columns, is a list column a column in the dataframe?

I got the confusion from R for Data Science

List-columns are  implicit  in  the  definition  of  the  data  frame:
  a  data  frame  is  a named list of equal length vectors. A list is a
  vector, so it’s always been legitimate to use a list as a column of a
  data frame. However, base  R  doesn’t  make  it  easy  to  create
  list-columns,  and data.frame()  treats a list as a list of columns:

```<code>data.frame(x = list(1:3, 3:5))
#>   x.1.3 x.3.5
#> 1     1     3
#> 2     2     4
#> 3     3     5
</code>```

You  can  prevent  data.frame()   from  doing  this  with  I() ,  but
  the result doesn’t print particularly well:

```<code>data.frame(
  x = I(list(1:3, 3:5)),
  y = c("1, 2", "3, 4, 5")
)
#>         x       y
#> 1 1, 2, 3    1, 2
#> 2 3, 4, 5 3, 4, 5
</code>```

答:
Not only are list-columns concepts in R and the tidyverse, sometimes they're nearly unavoidable.  Mostly, the contents of each cell in a tibble (or dataFrame) is a number, character or logical.  But the contents can be a vector, a list, or a tibble.  Often the next step, when you've created one of those, is to unnest.  For example, look at the terms with and in this tibble

```<code>library(tidyverse)
inputs <- tibble(Veggies = c("carrots", "potatoes and onions", "squash"),
                   Herbs = c("parsley", "sage", "rosemary and thyme"))
</code>```

We want to give each conjoined term its own line, like this:

```<code>splitPea <- inputs %>%
  mutate(Veggies = str_split(Veggies, "\\s+and\\s+"),
         Herbs = str_split(Herbs, "\\s+and\\s+"))
</code>```

Giving

```<code># A tibble: 3 x 2
  Veggies   Herbs
  <list>    <list>
1 <chr [1]> <chr [1]>
2 <chr [2]> <chr [1]>
3 <chr [1]> <chr [2]>
</code>```

Note that each column is a list, and the cell-contents are vectors.  Now unnest:

```<code>splitPea %>%
  unnest(c(Veggies, Herbs))

# A tibble: 5 x 2
  Veggies  Herbs
  <chr>    <chr>
1 carrots  parsley
2 potatoes sage
3 onions   sage
4 squash   rosemary
5 squash   thyme
</code>```

PS, see this post to see why + how you'd make a column of a list of tibbles.

Body:
Is list-column data structure  a concept in the R language or not?

What is a list column? When viewing a dataframe as a list of columns, is a list column a column in the dataframe?

I got the confusion from R for Data Science

List-columns are  implicit  in  the  definition  of  the  data  frame:
  a  data  frame  is  a named list of equal length vectors. A list is a
  vector, so it’s always been legitimate to use a list as a column of a
  data frame. However, base  R  doesn’t  make  it  easy  to  create
  list-columns,  and data.frame()  treats a list as a list of columns:

data.frame(x = list(1:3, 3:5))
#>   x.1.3 x.3.5
#> 1     1     3
#> 2     2     4
#> 3     3     5

You  can  prevent  data.frame()   from  doing  this  with  I() ,  but
  the result doesn’t print particularly well:

data.frame(
  x = I(list(1:3, 3:5)),
  y = c("1, 2", "3, 4, 5")
)
#>         x       y
#> 1 1, 2, 3    1, 2
#> 2 3, 4, 5 3, 4, 5

Body:
Not only are list-columns concepts in R and the tidyverse, sometimes they're nearly unavoidable.  Mostly, the contents of each cell in a tibble (or dataFrame) is a number, character or logical.  But the contents can be a vector, a list, or a tibble.  Often the next step, when you've created one of those, is to unnest.  For example, look at the terms with and in this tibble

library(tidyverse)
inputs <- tibble(Veggies = c("carrots", "potatoes and onions", "squash"),
                   Herbs = c("parsley", "sage", "rosemary and thyme"))

We want to give each conjoined term its own line, like this:

splitPea <- inputs %>%
  mutate(Veggies = str_split(Veggies, "\\s+and\\s+"),
         Herbs = str_split(Herbs, "\\s+and\\s+"))

Giving

# A tibble: 3 x 2
  Veggies   Herbs
  <list>    <list>
1 <chr [1]> <chr [1]>
2 <chr [2]> <chr [1]>
3 <chr [1]> <chr [2]>

Note that each column is a list, and the cell-contents are vectors.  Now unnest:

splitPea %>%
  unnest(c(Veggies, Herbs))

# A tibble: 5 x 2
  Veggies  Herbs
  <chr>    <chr>
1 carrots  parsley
2 potatoes sage
3 onions   sage
4 squash   rosemary
5 squash   thyme

PS, see this post to see why + how you'd make a column of a list of tibbles.


问:
How to use NiFi cron to schedule for specific time period
Is there a way to use NiFi cron driven scheduler or other ways to run the process for a specific time a day, or to stop for a brief moment.

For example: every day I want the scheduler to stop between 5am-6am & 5pm-6pm, and the rest of the time is continuous.

答:
The CRON scheduler allows for specifically-timed discrete invocations, rather than "on during this period and off during this period". I've crafted a CRON schedule expression which sort of meets your request, but I have a different suggestion instead (CRON scheduling is also not an encouraged approach; it was implemented in NiFi for legacy reasons but isn't really actively developed or recommended).

The CRON expression

0-59 0-4,6-16,18-23 * * *

This expression means "run (the processor) at minute 0, 1, ..., 59 of hours 0-4, 6-16, 18-23 (midnight through 4:59am, 6:00am through 4:59pm, and 6:00pm through 11:59pm) everyday." Your processor will run 1320 times each day (60 times per hour for 22 hours). However, this means it will run once per minute, which may or may not be frequent enough for your needs.

Better suggestion

My actual solution would be to enable the processor to run on the actual Run Schedule you want (every 1 sec, every 3 min, etc.) and use a script to invoke the HTTP API (or Python API) to enable/disable the processor at the specified times. You can even use the CRON scheduling capability of your operating system to do so.

Example:

In NiFi, Processor X is enabled and running.

At 0500 daily, a script is run (via CRON or otherwise), which invokes curl -X PUT http://my.nifi.service:8443/nifi-api/processors/... and updates the state to STOPPED.

At 0600 daily, a script is run which updates the state to STARTED again.

Repeat at 1700 and 1800.

You can parameterize the script to accept an argument determining start/stop to reduce duplication of code. I think this is a more robust solution to your problem.

Other resources:

NiFi REST API

NiPyAPI (Unofficial but very good Python client library for NiFi)

Starting/stopping processors using NiFi API via curl - Cloudera Community and Stack Overflow

You can also make any specific request via the GUI and use the browser's developer tools to record the exact API invocation to capture the processor UUID, JSON values, etc.


问:
Chart.js line graph doesn't show up most of the time
I want to display a chart with money donated and the date of the donation. Mysteriously, the chart shows up sometimes (~5% of the time), yet doesn't the other 95% of the time (See pictures at bottom).

I'm very confused about this issue I'm having. I want to create a line chart using some data I'm getting from an API. I'm using chart.js. Sometimes it shows up and sometimes it doesn't. It has nothing to do with getting the API data as (from looking at the console) that is done immediately. So I am sure it is a problem with my way of using Chart.js.

Here is my LineChart.vue:

```<code><script>
import { Line } from 'vue-chartjs'

export default {
  name: 'LineChart',
  extends: Line,
  props: {
    label: {
      type: String
    },
    chartData: {
      type: Array
    },
    options: {
      type: Object
    }
  },
  mounted () {
    const dates = this.chartData.map(d => d.donationDate).reverse()
    const totals = this.chartData.map(d => d.totalMoney).reverse()

    this.renderChart({
      labels: dates,
      datasets: [{
        label: this.label,
        data: totals
      }]
    },
    this.options)
  }
}
</script>
</code>```

Here is my code for Fundraiser.vue:

```<code><template>
  <div class="container">
    <div class="row mt-5">
      <div class="col">
        <h2>Positive</h2>
        <line-chart :chart-data=recentDonations :options=chartOptions label='Positive'>
        </line-chart>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'
import LineChart from '../components/LineChart.vue'

export default {
  name: 'Fundraiser',
  components: { LineChart },
  data () {
    return {
      recentDonations: [],
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      }
    }
  },
  async created () {
    const { data } = await axios({
      url: 'http://api.justgiving.com/[MY API KEY]/v1/crowdfunding/pages/[SOME-PAGE]/pledges',
      method: 'get',
      headers: {
        Accept: 'application/json'
      }
    })
    console.log(data)
    data.pledges.forEach(d => { // this part works fine.
      if (d.donationAmount != null) {
        const dateInEpochFormat = d.activityDate.substring(6, 16)
        const donationMade = moment.unix(dateInEpochFormat).format('MM/DD')
        this.recentDonations.push({ donationDate: donationMade, totalMoney: d.donationAmount })
      }
      console.log(this.recentDonations)
    })
  }
}
</script>
</code>```

As you can see from the pictue below, the data is being pulled fine (array of objects with two properties: donateDate and totalMoney)

So sometimes it shows up (very very rarely):
[][

Then I refresh the page (without touching ANY code) and all of a sudden:

Can someone please help me solve this mystery?

答:
Try to render the graph after receiving the response from the http request, maybe with an if statement and a variable as flag:

```<code><template>
  <div class="container">
    <div class="row mt-5">
      <div class="col" v-if="show">
        <h2>Positive</h2>
        <line-chart
          :chart-data="recentDonations"
          :options="chartOptions"
          label="Positive"
        >
        </line-chart>
      </div>
    </div>
  </div>
</template>
</code>```

In your export default object, you can have this:

```<code>export default {
  name: 'Fundraiser',
  components: { LineChart },
  data () {
    return {
      show: false,
      recentDonations: [],
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      }
    }
  },
  async created () {
    const { data } = await axios({
      url: 'http://api.justgiving.com/[MY API KEY]/v1/crowdfunding/pages/[SOME-
      PAGE]/pledges',
      method: 'get',
      headers: {
        Accept: 'application/json'
      }
    })
    console.log(data)
    data.pledges.forEach(d => { // this part works fine.
      if (d.donationAmount != null) {
        const dateInEpochFormat = d.activityDate.substring(6, 16)
        const donationMade = moment.unix(dateInEpochFormat).format('MM/DD')
        this.recentDonations.push({ donationDate: donationMade, totalMoney:
        d.donationAmount })
      }
      console.log(this.recentDonations)
    })
    this.show = true;
  }
}
</code>```

This is a workaround, You are waiting to have the data before render the graph, than way the first time that the graph is rendered, it can use the data and show the information.

The reason to not see data in the graph is because when the graph is rendered there is not information to show, once you get the response from the http request the graph is not updated, to do so, you must to watch the chartData prop, and once chartData is updated, you must call the chart.js update graph method (you can read more about it here: https://www.chartjs.org/docs/latest/developers/updates.html)

A better way to handle the data update is to assign the value to this.recentDonations after the forEach, that way you are not getting updates every time a pledge is pushed:
    ...
    const donations = [];
    data.pledges.forEach(d => { // this part works fine.
      if (d.donationAmount != null) {
        const dateInEpochFormat = d.activityDate.substring(6, 16)
        const donationMade = moment.unix(dateInEpochFormat).format('MM/DD')
        donations.push({ donationDate: donationMade, totalMoney:
        d.donationAmount })
      }
      console.log(this.recentDonations)
    })
    this.recentDonation = donations;
    this.show = true;
    ...

I did a test with a timeout function using this code (I don't know how to use the justgiving api):

```<code><template>
  <div class="container">
    <div class="row mt-5">
      <div class="col" v-if="show">
        <h2>Positive</h2>
        <line-chart
          :chart-data="recentDonations"
          :options="chartOptions"
          label="Positive"
        >
        </line-chart>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import moment from "moment";
import LineChart from "../components/LineChart.vue";

export default {
  name: "Fundraiser",
  components: { LineChart },
  data() {
    return {
      show: false,
      recentDonations: [],
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      }
    };
  },
  methods: {
    request() {
      const pledges = [
        { donationDate: "11/08", donationAmount: 5 },
        { donationDate: "11/09", donationAmount: 5 },
        { donationDate: "11/10", donationAmount: 5 },
        { donationDate: "11/11", donationAmount: 5 },
        { donationDate: "11/12", donationAmount: 5 },
        { donationDate: "11/13", donationAmount: 5 },
        { donationDate: "11/14", donationAmount: 5 },
        { donationDate: "11/15", donationAmount: 5 },
        { donationDate: "11/16", donationAmount: 5 },
        { donationDate: "11/17", donationAmount: 5 },
        { donationDate: "11/18", donationAmount: 5 },
        { donationDate: "11/19", donationAmount: 5 },
        { donationDate: "11/20", donationAmount: 5 },
        { donationDate: "11/21", donationAmount: 5 },
        { donationDate: "11/22", donationAmount: 5 }
      ];
      pledges.forEach(d => {
        // this part works fine.
        // if (d.donationAmount != null) {
        // const dateInEpochFormat = d.activityDate.substring(6, 16);
        // const donationMade = moment.unix(dateInEpochFormat).format("MM/DD");
        this.recentDonations.push({
          donationDate: d.donationDate,
          totalMoney: d.donationAmount
        });
        // }
        console.log(this.recentDonations);
      });
      this.show = true;
    }
  },
  async created() {
    await setTimeout(this.request, 1000);
  }
};
</script>
</code>```

If you remove the if statement, the graph doesn't show any data

Body:
I want to display a chart with money donated and the date of the donation. Mysteriously, the chart shows up sometimes (~5% of the time), yet doesn't the other 95% of the time (See pictures at bottom).

I'm very confused about this issue I'm having. I want to create a line chart using some data I'm getting from an API. I'm using chart.js. Sometimes it shows up and sometimes it doesn't. It has nothing to do with getting the API data as (from looking at the console) that is done immediately. So I am sure it is a problem with my way of using Chart.js.

Here is my LineChart.vue:

Here is my code for Fundraiser.vue:

<template>

Positive

        <line-chart :chart-data=recentDonations :options=chartOptions label='Positive'>
        </line-chart>

</template>

As you can see from the pictue below, the data is being pulled fine (array of objects with two properties: donateDate and totalMoney)

So sometimes it shows up (very very rarely):
[][

Then I refresh the page (without touching ANY code) and all of a sudden:

Can someone please help me solve this mystery?

Body:
Try to render the graph after receiving the response from the http request, maybe with an if statement and a variable as flag:

<template>
  <div class="container">
    <div class="row mt-5">
      <div class="col" v-if="show">
        <h2>Positive</h2>
        <line-chart
          :chart-data="recentDonations"
          :options="chartOptions"
          label="Positive"
        >
        </line-chart>
      </div>
    </div>
  </div>
</template>

In your export default object, you can have this:

export default {
  name: 'Fundraiser',
  components: { LineChart },
  data () {
    return {
      show: false,
      recentDonations: [],
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      }
    }
  },
  async created () {
    const { data } = await axios({
      url: 'http://api.justgiving.com/[MY API KEY]/v1/crowdfunding/pages/[SOME-
      PAGE]/pledges',
      method: 'get',
      headers: {
        Accept: 'application/json'
      }
    })
    console.log(data)
    data.pledges.forEach(d => { // this part works fine.
      if (d.donationAmount != null) {
        const dateInEpochFormat = d.activityDate.substring(6, 16)
        const donationMade = moment.unix(dateInEpochFormat).format('MM/DD')
        this.recentDonations.push({ donationDate: donationMade, totalMoney:
        d.donationAmount })
      }
      console.log(this.recentDonations)
    })
    this.show = true;
  }
}

This is a workaround, You are waiting to have the data before render the graph, than way the first time that the graph is rendered, it can use the data and show the information.

The reason to not see data in the graph is because when the graph is rendered there is not information to show, once you get the response from the http request the graph is not updated, to do so, you must to watch the chartData prop, and once chartData is updated, you must call the chart.js update graph method (you can read more about it here: https://www.chartjs.org/docs/latest/developers/updates.html)

A better way to handle the data update is to assign the value to this.recentDonations after the forEach, that way you are not getting updates every time a pledge is pushed:
    ...
    const donations = [];
    data.pledges.forEach(d => { // this part works fine.
      if (d.donationAmount != null) {
        const dateInEpochFormat = d.activityDate.substring(6, 16)
        const donationMade = moment.unix(dateInEpochFormat).format('MM/DD')
        donations.push({ donationDate: donationMade, totalMoney:
        d.donationAmount })
      }
      console.log(this.recentDonations)
    })
    this.recentDonation = donations;
    this.show = true;
    ...

I did a test with a timeout function using this code (I don't know how to use the justgiving api):

<template>
  <div class="container">
    <div class="row mt-5">
      <div class="col" v-if="show">
        <h2>Positive</h2>
        <line-chart
          :chart-data="recentDonations"
          :options="chartOptions"
          label="Positive"
        >
        </line-chart>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import moment from "moment";
import LineChart from "../components/LineChart.vue";

export default {
  name: "Fundraiser",
  components: { LineChart },
  data() {
    return {
      show: false,
      recentDonations: [],
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      }
    };
  },
  methods: {
    request() {
      const pledges = [
        { donationDate: "11/08", donationAmount: 5 },
        { donationDate: "11/09", donationAmount: 5 },
        { donationDate: "11/10", donationAmount: 5 },
        { donationDate: "11/11", donationAmount: 5 },
        { donationDate: "11/12", donationAmount: 5 },
        { donationDate: "11/13", donationAmount: 5 },
        { donationDate: "11/14", donationAmount: 5 },
        { donationDate: "11/15", donationAmount: 5 },
        { donationDate: "11/16", donationAmount: 5 },
        { donationDate: "11/17", donationAmount: 5 },
        { donationDate: "11/18", donationAmount: 5 },
        { donationDate: "11/19", donationAmount: 5 },
        { donationDate: "11/20", donationAmount: 5 },
        { donationDate: "11/21", donationAmount: 5 },
        { donationDate: "11/22", donationAmount: 5 }
      ];
      pledges.forEach(d => {
        // this part works fine.
        // if (d.donationAmount != null) {
        // const dateInEpochFormat = d.activityDate.substring(6, 16);
        // const donationMade = moment.unix(dateInEpochFormat).format("MM/DD");
        this.recentDonations.push({
          donationDate: d.donationDate,
          totalMoney: d.donationAmount
        });
        // }
        console.log(this.recentDonations);
      });
      this.show = true;
    }
  },
  async created() {
    await setTimeout(this.request, 1000);
  }
};
</script>

If you remove the if statement, the graph doesn't show any data


问:
How to ignore everything after the first character input
I would like to get rid of everything after the first char of a user input.

Everything is working fine, but I'm handling edge cases and if a user types something for example 'nfff' it would cause two functions to occur, when 'n' is entered as an input and when 'f' is entered as an input. I am aware that this can be solved using if (str[0] == 'n') { function() }, but I'd rather not use more memory with string.

Is there a more efficient way to discard everything after the first character?

答:
You can use scanf or getchar.

For example,

char my_char;
scanf("%c", &my_char);
```

So, this will ignore everything after the first character.

Body:
You can use scanf or getchar.

For example,

char my_char;
scanf("%c", &my_char);

So, this will ignore everything after the first character.


答:
Change IFS to an ANSI-C quoted string or remove IFS (since the default value already contains tab).
You can also use a process substitution and prevent the temporary file.

```<code>while IFS=$'\t' read -r f1 f2; do
  yes "$f1" | head -n "$f2"
done < <(paste file1 file2) > output.list
</code>```

Title: How do I print a line in one file based on a corresponding value in a second file?

Body:
I have two files:
File1:

A
B
C

File2:

2
4
3

I would like to print each line in file1 the number of times found on the corresponding line of file2, and then append each line to a separate file.

Desired output:

A
A
B
B
B
B
C
C
C

Here is one of the approaches I have tried:

touch output.list
paste file1 file2 > test.dict
cat test.dict

A       2
B       4
C       3

while IFS="\t" read -r f1 f2
do
   yes "$f1" | head -n "$f2" >> output.list
done < test.dict

For my output I get a bunch of lines that read:

head: : invalid number of lines

Any guidance would be greatly appreciated. Thanks!

Body:
Change IFS to an ANSI-C quoted string or remove IFS (since the default value already contains tab).
You can also use a process substitution and prevent the temporary file.

while IFS=$'\t' read -r f1 f2; do
  yes "$f1" | head -n "$f2"
done < <(paste file1 file2) > output.list


问:
Loop through array in react onclick using Hooks
I have an array of objects that I load from a json file and I want each item to load separately when I click a button. I completed that but the main problem is when the index goes out of bounds so then it shows

TypeError "Cannot read property 'content' of undefined".

How can I make then index be 0 again when the index reaches the last item? I tried solving it by including some if statements inside the button but no luck.
Here is the related part of the code till now:

```<code>function App() {
  const classes = useStyles();
  const questions_size = Data.length;
  const [num, setNum] = useState(0);
  const current = Data[num].content;

  (...)
  return (
    <Container>
      <Typography variant="h3" gutterBottom>
        About
      </Typography>
      <Button variant="contained" color="primary" onClick={()=> num<questions_size?setNum(num+1): setNum(0)}>Επομενο</Button>
      <Card className={classes.root}>
        <CardContent>

          <Typography variant="body1" gutterBottom>
            <p style={{ fontFamily: 'Tangerine, serif', fontSize: '35px', textShadow: '4px 4px 4px #aaa'}}>{current}</p>
          </Typography>
        </CardContent>
      </Card>
    </Container>
  )
</code>```

答:
The issue with your current approach is that the highest valid index is questions_size - 1, it should work like this:

```<code>onClick={() => num < questions_size - 1 ? setNum(num + 1) : setNum(0)}
</code>```

Another option is to use the remainder operator:

```<code>onClick={() => setNum(num + 1 % questions_size)}
</code>```

Body:
I have an array of objects that I load from a json file and I want each item to load separately when I click a button. I completed that but the main problem is when the index goes out of bounds so then it shows

TypeError "Cannot read property 'content' of undefined".

How can I make then index be 0 again when the index reaches the last item? I tried solving it by including some if statements inside the button but no luck.
Here is the related part of the code till now:

function App() {
  const classes = useStyles();
  const questions_size = Data.length;
  const [num, setNum] = useState(0);
  const current = Data[num].content;

  (...)
  return (
    <Container>
      <Typography variant="h3" gutterBottom>
        About
      </Typography>
      <Button variant="contained" color="primary" onClick={()=> num<questions_size?setNum(num+1): setNum(0)}>Επομενο</Button>
      <Card className={classes.root}>
        <CardContent>

          <Typography variant="body1" gutterBottom>

{current}

          </Typography>
        </CardContent>
      </Card>
    </Container>
  )

Body:
The issue with your current approach is that the highest valid index is questions_size - 1, it should work like this:

onClick={() => num < questions_size - 1 ? setNum(num + 1) : setNum(0)}

Another option is to use the remainder operator:

onClick={() => setNum(num + 1 % questions_size)}


问:
How do you create a file in assembly with a dynamically specified file path?
This question is mainly how to handle the pathname which is an arbitrarily long string, in assembly, without db or any helpers like that. I have seen several examples such as this which shows:

```<code>section .text
   global _start         ;must be declared for using gcc

_start:                  ;tell linker entry point
   ;create the file
   mov  eax, 8
   mov  ebx, file_name
   mov  ecx, 0777        ;read, write and execute by all
   int  0x80             ;call kernel

   section  .data
file_name db 'myfile.txt'
</code>```

However, I would specifically like to understand how to do this dynamically. I would like to (1) better understand the requirements of the filename in terms of assembly (does it need a null terminator, etc.), and more importantly (2) specify the file name without the use of db or any assembler helpers. For example, you could specify the file name through the command line, and its structure would be unknown to the object file.

How do you do this?

答:
System calls that take a const char* without a length arg always take C strings: 0-terminated, implicit length.

Like open(const char *path, int flags, int mode), unlike write(int fd, void *buf, size_t len).

This is why they work when called from C like open("input.txt", O_RDONLY), or open(argv[1], O_WRONLY|O_CREAT).  Remember that C string literals give you a pointer to an array of char in static storage with a 0 terminator.

BTW, NULL is a pointer constant.  NUL is ASCII '\0'.  Just call them "0 terminated" strings.

So yes, you should use , 0 at the end of your db.

Command-line args are always in this C-string format; it's how Unix passes around string data across system-call / process boundaries, as well as to ISO C standard library functions.  This includes all pathnames.

In Linux, on entry to _start, the stack pointer points at argc.  Above that are the elements of the char *argv[] array.  (Not a char **argv pointer, just an array of values right there on the stack, from ESP+4 to ESP+argc*4.  Also terminated by a NULL pointer (0)).  This is documented in the i386 and x86-64 System V ABI docs.

Linux Assembly x86_64 create a file using command line parameters shows an example of loading argv[1] into the pathname arg of a system call.

Reading from a file in assembly is a 32-bit example.

Body:
This question is mainly how to handle the pathname which is an arbitrarily long string, in assembly, without db or any helpers like that. I have seen several examples such as this which shows:

section .text
   global _start         ;must be declared for using gcc

_start:                  ;tell linker entry point
   ;create the file
   mov  eax, 8
   mov  ebx, file_name
   mov  ecx, 0777        ;read, write and execute by all
   int  0x80             ;call kernel

   section  .data
file_name db 'myfile.txt'

However, I would specifically like to understand how to do this dynamically. I would like to (1) better understand the requirements of the filename in terms of assembly (does it need a null terminator, etc.), and more importantly (2) specify the file name without the use of db or any assembler helpers. For example, you could specify the file name through the command line, and its structure would be unknown to the object file.

How do you do this?


问:
how to create a oauth client id for gcp programmatically
I can create OAuth2.0 Client IDs and Client Secret with Authorized redirect URIs using the GUI in GCP.. The Console URL is given below for reference

https://console.cloud.google.com/apis/credentials

How do we do this in cloud shell or with the GCloud SDK

答:
As of terraform-provider-google version 3.15, you can do this using the google_iap_client resource:

https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/iap_client

```<code>
resource "google_iap_brand" "project_brand" {
  support_email     = "support@example.com"
  application_title = "Cloud IAP protected Application"
  project           = google_project_service.project_service.project
}

resource "google_iap_client" "project_client" {
  display_name = "Test Client"
  brand        =  google_iap_brand.project_brand.name
}
</code>```

Body:
As of terraform-provider-google version 3.15, you can do this using the google_iap_client resource:

https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/iap_client

resource "google_iap_brand" "project_brand" {
  support_email     = "support@example.com"
  application_title = "Cloud IAP protected Application"
  project           = google_project_service.project_service.project
}

resource "google_iap_client" "project_client" {
  display_name = "Test Client"
  brand        =  google_iap_brand.project_brand.name
}