问:
Can the Django admin be configured to save generic content types with the id of the base model of an inherited model?
I'm using Django 1.3.

I have a base model  (not abstract) called BasicPost. I have a model inheriting from it called PostWithImage. BasicPost has a couple of  generic relations.

In models.py:

```<code>class BasicPost(models.Model):
   ...
   authors = generic.GenericRelation(OrderedCredit,
   verbose_name=_('authors'), blank=True, null=True)
   ...
   tags = generic.GenericRelation(TaggedItem, verbose_name=_('tags'),
                                  blank=True, null=True)
   ...

class PostWithImage(BasicPost):
   ...
</code>```

In admin.py:

```<code>class TaggedItemInline(generic.GenericTabularInline):
    ...
    model = TaggedItem
    ...

class OrderedCreditInline(generic.GenericTabularInline):
    ... # same concept as above

class BasicPostAdmin(admin.ModelAdmin):
    inlines = [OrderedCreditInline, TaggedItemInline]

class PostWithImageAdmin(BasicPostAdmin):
    ...
</code>```

When I save an object on the PostWithImage admin screen, it sets the content_type of my generic fields equal to PostWithImage. However if I want to now retrieve all posts (irrespective of whether they're a BasicPost, PostWithImage or any other kind of post) with a particular tag, I run into problems. No simple query will do it, because the tags are pointing to a bunch of different models. I have found a workaround, but it's very ugly (see below).

My question is: Is there a way I can coerce the admin interface into saving the tags with content_type pointing to the base class, i.e. BasicPost?

Here's the ugly workaround. It's very difficult for a programmer to decipher
and I suspect it generates very expensive database hits.

```<code>class BasicPost(models.Model)

   # This code uses model_utils select_subclasses method

   def get_related_posts(self):
      tags = self.tags.all()

      return BasicPost.objects.filter(
        pk__in=
            [t.object_id for t in
                TaggedItem.objects.filter(tag__name__in=[t.tag.name for t in tags])
                    if isinstance(t.content_type.model_class()(), BasicPost)])\
                        .select_subclasses().order_by('-date_published')
</code>```

答:
If its not an abstract, than you might have to do it the dirty way. Django documentation shows that if you use a one to many link, that you could basically query everything. Because thats not the case, the dirty way might be the only way. I haven't used enough Django to tell right off the bat.

I would suggest you look at the django book, http://www.djangobook.com/en/2.0/

This book has it all. When I was programming a django server a month ago, this became my one stop shop reference.

I hope this helps.

Body:
I'm using Django 1.3.

I have a base model  (not abstract) called BasicPost. I have a model inheriting from it called PostWithImage. BasicPost has a couple of  generic relations.

In models.py:

class BasicPost(models.Model):
   ...
   authors = generic.GenericRelation(OrderedCredit,
   verbose_name=_('authors'), blank=True, null=True)
   ...
   tags = generic.GenericRelation(TaggedItem, verbose_name=_('tags'),
                                  blank=True, null=True)
   ...

class PostWithImage(BasicPost):
   ...

In admin.py:

class TaggedItemInline(generic.GenericTabularInline):
    ...
    model = TaggedItem
    ...

class OrderedCreditInline(generic.GenericTabularInline):
    ... # same concept as above

class BasicPostAdmin(admin.ModelAdmin):
    inlines = [OrderedCreditInline, TaggedItemInline]

class PostWithImageAdmin(BasicPostAdmin):
    ...

When I save an object on the PostWithImage admin screen, it sets the content_type of my generic fields equal to PostWithImage. However if I want to now retrieve all posts (irrespective of whether they're a BasicPost, PostWithImage or any other kind of post) with a particular tag, I run into problems. No simple query will do it, because the tags are pointing to a bunch of different models. I have found a workaround, but it's very ugly (see below).

My question is: Is there a way I can coerce the admin interface into saving the tags with content_type pointing to the base class, i.e. BasicPost?

Here's the ugly workaround. It's very difficult for a programmer to decipher
and I suspect it generates very expensive database hits.

class BasicPost(models.Model)

   # This code uses model_utils select_subclasses method

   def get_related_posts(self):
      tags = self.tags.all()

      return BasicPost.objects.filter(
        pk__in=
            [t.object_id for t in
                TaggedItem.objects.filter(tag__name__in=[t.tag.name for t in tags])
                    if isinstance(t.content_type.model_class()(), BasicPost)])\
                        .select_subclasses().order_by('-date_published')


来源: stackexchange

问:
Doesn't see records in admin site of django
I have a problem with one of my tables that I created in my django Project. The recording of data via administration site is very good, but I do not see any record. when I try to see the records in recent actions, I get the following message "Produit with ID "None" doesn't exist. Perhaps it was deleted?"

Image of django administration site with the warning message

答:
Maybe because you haven't add
MEDIA_URL = os.path.join(BASE_DIR, 'media/')
MEDIA_ROOT = '/media/'
 to your project's settings.py file.

ContentLicense: CC BY-SA 4.0


问:
How can I multiply multiple dataframes of a list by each observation of a vector?
I have a list of dataframes that I would like to multiply for each element of vector.

The first dataframe in the list would be multiplied by the first observation of the vector, and so on, producing another list of dataframes already multiplied.

I tried to do this with a loop, but was unsuccessful. I also tried to imagine something using map or lapply, but I couldn't.

```<code>for(i in vec){
  for(j in listdf){
     listdf2 <- i*listdf[[j]]
    }
}

Error in listdf[[j]] : invalid subscript type 'list'
</code>```

Any idea how to solve this?

*Vector and the List of Dataframes have the same length.

答:
Use Map :

```<code>listdf2 <- Map(`*`, listdf, vec)
</code>```

in purrr this can be done using map2 :

```<code>listdf2 <- purrr::map2(listdf, vec, `*`)
</code>```

If you are interested in for loop solution you just need one loop :

```<code>listdf2 <- vector('list', length(listdf))
for (i in seq_along(vec)) {
   listdf2[[i]] <- listdf[[i]] * vec[i]
}
</code>```

data

```<code>vec <- c(4, 3, 5)
df <- data.frame(a = 1:5, b = 3:7)
listdf <- list(df, df, df)
</code>```

Body:
I have a list of dataframes that I would like to multiply for each element of vector.

The first dataframe in the list would be multiplied by the first observation of the vector, and so on, producing another list of dataframes already multiplied.

I tried to do this with a loop, but was unsuccessful. I also tried to imagine something using map or lapply, but I couldn't.

for(i in vec){
  for(j in listdf){
     listdf2 <- i*listdf[[j]]
    }
}

Error in listdf[[j]] : invalid subscript type 'list'

Any idea how to solve this?

*Vector and the List of Dataframes have the same length.

Body:
Use Map :

listdf2 <- Map(`*`, listdf, vec)

in purrr this can be done using map2 :

listdf2 <- purrr::map2(listdf, vec, `*`)

If you are interested in for loop solution you just need one loop :

listdf2 <- vector('list', length(listdf))
for (i in seq_along(vec)) {
   listdf2[[i]] <- listdf[[i]] * vec[i]
}

data

vec <- c(4, 3, 5)
df <- data.frame(a = 1:5, b = 3:7)
listdf <- list(df, df, df)


问:
Access Lambda environment variables from .env file
I am running .net core 3.1 AWS Lambda function but I am unable to access the environment variable from the AWS Lambda Console in c# using:

```<code>var envVariable = Environment.GetEnvironmentVariable("myVariableName");
</code>```

The environment variables are stored in a .env file in the root of my lambda function. Does the .env file need to be copied into the build folder for it to be accessible in the lambda function?. How can I access the AWS Lambda environment variable from the .env file?

Application Structure

cloudformation-template.json refers to .env file.

update: 5/31/2020:

I removed the .env file and added the variables in the cloudformation-template.json directly as individual variables. When I try to push the same to aws using amplify publish command, I get a

```<code>Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete error
</code>```

答:
I am able to solve this issue by adding environment variables directly to the cloudformation-template.json and running the amplify publish command to push to aws.

```<code>"Environment": {
                    "Variables": {
                        "VUE_APP_STRIPE_PUBLISHABLE_KEY": "<someRandomString>",
                        "VUE_APP_STRIPE_SECRET_KEY": "<someRandomString>"
                    }
                },
</code>```

Body:
I am running .net core 3.1 AWS Lambda function but I am unable to access the environment variable from the AWS Lambda Console in c# using:

var envVariable = Environment.GetEnvironmentVariable("myVariableName");

The environment variables are stored in a .env file in the root of my lambda function. Does the .env file need to be copied into the build folder for it to be accessible in the lambda function?. How can I access the AWS Lambda environment variable from the .env file?

Application Structure

cloudformation-template.json refers to .env file.

update: 5/31/2020:

I removed the .env file and added the variables in the cloudformation-template.json directly as individual variables. When I try to push the same to aws using amplify publish command, I get a

Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete error

Body:
I am able to solve this issue by adding environment variables directly to the cloudformation-template.json and running the amplify publish command to push to aws.

"Environment": {
                    "Variables": {
                        "VUE_APP_STRIPE_PUBLISHABLE_KEY": "<someRandomString>",
                        "VUE_APP_STRIPE_SECRET_KEY": "<someRandomString>"
                    }
                },


问:
How to convert numbers in an hour column to actual hours
I have an 'hour' column in a pandas dataframe that is simply a list of numbers from 0 to 23 representing hours.  How can I convert them to an hour format such as 01:00 when the numbers are single digit ( like 1 ) and double digit (like 18)?  The single digit numbers need to have a leading zero, a colon and two trailing zeros.  The double digit numbers need only a colon and two trailing zeros.  How can this be accomplished in a dataframe?  Also, I have a 'date' column that needs to merge with the hour column after the hour column is converted.

```<code> e.g.    date           hour
           2018-07-01     0
           2018-07-01     1
           2018-07-01     3
           ...
           2018-07-01     21
           2018-07-01     22
           2018-07-01     23

Needs to look like:
          date
          2018-07-01 01:00
          ...
          2018-07-01 23:00
</code>```

The source of the data is a .csv file.
Thanks for your consideration. I'm new to pandas and I can't find in their documentation how to do  this considering the single and double digit numbers.

Body:
I have an 'hour' column in a pandas dataframe that is simply a list of numbers from 0 to 23 representing hours.  How can I convert them to an hour format such as 01:00 when the numbers are single digit ( like 1 ) and double digit (like 18)?  The single digit numbers need to have a leading zero, a colon and two trailing zeros.  The double digit numbers need only a colon and two trailing zeros.  How can this be accomplished in a dataframe?  Also, I have a 'date' column that needs to merge with the hour column after the hour column is converted.

 e.g.    date           hour
           2018-07-01     0
           2018-07-01     1
           2018-07-01     3
           ...
           2018-07-01     21
           2018-07-01     22
           2018-07-01     23

Needs to look like:
          date
          2018-07-01 01:00
          ...
          2018-07-01 23:00

The source of the data is a .csv file.
Thanks for your consideration. I'm new to pandas and I can't find in their documentation how to do  this considering the single and double digit numbers.

Body:
Convert hours to timedeltas by to_timedelta and add to datetimes converted by to_datetime if necessary:

df['date'] = pd.to_datetime(df['date']) + pd.to_timedelta(df['hour'], unit='h')
print (df)
                 date  hour
0 2018-07-01 00:00:00     0
1 2018-07-01 01:00:00     1
2 2018-07-01 03:00:00     3
3 2018-07-01 21:00:00    21
4 2018-07-01 22:00:00    22
5 2018-07-01 23:00:00    23

If need also remove hour column use DataFrame.pop

df['date'] = pd.to_datetime(df['date']) + pd.to_timedelta(df.pop('hour'), unit='h')
print (df)
                 date
0 2018-07-01 00:00:00
1 2018-07-01 01:00:00
2 2018-07-01 03:00:00
3 2018-07-01 21:00:00
4 2018-07-01 22:00:00
5 2018-07-01 23:00:00


问:
Doing the opposite of dropna in pandas dataframe
I'm sure this is easy to do but I cant seem to find an answer on stack overflow. I have the following dataframe.

```<code># Import pandas library
import pandas as pd
import numpy as np

# initialize list of lists
data = [['tom', 10,1], ['nick', 15,np.nan], ['juli', 14,1], ['mick', 15,np.nan], ['james', 18,1], ['nathan', 15,np.nan], ['jason', 17,1]
       , ['ted', 14,np.nan], ['ben',16 ,1], ['dom', 22,1]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age','Excuse'])
print(df)

    Name  Age  Excuse
0     tom   10     1.0
1    nick   15     NaN
2    juli   14     1.0
3    mick   15     NaN
4   james   18     1.0
5  nathan   15     NaN
6   jason   17     1.0
7     ted   14     NaN
8     ben   16     1.0
9     dom   22     1.0
</code>```

and I am hoping to delete all rows which have an excuse so that i get:

```<code>   Name  Age  Excuse

1    nick   15     NaN
3    mick   15     NaN
5  nathan   15     NaN
7     ted   14     NaN
</code>```

Any ideas? is there a function for the opposite of df = df.dropna(subset=['Excuse'])? Thanks!

答:
Please try

```<code>df[df.Excuse.isna()]
</code>```

Body:
I'm sure this is easy to do but I cant seem to find an answer on stack overflow. I have the following dataframe.

# Import pandas library
import pandas as pd
import numpy as np

# initialize list of lists
data = [['tom', 10,1], ['nick', 15,np.nan], ['juli', 14,1], ['mick', 15,np.nan], ['james', 18,1], ['nathan', 15,np.nan], ['jason', 17,1]
       , ['ted', 14,np.nan], ['ben',16 ,1], ['dom', 22,1]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age','Excuse'])
print(df)

    Name  Age  Excuse
0     tom   10     1.0
1    nick   15     NaN
2    juli   14     1.0
3    mick   15     NaN
4   james   18     1.0
5  nathan   15     NaN
6   jason   17     1.0
7     ted   14     NaN
8     ben   16     1.0
9     dom   22     1.0

and I am hoping to delete all rows which have an excuse so that i get:

   Name  Age  Excuse

1    nick   15     NaN
3    mick   15     NaN
5  nathan   15     NaN
7     ted   14     NaN

Any ideas? is there a function for the opposite of df = df.dropna(subset=['Excuse'])? Thanks!

Body:
Please try

df[df.Excuse.isna()]


问:
TFS vs open source alternatives?
We're currently in the process of setting up a source control/build/and more-server for .NET development and we're thinking about either utilizing the Team Foundation Server (which costs a lot of dough) or combining several open source options, such as SourceForge Enterprise/GForge and Subversion and CruiseControl.net and so on. Has anyone walked down the full blown OSS road or is it TFS only if you want to get it right and get to work soon?</p>

答:
Subversion + Cruisecontol.Net is a good alternative.
SVN is is feature-rich, stable and flexible.</p>

OwnerDisplayName: Microserf

ContentLicense: CC BY-SA 2.5

Title: TFS vs open source alternatives?

LastEditorDisplayName: Huppie

OwnerDisplayName: Anthony


问:
Accessing SharePoint through Java Application
HI

I want to access my sharepoint site through my java application or through jsp pages. At my website user can search and download documents from sharepoint document library.if any java api? plz send me sample code..

Regards
Siva

答:
You can check out WSRP then you may be able to show your web parts in java portlets.
http://en.wikipedia.org/wiki/Web_Services_for_Remote_Portlets
I remeber testing it in SharePoint 2007 to show lists in a java portlets. </p>

ContentLicense: CC BY-SA 3.0


问:
Unity object reference not set to an instance of an object unity
I have a "object reference not set to an instance of an object unity" errors even though I have an instance of object in project.

```<code>26: teslaGun = GameObject.Find("TeslaGun");
27: teslaGunController = teslaGun.GetComponent<TeslaGunController>();

35: arms = GameObject.Find("Arms").gameObject;

47: if (arms.activeSelf)
</code>```

答: It isn't a good idea to find a Gameobject with its name. You can use FindObjectOfType instead of Find. Also you can make teslaGam and arms public and set them in inspector.

Body:
I have a "object reference not set to an instance of an object unity" errors even though I have an instance of object in project.

26: teslaGun = GameObject.Find("TeslaGun");
27: teslaGunController = teslaGun.GetComponent<TeslaGunController>();

35: arms = GameObject.Find("Arms").gameObject;

47: if (arms.activeSelf)


问:
Skip JWT Auth during Tests ASP.Net Core 3.1 Web Api
I a have a very simple app with one JWT authenticated controller:

[ApiController]
[Authorize]
[Route("[controller]")]
public class JwtController : ControllerBase
{

    public JwtController() { }

    [HttpGet]
    public ActionResult Get() => Ok("Working!");
}
```

<p>With the authentication configured as:</p>

<pre class="lang-cs prettyprint-override"><code>services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false
    };
});
</code>```

During tests, i want the user to be "authenticated" all the time so that [Authorize] would be skipped.

[Fact]
public async Task JwtIsSkipped()
{
    var response = (await _Client.GetAsync("/jwt")).EnsureSuccessStatusCode();
    var stringResponse = await response.Content.ReadAsStringAsync();

    Assert.Equal("Working!", stringResponse);
}
```

<p>Running the test like this will fail, so following this doc I added this simple auth handler:</p>

<pre class="lang-cs prettyprint-override"><code>public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public const string DefaultScheme = "Test";
    public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
        var identity = new ClaimsIdentity(claims, DefaultScheme);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, DefaultScheme);

        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}
</code>```

So now my test class looks like this:

public class UnitTest : IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _Factory;
    private readonly HttpClient _Client;

    public UnitTest(WebApplicationFactory<Startup> factory)
    {
        _Factory = factory;
        _Client = _Factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureTestServices(services =>
            {
                services.AddAuthentication(TestAuthHandler.DefaultScheme)
                        .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
                            TestAuthHandler.DefaultScheme, options => { });
            });
        }).CreateClient();

        _Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(TestAuthHandler.DefaultScheme);
    }

    [Fact]
    public async Task JwtIsSkipped()
    {
        var response = (await _Client.GetAsync("/jwt")).EnsureSuccessStatusCode();
        var stringResponse = await response.Content.ReadAsStringAsync();

        Assert.Equal("Working!", stringResponse);
    }
}
```

And it still fails, I have no idea what I'm doing wrong.

答:
You need to set DefaultAuthenticateScheme

```<code>builder.ConfigureTestServices(services =>
{
    services.AddAuthentication(options =>
    {
        x.DefaultAuthenticateScheme = TestAuthHandler.DefaultScheme;
        x.DefaultScheme = TestAuthHandler.DefaultScheme;
    }).AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
           TestAuthHandler.DefaultScheme, options => { });
});
</code>```

Body:
I a have a very simple app with one JWT authenticated controller:

[ApiController]
[Authorize]
[Route("[controller]")]
public class JwtController : ControllerBase
{

    public JwtController() { }

    [HttpGet]
    public ActionResult Get() => Ok("Working!");
}

With the authentication configured as:

services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false
    };
});

During tests, i want the user to be "authenticated" all the time so that [Authorize] would be skipped.

[Fact]
public async Task JwtIsSkipped()
{
    var response = (await _Client.GetAsync("/jwt")).EnsureSuccessStatusCode();
    var stringResponse = await response.Content.ReadAsStringAsync();

    Assert.Equal("Working!", stringResponse);
}

Running the test like this will fail, so following this doc I added this simple auth handler:

public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public const string DefaultScheme = "Test";
    public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
        var identity = new ClaimsIdentity(claims, DefaultScheme);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, DefaultScheme);

        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}

So now my test class looks like this:

public class UnitTest : IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _Factory;
    private readonly HttpClient _Client;

    public UnitTest(WebApplicationFactory<Startup> factory)
    {
        _Factory = factory;
        _Client = _Factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureTestServices(services =>
            {
                services.AddAuthentication(TestAuthHandler.DefaultScheme)
                        .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
                            TestAuthHandler.DefaultScheme, options => { });
            });
        }).CreateClient();

        _Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(TestAuthHandler.DefaultScheme);
    }

    [Fact]
    public async Task JwtIsSkipped()
    {
        var response = (await _Client.GetAsync("/jwt")).EnsureSuccessStatusCode();
        var stringResponse = await response.Content.ReadAsStringAsync();

        Assert.Equal("Working!", stringResponse);
    }
}

And it still fails, I have no idea what I'm doing wrong.

Body:
You need to set DefaultAuthenticateScheme

builder.ConfigureTestServices(services =>
{
    services.AddAuthentication(options =>
    {
        x.DefaultAuthenticateScheme = TestAuthHandler.DefaultScheme;
        x.DefaultScheme = TestAuthHandler.DefaultScheme;
    }).AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
           TestAuthHandler.DefaultScheme, options => { });
});


问:
Import data between spreadsheets where column = value?
Note: My question is similar Googe Spreadsheets' ImportRange function.

Is it possible in Google Spreadsheets or Microsoft Excel to import data based on cell values?

For example, can I copy contents of Sheet1 to another sheet where column B == "foo"?

Target (Sheet1):

The destination sheet should only copy Row 2 and 4 since those are the only ones containing "foo"

Edit:

For Google Docs, I am looking to something like this:

=ImportRange("spreadsheetkey", QUERY('sheetname'!A6:E10, "SELECT A, B = 'foo'")) however I can't get it to work.

答:
You can do it with FILTER function:</p>

```<code>=FILTER(IMPORTRANGE("spreadsheet_url", "'sheet_name'!A6:E10"),
IMPORTRANGE("spreadsheet_url", "'sheet_name'!B6:B10")="foo")
</code>```

Body:
You can do it with FILTER function:

=FILTER(IMPORTRANGE("spreadsheet_url", "'sheet_name'!A6:E10"),
IMPORTRANGE("spreadsheet_url", "'sheet_name'!B6:B10")="foo")


问:
Read a text file line by line in Swift?
I just started learning Swift. I have got my code to read from the text file, and the App displays the content of the entire text file. How can I display line by line and call upon that line multiple times?

TextFile.txt contains the following:

```<code>1. Banana
2. Apple
3. pear
4. strawberry
5. blueberry
6. blackcurrant
</code>```

The following is what currently have..

```<code>  if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){
        var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)
            if let content = (data){
                TextView.text = content
    }
</code>```

If there is another way of doing this please let me know. It would be much appreciated.

答:
Swift 5.5

The solution below shows how to read one line at a time. This is quite different from reading the entire contents into memory. Reading line-by-line scales well if you have a large file to read. Putting an entire file into memory does not scale well for large files.

The example below uses a while loop that quits when there are no more lines, but you can choose a different number of lines to read if you wish.

The code works as follows:

create a URL that tells where the file is located

make sure the file exists

open the file for reading

set up some initial variables for reading

read each line using getLine()

close the file and free the buffer when done

You could make the code less verbose if you wish; I have included comments to explain what the variables' purposes are.

Swift 5.5

import Cocoa

// get URL to the the documents directory in the sandbox
let home = FileManager.default.homeDirectoryForCurrentUser

// add a filename
let fileUrl = home
    .appendingPathComponent("Documents")
    .appendingPathComponent("my_file")
    .appendingPathExtension("txt")

// make sure the file exists
guard FileManager.default.fileExists(atPath: fileUrl.path) else {
    preconditionFailure("file expected at \(fileUrl.absoluteString) is missing")
}

// open the file for reading
// note: user should be prompted the first time to allow reading from this location
guard let filePointer:UnsafeMutablePointer<FILE> = fopen(fileUrl.path,"r") else {
    preconditionFailure("Could not open file at \(fileUrl.absoluteString)")
}

// a pointer to a null-terminated, UTF-8 encoded sequence of bytes
var lineByteArrayPointer: UnsafeMutablePointer<CChar>? = nil

// see the official Swift documentation for more information on the `defer` statement
// https://docs.swift.org/swift-book/ReferenceManual/Statements.html#grammar_defer-statement
defer {
    // remember to close the file when done
    fclose(filePointer)

    // The buffer should be freed by even if getline() failed.
    lineByteArrayPointer?.deallocate()
}

// the smallest multiple of 16 that will fit the byte array for this line
var lineCap: Int = 0

// initial iteration
var bytesRead = getline(&lineByteArrayPointer, &lineCap, filePointer)

while (bytesRead > 0) {

    // note: this translates the sequence of bytes to a string using UTF-8 interpretation
    let lineAsString = String.init(cString:lineByteArrayPointer!)

    // do whatever you need to do with this single line of text
    // for debugging, can print it
    print(lineAsString)

    // updates number of bytes read, for the next iteration
    bytesRead = getline(&lineByteArrayPointer, &lineCap, filePointer)
}
```

Title: Read a text file line by line in Swift?

Body:
I just started learning Swift. I have got my code to read from the text file, and the App displays the content of the entire text file. How can I display line by line and call upon that line multiple times?

TextFile.txt contains the following:

1. Banana
2. Apple
3. pear
4. strawberry
5. blueberry
6. blackcurrant

The following is what currently have..

  if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){
        var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)
            if let content = (data){
                TextView.text = content
    }

If there is another way of doing this please let me know. It would be much appreciated.


问:
Is there way to programmatically enable GPS on Android 2.1 & above?
I have been seeing different posts that GPS cannot be enabled programmatically How do I find out if the GPS of an Android device is enabled

But this app enables the GPS when it is disabled. Can anyone please help me out.

Thanks,
Prateek

答:
If the documentation said that it can't be set programmatically, I suggest you not to do so. There are many impacts why the documentation said that. And if someone was able to do that (enabling the GPS programmatically), it means he/she doing something that was undocumented.

Activating GPS requires user's permission. If your application was able to activate the GPS without notifying the users (furthermore, asking for the user's permission), you might violate the privacy policy.


问:
Trying to use function from external .py file
I am using import DiGraph to import my external file and trying to run the following code:

prediction = DiGraph.remove_duplicates(make_trips(G, source='c1', target=['c2', 'c3']))

but I get NameError: name 'make_trips' is not defined

All the names are how they appear in my external file and it is even identical code besides the prediction =. What am I missing?

*Edit:
Thanks, Gilch, Kartikeya Sharma, and Nishat for the explanations.

答:
Did you mean DiGraph.make_trips?

Importing like that only gives you the one module object; it doesn't dump its contents into the current namespace. (You could use from DiGraph import * for that, but star imports get confusing fast, so they're generally not recommended.)

Now I get NameError: name 'G' is not defined. 'G' is a variable at the top of the file. How should I handle this? Thanks

At the top of the DiGraph file? You can do it the same way. DiGraph.G.

If DiGraph is too much to type, you can do

```<code>import DiGraph as dg
</code>```

instead of import DiGraph. Then you can refer to the DiGraph module as dg instead, e.g.

```<code>prediction = dg.remove_duplicates(dg.make_trips(dg.G, source='c1', target=['c2', 'c3']))
</code>```

Body:
Did you mean DiGraph.make_trips?

Importing like that only gives you the one module object; it doesn't dump its contents into the current namespace. (You could use from DiGraph import * for that, but star imports get confusing fast, so they're generally not recommended.)

Now I get NameError: name 'G' is not defined. 'G' is a variable at the top of the file. How should I handle this? Thanks

At the top of the DiGraph file? You can do it the same way. DiGraph.G.

If DiGraph is too much to type, you can do

import DiGraph as dg

instead of import DiGraph. Then you can refer to the DiGraph module as dg instead, e.g.

prediction = dg.remove_duplicates(dg.make_trips(dg.G, source='c1', target=['c2', 'c3']))


问:
How to load a C#/C++ dll in python?
Now I have only a DLL file which writen in C# and C++ mixed(C# code call the C++ natvie code inside) I know, I want to wrap this DLL file with Python(ctypes), using a refoctor(dnSpy) to reverse the DLL i found the function named s_set_server_public_key.

So my question is how to use Python to call this function? the DLL is attached, could you please give me some suggestion? Thanks very much!!!
enter image description here

答:
I think this answer is useful for you:

```<code>import ctypes

# Load DLL into memory.

hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")

# Set up prototype and parameters for the desired function call.
# HLLAPI

hllApiProto = ctypes.WINFUNCTYPE (
    ctypes.c_int,      # Return type.
    ctypes.c_void_p,   # Parameters 1 ...
    ctypes.c_void_p,
    ctypes.c_void_p,
    ctypes.c_void_p)   # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),

# Actually map the call ("HLLAPI(...)") to a Python name.

hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)

# This is how you can actually call the DLL function.
# Set up the variables and call the Python name with them.

p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p (sessionVar)
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))
</code>```

How can I use a DLL file from Python?

Title: How to load a C#/C++ dll in python?

Body:
I think this answer is useful for you:

import ctypes

# Load DLL into memory.

hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")

# Set up prototype and parameters for the desired function call.
# HLLAPI

hllApiProto = ctypes.WINFUNCTYPE (
    ctypes.c_int,      # Return type.
    ctypes.c_void_p,   # Parameters 1 ...
    ctypes.c_void_p,
    ctypes.c_void_p,
    ctypes.c_void_p)   # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),

# Actually map the call ("HLLAPI(...)") to a Python name.

hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)

# This is how you can actually call the DLL function.
# Set up the variables and call the Python name with them.

p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p (sessionVar)
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))

How can I use a DLL file from Python?


问:
How can you get the position and value from a row in an exact cover matrix for sudoku?
Using an exact cover matrix of sudoku such as the one here, each row in the matrix correlates to a position in the sudoku grid (row, column) and a value.

Given only the row number in the cover matrix, and the size of the sudoku grid (in that case 9), what is an algorithm for determining the row, column and value that the row refers to? (for example, row 1 refers to row 1, column 1 and value 1, row 12 refers to row 1, column 2, value 3)

答:
I wrote this in java which does solve the problem, however I am still curious if there is any way to do this without using a loop, it feels like a problem that could be expressed purely in math to me.

```<code>private int[] rowInGrid(int puzzleSize, int matrixRow) {
        // return the row, column and value correlating to a row in the cover matrix

        int row = 0;
        int col = 0;
        int val = 0;

        for (int i = 0; i < matrixRow; i++) {
            val++;

            if (val == puzzleSize) {
                col++;
                val = 0;
            }

            if (col == puzzleSize) {
                row++;
                col = 0;
            }
        }

        return new int[]{row,col,val};
    }
</code>```

The function takes the puzzle size (width/height/number of values) and the row number in the cover matrix (eg 0 refers to the first possible value in the first row and first column of the board) and returns the position on the board and the value. This function is all 0 indexed.

Body:
I wrote this in java which does solve the problem, however I am still curious if there is any way to do this without using a loop, it feels like a problem that could be expressed purely in math to me.

private int[] rowInGrid(int puzzleSize, int matrixRow) {
        // return the row, column and value correlating to a row in the cover matrix

        int row = 0;
        int col = 0;
        int val = 0;

        for (int i = 0; i < matrixRow; i++) {
            val++;

            if (val == puzzleSize) {
                col++;
                val = 0;
            }

            if (col == puzzleSize) {
                row++;
                col = 0;
            }
        }

        return new int[]{row,col,val};
    }

The function takes the puzzle size (width/height/number of values) and the row number in the cover matrix (eg 0 refers to the first possible value in the first row and first column of the board) and returns the position on the board and the value. This function is all 0 indexed.


问:
Using stdlib.h on xcode
How do I use system ("cls") or system ("pause") commands on xcode? Obviously he does not interpret them as they are not system commands, how can I do it?</p>

答:
What happens if you use the following code on Linux or macOS?

```<code>system("cls")
</code>```

Or,

```<code>system("md hello-folder")
</code>```

Obviously they won't work since the're unknown in Unix and macOS systems. Instead, they're platform dependent and only will work for Windows.

Although there are several commands which helps to clear the terminal screen, referring you to visit this thread of SO. You may try those commands under system().

Disclaimer: system() shouldn't be used on larger productions which are said to be platform-independent, more information here.

Title: Using stdlib.h on xcode

Body:
What happens if you use the following code on Linux or macOS?

system("cls")

Or,

system("md hello-folder")

Obviously they won't work since the're unknown in Unix and macOS systems. Instead, they're platform dependent and only will work for Windows.

Although there are several commands which helps to clear the terminal screen, referring you to visit this thread of SO. You may try those commands under system().

Disclaimer: system() shouldn't be used on larger productions which are said to be platform-independent, more information here.


问:
ejs@3.1.3 postinstall: `node --harmony ./postinstall.js Exit status 1
While I'm trying to install ejs using npm I'm getting this error and I'm not able to install ejs in my PC. can anyone help me with this?

答: I tried everything available in Google and finally, I got the solution npm install ejs --force by this command we can install ejs forcibly to your project.


问:
how to calculate errors in neural networks, when the size of the matrix dimensions of the output do not match the size of the label?
I tried to make code for image classification with neural networks without using libraries such as KERAS, etc.

but I have difficulty when I want to calculate the error, because the size of the matrix of the output feedforward does not match the size of the matrix label one hot multiclass

The following is the code for the one hot multiclass label, here I use 20 classes with each class having 15 variations (300 inputs, size = 64 x 64 pixels) :

```<code>labels_train = np.array([0] * 15 + [1] * 15 + [2] * 15 + [3] * 15 + [4] * 15 + [5] * 15 + [6] * 15 + [7]
                        * 15 + [8] * 15 + [9] * 15 + [10] * 15 + [11] * 15 + [12] * 15 + [13] * 15 + [14]
                        * 15 + [15] * 15 + [16] * 15 + [17] * 15 + [18] * 15 + [19] * 15)

y_train = np.zeros((300,20))

for i in range(300):
    y_train[i, labels_train[i]] = 1

</code>```

The following is the code for feedforward and calculation of the error value :

```<code>for epoch in range(1):

    hasil_ih = np.dot(W_ih, x_train) + B_ih
    output_ih = sigmoid(hasil_ih)

    hasil_hh = np.dot(W_hh, output_ih) + B_hh
    output_hh = sigmoid(hasil_hh)

    hasil_ho = np.dot(W_ho, output_hh) + B_ho
    output_ho = sigmoid(hasil_ho)

    print(output_ho.shape)
    print(y_train.shape)
    error_o = labels_train - output_ho

</code>```

and here are the results when the program is running :

```<code>Traceback (most recent call last):
(300, 4096)
  File "D:/Pengenalan_Induk_Aksara/NN2.py", line 71, in <module>
(300, 20)
    error_o = labels_train - output_ho
ValueError: operands could not be broadcast together with shapes (300,) (300,4096)

Process finished with exit code 1
</code>```

please help me, I'm still a beginner and I haven't found a solution. The following is the complete code :

```<code>import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import os

dir = "data_train/LBP_R1/"
kategori = ["ka","ga","nga","pa","ba","ma","ta","da","na","ca","ja","nya","ya","a","la","ra","sa","wa","ha","gha"]
features = []; label = []

for y in kategori:
    path = os.path.join(dir, y)
    class_num = kategori.index(y)
    label.append(class_num)

    for img in os.listdir(path):
        im = Image.open(os.path.join(path,img))
        imgs = list(im.getdata())
        features.append(imgs)

x_train = np.vstack([features])
x_train = (x_train/255)

labels_train = np.array([0] * 15 + [1] * 15 + [2] * 15 + [3] * 15 + [4] * 15 +
                        [5] * 15 + [6] * 15 + [7] * 15 + [8] * 15 + [9] * 15 +
                        [10] * 15 + [11] * 15 + [12] * 15 + [13] * 15 + [14] *
                        15 + [15] * 15 + [16] * 15 + [17] * 15 + [18] * 15 + [19]
                        * 15)

y_train = np.zeros((300,20))

for i in range(300):
    y_train[i, labels_train[i]] = 1

#Training Phase
def sigmoid(x):
    return 1/(1+np.exp(-x))

def dsigmoid(y):
    return y*(1-y)

attributes = x_train.shape[0]
hidden_nodes = 4
output_nodes = 300

np.random.seed(42)
W_ih = np.random.rand(hidden_nodes,attributes) #bobot input layer 1
B_ih = np.random.rand(hidden_nodes,1) #Bias input layer 1

W_hh = np.random.rand(hidden_nodes, hidden_nodes) #weight hidden layer 2
B_hh = np.random.rand(hidden_nodes, 1) #bias hidden layer 2

W_ho = np.random.rand(output_nodes, hidden_nodes) #weight hidden output
B_ho = np.random.rand(output_nodes, 1) #bias hidden output

lr = 0.25; #Learning rate

for epoch in range(1):

    hasil_ih = np.dot(W_ih, x_train) + B_ih
    output_ih = sigmoid(hasil_ih)

    hasil_hh = np.dot(W_hh, output_ih) + B_hh
    output_hh = sigmoid(hasil_hh)

    hasil_ho = np.dot(W_ho, output_hh) + B_ho
    output_ho = sigmoid(hasil_ho)

    print(output_ho.shape)
    print(y_train.shape)

    error_o = labels_train - output_ho
    print(output_ho)
    print(y_train)
    print(error_o)

</code>```

答:
Just take the index with max probability to get the class. But that will give you a number of failed cases.

```<code>output_ho_idx = np.argmax(output_ho)
error_o = labels_train - output_ho_idx
</code>```

You can also convert your labels to one-hot-encoding and estimate the error with the sigmoid output.

Body:
I tried to make code for image classification with neural networks without using libraries such as KERAS, etc.

but I have difficulty when I want to calculate the error, because the size of the matrix of the output feedforward does not match the size of the matrix label one hot multiclass

The following is the code for the one hot multiclass label, here I use 20 classes with each class having 15 variations (300 inputs, size = 64 x 64 pixels) :

labels_train = np.array([0] * 15 + [1] * 15 + [2] * 15 + [3] * 15 + [4] * 15 + [5] * 15 + [6] * 15 + [7]
                        * 15 + [8] * 15 + [9] * 15 + [10] * 15 + [11] * 15 + [12] * 15 + [13] * 15 + [14]
                        * 15 + [15] * 15 + [16] * 15 + [17] * 15 + [18] * 15 + [19] * 15)

y_train = np.zeros((300,20))

for i in range(300):
    y_train[i, labels_train[i]] = 1

The following is the code for feedforward and calculation of the error value :

for epoch in range(1):

    hasil_ih = np.dot(W_ih, x_train) + B_ih
    output_ih = sigmoid(hasil_ih)

    hasil_hh = np.dot(W_hh, output_ih) + B_hh
    output_hh = sigmoid(hasil_hh)

    hasil_ho = np.dot(W_ho, output_hh) + B_ho
    output_ho = sigmoid(hasil_ho)

    print(output_ho.shape)
    print(y_train.shape)
    error_o = labels_train - output_ho

and here are the results when the program is running :

Traceback (most recent call last):
(300, 4096)
  File "D:/Pengenalan_Induk_Aksara/NN2.py", line 71, in <module>
(300, 20)
    error_o = labels_train - output_ho
ValueError: operands could not be broadcast together with shapes (300,) (300,4096)

Process finished with exit code 1

please help me, I'm still a beginner and I haven't found a solution. The following is the complete code :

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import os

dir = "data_train/LBP_R1/"
kategori = ["ka","ga","nga","pa","ba","ma","ta","da","na","ca","ja","nya","ya","a","la","ra","sa","wa","ha","gha"]
features = []; label = []

for y in kategori:
    path = os.path.join(dir, y)
    class_num = kategori.index(y)
    label.append(class_num)

    for img in os.listdir(path):
        im = Image.open(os.path.join(path,img))
        imgs = list(im.getdata())
        features.append(imgs)

x_train = np.vstack([features])
x_train = (x_train/255)

labels_train = np.array([0] * 15 + [1] * 15 + [2] * 15 + [3] * 15 + [4] * 15 +
                        [5] * 15 + [6] * 15 + [7] * 15 + [8] * 15 + [9] * 15 +
                        [10] * 15 + [11] * 15 + [12] * 15 + [13] * 15 + [14] *
                        15 + [15] * 15 + [16] * 15 + [17] * 15 + [18] * 15 + [19]
                        * 15)

y_train = np.zeros((300,20))

for i in range(300):
    y_train[i, labels_train[i]] = 1

#Training Phase
def sigmoid(x):
    return 1/(1+np.exp(-x))

def dsigmoid(y):
    return y*(1-y)

attributes = x_train.shape[0]
hidden_nodes = 4
output_nodes = 300

np.random.seed(42)
W_ih = np.random.rand(hidden_nodes,attributes) #bobot input layer 1
B_ih = np.random.rand(hidden_nodes,1) #Bias input layer 1

W_hh = np.random.rand(hidden_nodes, hidden_nodes) #weight hidden layer 2
B_hh = np.random.rand(hidden_nodes, 1) #bias hidden layer 2

W_ho = np.random.rand(output_nodes, hidden_nodes) #weight hidden output
B_ho = np.random.rand(output_nodes, 1) #bias hidden output

lr = 0.25; #Learning rate

for epoch in range(1):

    hasil_ih = np.dot(W_ih, x_train) + B_ih
    output_ih = sigmoid(hasil_ih)

    hasil_hh = np.dot(W_hh, output_ih) + B_hh
    output_hh = sigmoid(hasil_hh)

    hasil_ho = np.dot(W_ho, output_hh) + B_ho
    output_ho = sigmoid(hasil_ho)

    print(output_ho.shape)
    print(y_train.shape)

    error_o = labels_train - output_ho
    print(output_ho)
    print(y_train)
    print(error_o)

Body:
Just take the index with max probability to get the class. But that will give you a number of failed cases.

output_ho_idx = np.argmax(output_ho)
error_o = labels_train - output_ho_idx

You can also convert your labels to one-hot-encoding and estimate the error with the sigmoid output.


问:
Azure devops repo to download a particular file from repo using RestApi
Trying to download a particular file abc.pdf from azure devops repository using RestApi's.  I was able to download the required file i wanted but not able to open the downloaded pdf file and also noted that downloaded file is twice the size of the original file in the repo.

```<code>$uri = "https://dev.azure.com/$($organization)/$($project)/_apis/git/repositories/$($repoId)/items?Path=$($appPath)&download=true&api-version=5.1"
$uri = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repoId/blobs/$($sha1_blob)?download=true&fileName=abc.pdf&api-version=5.1"
</code>```

$result = Invoke-RestMethod -Uri $uri -Method Get -Headers $header
$result | out-file "abc.pdf"

I am using powershell to make the rest call and tried with the above 2 url to download the file and it's downloading the file but at twice the size of the original..
am I missing something overhere?? these 2 are the restapi url i have used!!!
link for git blob from azure devops restapi

link for items to download from azure devops

答:
the problem was with the seperate $result | out-file "abc.pdf" with the encodings for pdf file.
instead used -outfile parameter in invoke-restmethod itself and the pdf file was copied successfully.

```<code>Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json" -Headers $header -outfile "abc.pdf"
</code>```

Body:
Trying to download a particular file abc.pdf from azure devops repository using RestApi's.  I was able to download the required file i wanted but not able to open the downloaded pdf file and also noted that downloaded file is twice the size of the original file in the repo.

$uri = "https://dev.azure.com/$($organization)/$($project)/_apis/git/repositories/$($repoId)/items?Path=$($appPath)&download=true&api-version=5.1"
$uri = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repoId/blobs/$($sha1_blob)?download=true&fileName=abc.pdf&api-version=5.1"

$result = Invoke-RestMethod -Uri $uri -Method Get -Headers $header
$result | out-file "abc.pdf"

I am using powershell to make the rest call and tried with the above 2 url to download the file and it's downloading the file but at twice the size of the original..
am I missing something overhere?? these 2 are the restapi url i have used!!!
link for git blob from azure devops restapi

link for items to download from azure devops

Body:
the problem was with the seperate $result | out-file "abc.pdf" with the encodings for pdf file.
instead used -outfile parameter in invoke-restmethod itself and the pdf file was copied successfully.

Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json" -Headers $header -outfile "abc.pdf"


问:
integer constant long long int?
```<code>long long int
</code>```

It seems to be valid in C. but is this valid in c++?

答: The data type long long int is valid only in the C99 and C++0x language standards, it is not valid in C90 or C++03.  Some compilers such as GCC permit it to be used in those earlier language versions as an extension—when compiling as C90.  GCC will give a warning on its usage if both the -Wlong-long and -pedantic options are specified.

Title: integer constant long long int?

Body:
long long int

It seems to be valid in C. but is this valid in c++?


问:
List of abstract class with generic parameter type?
Let's say I have these classes:

public abstract class Thing<T> { }

public class Str : Thing<string> { }

public class Boo : Thing<bool> { }
```

<p>I'd like to create a <code>List</code> of <code>Thing</code>.</p>

<p>This is an example of what I'd like to do (invalid C# code):</p>

```new List<Something>()
{
    new Str(),
    new Boo()
};
```

How could I do something like that, would it even be possible?

I found this but couldn't seem to correctly understand any of the proposed answers.

答:
To satisfy List<Something> then Thing<T> must inherit Something. The answers in the post you linked have the solution: you need to introduce a non-generic base class.

```<code>public abstract class Something { }
public abstract class Thing<T>: Something { }

public class Str : Thing<string> { }
public class Boo : Thing<bool> { }

new List<Something>()
{
    new Str(),
    new Boo()
};

</code>```

Body:
Let's say I have these classes:

public abstract class Thing<T> { }

public class Str : Thing<string> { }

public class Boo : Thing<bool> { }

I'd like to create a List of Thing.

This is an example of what I'd like to do (invalid C# code):

new List<Something>()
{
    new Str(),
    new Boo()
};

How could I do something like that, would it even be possible?

I found this but couldn't seem to correctly understand any of the proposed answers.

Body:
To satisfy List<Something> then Thing<T> must inherit Something. The answers in the post you linked have the solution: you need to introduce a non-generic base class.

public abstract class Something { }
public abstract class Thing<T>: Something { }

public class Str : Thing<string> { }
public class Boo : Thing<bool> { }

new List<Something>()
{
    new Str(),
    new Boo()
};


问:
Why does this DFS-based topological sort algorithm work?
Here is the algorithm that I pulled from this competitive programming resource.

```<code>int n; // number of vertices
vector<vector<int>> adj; // adjacency list of graph
vector<bool> visited;
vector<int> ans;

void dfs(int v) {
    visited[v] = true;
    for (int u : adj[v]) {
        if (!visited[u])
            dfs(u);
    }
    ans.push_back(v);
}

void topological_sort() {
    visited.assign(n, false);
    ans.clear();
    for (int i = 0; i < n; ++i) {
        if (!visited[i])
            dfs(i);
    }
    reverse(ans.begin(), ans.end());
}
</code>```

How does this algorithm avoid adding vertices to the topologically sorted collection that have incoming directed edges? Say, for example, that the first vertex (0 in this example) checked by the for loop has an incoming directed edge from vertex (1). What is stopping this algorithm from outputting (0) before first ensuring that (1) has been output?

答:
It's building the output vector backwards.  If there's an incoming directed edge from vertex (1) to vertex (0), you want to output (0) before (1).

Note that dfs(int v) calls ans.push_back(v) only after it recurses to all its descendants.  This ensures that anything that follows v will have been added to the output vector before v.  Anything not visited[] after dfs(0) returns is either unrelated to 0 or its descendants (and therefore can be added later), or precedes them (and therefore should be added later).

Body:
Here is the algorithm that I pulled from this competitive programming resource.

int n; // number of vertices
vector<vector<int>> adj; // adjacency list of graph
vector<bool> visited;
vector<int> ans;

void dfs(int v) {
    visited[v] = true;
    for (int u : adj[v]) {
        if (!visited[u])
            dfs(u);
    }
    ans.push_back(v);
}

void topological_sort() {
    visited.assign(n, false);
    ans.clear();
    for (int i = 0; i < n; ++i) {
        if (!visited[i])
            dfs(i);
    }
    reverse(ans.begin(), ans.end());
}

How does this algorithm avoid adding vertices to the topologically sorted collection that have incoming directed edges? Say, for example, that the first vertex (0 in this example) checked by the for loop has an incoming directed edge from vertex (1). What is stopping this algorithm from outputting (0) before first ensuring that (1) has been output?


问:
How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway
for instance if we want to use

GET /user?name=bob

or

GET /user/bob

How would you pass both of these examples as a parameter to the Lambda function?

I saw something about setting a "mapped from" in the documentation, but I can't find that setting in the API Gateway console.

method.request.path.parameter-name for a path parameter named parameter-name as defined in the Method Request page.

method.request.querystring.parameter-name for a query string parameter named parameter-name as defined in the Method Request page.

I don't see either of these options even though I defined a query string.

答:
Refer Doc :
https://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-lambda.html#api-as-lambda-proxy-expose-get-method-with-path-parameters-to-call-lambda-function

You need to modify the Mapping Template


问:
MPAndroid Chart dissapears after calling invalidate() with new data
In my Weather app, I have a MainFragment which has a button that opens a different fragment (SearchFragment) (via replace), allows a user to select a location and then fetches weather data for that location and loads it in various views including an MPAndroid LineChart. My issue is that whenever I come back from the search fragment, although the new data is fetched for the chart and I'm calling chart.notifyDataSetChanged() & chart.invalidate() (also tried chart.postInvalidate() since it was suggested when working on another thread) after the invalidate() is called the chart simply disappears. What am i missing here?

MainFragment:

```<code>const val UNIT_SYSTEM_KEY = "UNIT_SYSTEM"
const val LATEST_CURRENT_LOCATION_KEY = "LATEST_CURRENT_LOC"

class MainFragment : Fragment() {

// Lazy inject the view model
private val viewModel: WeatherViewModel by viewModel()
private lateinit var weatherUnitConverter: WeatherUnitConverter

private val TAG = MainFragment::class.java.simpleName

// View declarations
...

// OnClickListener to handle the current weather's "Details" layout expansion/collapse
private val onCurrentWeatherDetailsClicked = View.OnClickListener {
    if (detailsExpandedLayout.visibility == View.GONE) {
        detailsExpandedLayout.visibility = View.VISIBLE
        detailsExpandedArrow.setImageResource(R.drawable.ic_arrow_up_black)
    } else {
        detailsExpandedLayout.visibility = View.GONE
        detailsExpandedArrow.setImageResource(R.drawable.ic_down_arrow)
    }
}

// OnClickListener to handle place searching using the Places SDK
private val onPlaceSearchInitiated = View.OnClickListener {
    (activity as MainActivity).openSearchPage()
}

// RefreshListener to update the UI when the location settings are changed
private val refreshListener = SwipeRefreshLayout.OnRefreshListener {
    Toast.makeText(activity, "calling onRefresh()", Toast.LENGTH_SHORT).show()
    swipeRefreshLayout.isRefreshing = false
}

// OnClickListener to allow navigating from this fragment to the settings one
private val onSettingsButtonClicked: View.OnClickListener = View.OnClickListener {
    (activity as MainActivity).openSettingsPage()
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    val view = inflater.inflate(R.layout.main_fragment, container, false)
    // View initializations
    .....
    hourlyChart = view.findViewById(R.id.lc_hourly_forecasts)
    return view
}

   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    setUpChart()
    lifecycleScope.launch {
        // Shows a lottie animation while the data is being loaded
        //scrollView.visibility = View.GONE
        //lottieAnimView.visibility = View.VISIBLE
        bindUIAsync().await()
        // Stops the animation and reveals the layout with the data loaded
        //scrollView.visibility = View.VISIBLE
        //lottieAnimView.visibility = View.GONE
    }
}

@SuppressLint("SimpleDateFormat")
    private fun bindUIAsync() = lifecycleScope.async(Dispatchers.Main) {
        // fetch current weather
        val currentWeather = viewModel.currentWeatherData

    // Observe the current weather live data
    currentWeather.observe(viewLifecycleOwner, Observer { currentlyLiveData ->
        if (currentlyLiveData == null) return@Observer

        currentlyLiveData.observe(viewLifecycleOwner, Observer { currently ->

            setCurrentWeatherDate(currently.time.toDouble())

            // Get the unit system pref's value
            val unitSystem = viewModel.preferences.getString(
                UNIT_SYSTEM_KEY,
                UnitSystem.SI.name.toLowerCase(Locale.ROOT)
            )

            // set up views dependent on the Unit System pref's value
            when (unitSystem) {
                UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> {
                    setCurrentWeatherTemp(currently.temperature)
                    setUnitSystemImgView(unitSystem)
                }
                UnitSystem.US.name.toLowerCase(Locale.ROOT) -> {
                    setCurrentWeatherTemp(
                        weatherUnitConverter.convertToFahrenheit(
                            currently.temperature
                        )
                    )
                    setUnitSystemImgView(unitSystem)
                }
            }

            setCurrentWeatherSummaryText(currently.summary)
            setCurrentWeatherSummaryIcon(currently.icon)
            setCurrentWeatherPrecipProb(currently.precipProbability)
        })
    })

    // fetch the location
    val weatherLocation = viewModel.weatherLocation
    // Observe the location for changes
    weatherLocation.observe(viewLifecycleOwner, Observer { locationLiveData ->
        if (locationLiveData == null) return@Observer

        locationLiveData.observe(viewLifecycleOwner, Observer { location ->
            Log.d(TAG,"location update = $location")
            locationTxtView.text = location.name
        })
    })

    // fetch hourly weather
    val hourlyWeather = viewModel.hourlyWeatherEntries

    // Observe the hourly weather live data
    hourlyWeather.observe(viewLifecycleOwner, Observer { hourlyLiveData ->
        if (hourlyLiveData == null) return@Observer

        hourlyLiveData.observe(viewLifecycleOwner, Observer { hourly ->
            val xAxisLabels = arrayListOf<String>()
            val sdf = SimpleDateFormat("HH")
            for (i in hourly.indices) {
                val formattedLabel = sdf.format(Date(hourly[i].time * 1000))
                xAxisLabels.add(formattedLabel)
            }
            setChartAxisLabels(xAxisLabels)
        })
    })

    // fetch weekly weather
    val weeklyWeather = viewModel.weeklyWeatherEntries

    // get the timezone from the prefs
    val tmz = viewModel.preferences.getString(LOCATION_TIMEZONE_KEY, "America/Los_Angeles")!!

    // observe the weekly weather live data
    weeklyWeather.observe(viewLifecycleOwner, Observer { weeklyLiveData ->
        if (weeklyLiveData == null) return@Observer

        weeklyLiveData.observe(viewLifecycleOwner, Observer { weatherEntries ->
            // update the recyclerView with the new data
            (weeklyForecastRCV.adapter as WeeklyWeatherAdapter).updateWeeklyWeatherData(
                weatherEntries, tmz
            )
            for (day in weatherEntries) { //TODO:sp replace this with the full list once the repo issue is fixed
                val zdtNow = Instant.now().atZone(ZoneId.of(tmz))
                val dayZdt = Instant.ofEpochSecond(day.time).atZone(ZoneId.of(tmz))
                val formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy")
                val formattedNowZtd = zdtNow.format(formatter)
                val formattedDayZtd = dayZdt.format(formatter)
                if (formattedNowZtd == formattedDayZtd) { // find the right week day whose data we want to use for the UI
                    initTodayData(day, tmz)
                }
            }
        })
    })

    // get the hourly chart's computed data
    val hourlyChartLineData = viewModel.hourlyChartData

    // Observe the chart's data
    hourlyChartLineData.observe(viewLifecycleOwner, Observer { lineData ->
        if(lineData == null) return@Observer

        hourlyChart.data = lineData // Error due to the live data value being of type Unit
    })

    return@async true
}

...

private fun setChartAxisLabels(labels: ArrayList<String>) {
    // Populate the X axis with the hour labels
    hourlyChart.xAxis.valueFormatter = IndexAxisValueFormatter(labels)
}

/**
 * Sets up the chart with the appropriate
 * customizations.
 */
private fun setUpChart() {
    hourlyChart.apply {
        description.isEnabled = false
        setNoDataText("Data is loading...")

        // enable touch gestures
        setTouchEnabled(true)
        dragDecelerationFrictionCoef = 0.9f

        // enable dragging
        isDragEnabled = true
        isHighlightPerDragEnabled = true
        setDrawGridBackground(false)
        axisRight.setDrawLabels(false)
        axisLeft.setDrawLabels(false)
        axisLeft.setDrawGridLines(false)
        xAxis.setDrawGridLines(false)
        xAxis.isEnabled = true

        // disable zoom functionality
        setScaleEnabled(false)
        setPinchZoom(false)
        isDoubleTapToZoomEnabled = false

        // disable the chart's legend
        legend.isEnabled = false

        // append extra offsets to the chart's auto-calculated ones
        setExtraOffsets(0f, 0f, 0f, 10f)

        data = LineData()
        data.isHighlightEnabled = false
        setVisibleXRangeMaximum(6f)
        setBackgroundColor(resources.getColor(R.color.bright_White, null))
    }

    // X Axis setup
    hourlyChart.xAxis.apply {
        position = XAxis.XAxisPosition.BOTTOM
        textSize = 14f
        setDrawLabels(true)
        setDrawAxisLine(false)
        granularity = 1f // one hour
        spaceMax = 0.2f // add padding start
        spaceMin = 0.2f // add padding end
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            typeface = resources.getFont(R.font.work_sans)
        }
        textColor = resources.getColor(R.color.black, null)
    }

    // Left Y axis setup
    hourlyChart.axisLeft.apply {
        setDrawLabels(false)
        setDrawGridLines(false)
        setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
        isEnabled = false
        isGranularityEnabled = true
        // temperature values range (higher than probable temps in order to scale down the chart)
        axisMinimum = 0f
        axisMaximum = when (getUnitSystemValue()) {
            UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> 50f
            UnitSystem.US.name.toLowerCase(Locale.ROOT) -> 150f
            else -> 50f
        }
    }

    // Right Y axis setup
   hourlyChart.axisRight.apply {
       setDrawGridLines(false)
       isEnabled = false
   }
}
}
</code>```

ViewModel class:

```<code>class WeatherViewModel(
private val forecastRepository: ForecastRepository,
private val weatherUnitConverter: WeatherUnitConverter,
context: Context
) : ViewModel() {

private val appContext = context.applicationContext

// Retrieve the sharedPrefs
val preferences:SharedPreferences
    get() = PreferenceManager.getDefaultSharedPreferences(appContext)

// This will run only when currentWeatherData is called from the View
val currentWeatherData = liveData {
    val task = viewModelScope.async {  forecastRepository.getCurrentWeather() }
    emit(task.await())
}

val hourlyWeatherEntries = liveData {
    val task = viewModelScope.async {  forecastRepository.getHourlyWeather() }
    emit(task.await())
}

val weeklyWeatherEntries = liveData {
    val task = viewModelScope.async {
        val currentDateEpoch = LocalDate.now().toEpochDay()
        forecastRepository.getWeekDayWeatherList(currentDateEpoch)
    }
    emit(task.await())
}

val weatherLocation = liveData {
    val task = viewModelScope.async(Dispatchers.IO) {
        forecastRepository.getWeatherLocation()
    }
    emit(task.await())
}

val hourlyChartData = liveData {
    val task = viewModelScope.async(Dispatchers.Default) {
        // Build the chart data
        hourlyWeatherEntries.observeForever { hourlyWeatherLiveData ->
            if(hourlyWeatherLiveData == null) return@observeForever

            hourlyWeatherLiveData.observeForever {hourlyWeather ->
                createChartData(hourlyWeather)
            }
        }
    }
    emit(task.await())
}

/**
 * Creates the line chart's data and returns them.
 * @return The line chart's data (x,y) value pairs
 */
private fun createChartData(hourlyWeather: List<HourWeatherEntry>?): LineData {
    if(hourlyWeather == null) return LineData()

    val unitSystemValue = preferences.getString(UNIT_SYSTEM_KEY, "si")!!
    val values = arrayListOf<Entry>()

    for (i in hourlyWeather.indices) { // init data points
        // format the temperature appropriately based on the unit system selected
        val hourTempFormatted = when (unitSystemValue) {
            UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> hourlyWeather[i].temperature
            UnitSystem.US.name.toLowerCase(Locale.ROOT) -> weatherUnitConverter.convertToFahrenheit(
                hourlyWeather[i].temperature
            )
            else -> hourlyWeather[i].temperature
        }

        // Create the data point
        values.add(
            Entry(
                i.toFloat(),
                hourTempFormatted.toFloat(),
                appContext.resources.getDrawable(determineSummaryIcon(hourlyWeather[i].icon), null)
            )
        )
    }
    Log.d("MainFragment viewModel", "$values")
    // create a data set and customize it
    val lineDataSet = LineDataSet(values, "")

    val color = appContext.resources.getColor(R.color.black, null)
    val offset = MPPointF.getInstance()
    offset.y = -35f

    lineDataSet.apply {
        valueFormatter = YValueFormatter()
        setDrawValues(true)
        fillDrawable = appContext.resources.getDrawable(R.drawable.gradient_night_chart, null)
        setDrawFilled(true)
        setDrawIcons(true)
        setCircleColor(color)
        mode = LineDataSet.Mode.HORIZONTAL_BEZIER
        this.color = color // line color
        iconsOffset = offset
        lineWidth = 3f
        valueTextSize = 9f
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            valueTypeface = appContext.resources.getFont(R.font.work_sans_medium)
        }
    }

    // create a LineData object using our LineDataSet
    val data = LineData(lineDataSet)
    data.apply {
        setValueTextColor(R.color.colorPrimary)
        setValueTextSize(15f)
    }
    return data
}

private fun determineSummaryIcon(icon: String): Int {
    return when (icon) {
        "clear-day" -> R.drawable.ic_sun
        "clear-night" -> R.drawable.ic_moon
        "rain" -> R.drawable.ic_precipitation
        "snow" -> R.drawable.ic_snowflake
        "sleet" -> R.drawable.ic_sleet
        "wind" -> R.drawable.ic_wind_speed
        "fog" -> R.drawable.ic_fog
        "cloudy" -> R.drawable.ic_cloud_coverage
        "partly-cloudy-day" -> R.drawable.ic_cloudy_day
        "partly-cloudy-night" -> R.drawable.ic_cloudy_night
        "hail" -> R.drawable.ic_hail
        "thunderstorm" -> R.drawable.ic_thunderstorm
        "tornado" -> R.drawable.ic_tornado
        else -> R.drawable.ic_sun
    }
}
</code>```

}

LazyDeferred:

```<code>fun<T> lazyDeferred(block: suspend CoroutineScope.() -> T) : Lazy<Deferred<T>> {
    return lazy {
        GlobalScope.async {
            block.invoke(this)
        }
    }
}
</code>```

ScopedFragment :

```<code>abstract class ScopedFragment : Fragment(), CoroutineScope {
private lateinit var job: Job

override val coroutineContext: CoroutineContext
    get() = job + Dispatchers.Main

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    job = Job()
}

override fun onDestroy() {
    job.cancel()
    super.onDestroy()
}
}
</code>```

答: Separate the setupChart and setData logics. Setup chart once out of the observer, inside the observer setData and after that call invalidate().</p>

Body:
In my Weather app, I have a MainFragment which has a button that opens a different fragment (SearchFragment) (via replace), allows a user to select a location and then fetches weather data for that location and loads it in various views including an MPAndroid LineChart. My issue is that whenever I come back from the search fragment, although the new data is fetched for the chart and I'm calling chart.notifyDataSetChanged() & chart.invalidate() (also tried chart.postInvalidate() since it was suggested when working on another thread) after the invalidate() is called the chart simply disappears. What am i missing here?

MainFragment:

const val UNIT_SYSTEM_KEY = "UNIT_SYSTEM"
const val LATEST_CURRENT_LOCATION_KEY = "LATEST_CURRENT_LOC"

class MainFragment : Fragment() {

// Lazy inject the view model
private val viewModel: WeatherViewModel by viewModel()
private lateinit var weatherUnitConverter: WeatherUnitConverter

private val TAG = MainFragment::class.java.simpleName

// View declarations
...

// OnClickListener to handle the current weather's "Details" layout expansion/collapse
private val onCurrentWeatherDetailsClicked = View.OnClickListener {
    if (detailsExpandedLayout.visibility == View.GONE) {
        detailsExpandedLayout.visibility = View.VISIBLE
        detailsExpandedArrow.setImageResource(R.drawable.ic_arrow_up_black)
    } else {
        detailsExpandedLayout.visibility = View.GONE
        detailsExpandedArrow.setImageResource(R.drawable.ic_down_arrow)
    }
}

// OnClickListener to handle place searching using the Places SDK
private val onPlaceSearchInitiated = View.OnClickListener {
    (activity as MainActivity).openSearchPage()
}

// RefreshListener to update the UI when the location settings are changed
private val refreshListener = SwipeRefreshLayout.OnRefreshListener {
    Toast.makeText(activity, "calling onRefresh()", Toast.LENGTH_SHORT).show()
    swipeRefreshLayout.isRefreshing = false
}

// OnClickListener to allow navigating from this fragment to the settings one
private val onSettingsButtonClicked: View.OnClickListener = View.OnClickListener {
    (activity as MainActivity).openSettingsPage()
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    val view = inflater.inflate(R.layout.main_fragment, container, false)
    // View initializations
    .....
    hourlyChart = view.findViewById(R.id.lc_hourly_forecasts)
    return view
}

   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    setUpChart()
    lifecycleScope.launch {
        // Shows a lottie animation while the data is being loaded
        //scrollView.visibility = View.GONE
        //lottieAnimView.visibility = View.VISIBLE
        bindUIAsync().await()
        // Stops the animation and reveals the layout with the data loaded
        //scrollView.visibility = View.VISIBLE
        //lottieAnimView.visibility = View.GONE
    }
}

@SuppressLint("SimpleDateFormat")
    private fun bindUIAsync() = lifecycleScope.async(Dispatchers.Main) {
        // fetch current weather
        val currentWeather = viewModel.currentWeatherData

    // Observe the current weather live data
    currentWeather.observe(viewLifecycleOwner, Observer { currentlyLiveData ->
        if (currentlyLiveData == null) return@Observer

        currentlyLiveData.observe(viewLifecycleOwner, Observer { currently ->

            setCurrentWeatherDate(currently.time.toDouble())

            // Get the unit system pref's value
            val unitSystem = viewModel.preferences.getString(
                UNIT_SYSTEM_KEY,
                UnitSystem.SI.name.toLowerCase(Locale.ROOT)
            )

            // set up views dependent on the Unit System pref's value
            when (unitSystem) {
                UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> {
                    setCurrentWeatherTemp(currently.temperature)
                    setUnitSystemImgView(unitSystem)
                }
                UnitSystem.US.name.toLowerCase(Locale.ROOT) -> {
                    setCurrentWeatherTemp(
                        weatherUnitConverter.convertToFahrenheit(
                            currently.temperature
                        )
                    )
                    setUnitSystemImgView(unitSystem)
                }
            }

            setCurrentWeatherSummaryText(currently.summary)
            setCurrentWeatherSummaryIcon(currently.icon)
            setCurrentWeatherPrecipProb(currently.precipProbability)
        })
    })

    // fetch the location
    val weatherLocation = viewModel.weatherLocation
    // Observe the location for changes
    weatherLocation.observe(viewLifecycleOwner, Observer { locationLiveData ->
        if (locationLiveData == null) return@Observer

        locationLiveData.observe(viewLifecycleOwner, Observer { location ->
            Log.d(TAG,"location update = $location")
            locationTxtView.text = location.name
        })
    })

    // fetch hourly weather
    val hourlyWeather = viewModel.hourlyWeatherEntries

    // Observe the hourly weather live data
    hourlyWeather.observe(viewLifecycleOwner, Observer { hourlyLiveData ->
        if (hourlyLiveData == null) return@Observer

        hourlyLiveData.observe(viewLifecycleOwner, Observer { hourly ->
            val xAxisLabels = arrayListOf<String>()
            val sdf = SimpleDateFormat("HH")
            for (i in hourly.indices) {
                val formattedLabel = sdf.format(Date(hourly[i].time * 1000))
                xAxisLabels.add(formattedLabel)
            }
            setChartAxisLabels(xAxisLabels)
        })
    })

    // fetch weekly weather
    val weeklyWeather = viewModel.weeklyWeatherEntries

    // get the timezone from the prefs
    val tmz = viewModel.preferences.getString(LOCATION_TIMEZONE_KEY, "America/Los_Angeles")!!

    // observe the weekly weather live data
    weeklyWeather.observe(viewLifecycleOwner, Observer { weeklyLiveData ->
        if (weeklyLiveData == null) return@Observer

        weeklyLiveData.observe(viewLifecycleOwner, Observer { weatherEntries ->
            // update the recyclerView with the new data
            (weeklyForecastRCV.adapter as WeeklyWeatherAdapter).updateWeeklyWeatherData(
                weatherEntries, tmz
            )
            for (day in weatherEntries) { //TODO:sp replace this with the full list once the repo issue is fixed
                val zdtNow = Instant.now().atZone(ZoneId.of(tmz))
                val dayZdt = Instant.ofEpochSecond(day.time).atZone(ZoneId.of(tmz))
                val formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy")
                val formattedNowZtd = zdtNow.format(formatter)
                val formattedDayZtd = dayZdt.format(formatter)
                if (formattedNowZtd == formattedDayZtd) { // find the right week day whose data we want to use for the UI
                    initTodayData(day, tmz)
                }
            }
        })
    })

    // get the hourly chart's computed data
    val hourlyChartLineData = viewModel.hourlyChartData

    // Observe the chart's data
    hourlyChartLineData.observe(viewLifecycleOwner, Observer { lineData ->
        if(lineData == null) return@Observer

        hourlyChart.data = lineData // Error due to the live data value being of type Unit
    })

    return@async true
}

...

private fun setChartAxisLabels(labels: ArrayList<String>) {
    // Populate the X axis with the hour labels
    hourlyChart.xAxis.valueFormatter = IndexAxisValueFormatter(labels)
}

/**
 * Sets up the chart with the appropriate
 * customizations.
 */
private fun setUpChart() {
    hourlyChart.apply {
        description.isEnabled = false
        setNoDataText("Data is loading...")

        // enable touch gestures
        setTouchEnabled(true)
        dragDecelerationFrictionCoef = 0.9f

        // enable dragging
        isDragEnabled = true
        isHighlightPerDragEnabled = true
        setDrawGridBackground(false)
        axisRight.setDrawLabels(false)
        axisLeft.setDrawLabels(false)
        axisLeft.setDrawGridLines(false)
        xAxis.setDrawGridLines(false)
        xAxis.isEnabled = true

        // disable zoom functionality
        setScaleEnabled(false)
        setPinchZoom(false)
        isDoubleTapToZoomEnabled = false

        // disable the chart's legend
        legend.isEnabled = false

        // append extra offsets to the chart's auto-calculated ones
        setExtraOffsets(0f, 0f, 0f, 10f)

        data = LineData()
        data.isHighlightEnabled = false
        setVisibleXRangeMaximum(6f)
        setBackgroundColor(resources.getColor(R.color.bright_White, null))
    }

    // X Axis setup
    hourlyChart.xAxis.apply {
        position = XAxis.XAxisPosition.BOTTOM
        textSize = 14f
        setDrawLabels(true)
        setDrawAxisLine(false)
        granularity = 1f // one hour
        spaceMax = 0.2f // add padding start
        spaceMin = 0.2f // add padding end
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            typeface = resources.getFont(R.font.work_sans)
        }
        textColor = resources.getColor(R.color.black, null)
    }

    // Left Y axis setup
    hourlyChart.axisLeft.apply {
        setDrawLabels(false)
        setDrawGridLines(false)
        setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
        isEnabled = false
        isGranularityEnabled = true
        // temperature values range (higher than probable temps in order to scale down the chart)
        axisMinimum = 0f
        axisMaximum = when (getUnitSystemValue()) {
            UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> 50f
            UnitSystem.US.name.toLowerCase(Locale.ROOT) -> 150f
            else -> 50f
        }
    }

    // Right Y axis setup
   hourlyChart.axisRight.apply {
       setDrawGridLines(false)
       isEnabled = false
   }
}
}

ViewModel class:

class WeatherViewModel(
private val forecastRepository: ForecastRepository,
private val weatherUnitConverter: WeatherUnitConverter,
context: Context
) : ViewModel() {

private val appContext = context.applicationContext

// Retrieve the sharedPrefs
val preferences:SharedPreferences
    get() = PreferenceManager.getDefaultSharedPreferences(appContext)

// This will run only when currentWeatherData is called from the View
val currentWeatherData = liveData {
    val task = viewModelScope.async {  forecastRepository.getCurrentWeather() }
    emit(task.await())
}

val hourlyWeatherEntries = liveData {
    val task = viewModelScope.async {  forecastRepository.getHourlyWeather() }
    emit(task.await())
}

val weeklyWeatherEntries = liveData {
    val task = viewModelScope.async {
        val currentDateEpoch = LocalDate.now().toEpochDay()
        forecastRepository.getWeekDayWeatherList(currentDateEpoch)
    }
    emit(task.await())
}

val weatherLocation = liveData {
    val task = viewModelScope.async(Dispatchers.IO) {
        forecastRepository.getWeatherLocation()
    }
    emit(task.await())
}

val hourlyChartData = liveData {
    val task = viewModelScope.async(Dispatchers.Default) {
        // Build the chart data
        hourlyWeatherEntries.observeForever { hourlyWeatherLiveData ->
            if(hourlyWeatherLiveData == null) return@observeForever

            hourlyWeatherLiveData.observeForever {hourlyWeather ->
                createChartData(hourlyWeather)
            }
        }
    }
    emit(task.await())
}

/**
 * Creates the line chart's data and returns them.
 * @return The line chart's data (x,y) value pairs
 */
private fun createChartData(hourlyWeather: List<HourWeatherEntry>?): LineData {
    if(hourlyWeather == null) return LineData()

    val unitSystemValue = preferences.getString(UNIT_SYSTEM_KEY, "si")!!
    val values = arrayListOf<Entry>()

    for (i in hourlyWeather.indices) { // init data points
        // format the temperature appropriately based on the unit system selected
        val hourTempFormatted = when (unitSystemValue) {
            UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> hourlyWeather[i].temperature
            UnitSystem.US.name.toLowerCase(Locale.ROOT) -> weatherUnitConverter.convertToFahrenheit(
                hourlyWeather[i].temperature
            )
            else -> hourlyWeather[i].temperature
        }

        // Create the data point
        values.add(
            Entry(
                i.toFloat(),
                hourTempFormatted.toFloat(),
                appContext.resources.getDrawable(determineSummaryIcon(hourlyWeather[i].icon), null)
            )
        )
    }
    Log.d("MainFragment viewModel", "$values")
    // create a data set and customize it
    val lineDataSet = LineDataSet(values, "")

    val color = appContext.resources.getColor(R.color.black, null)
    val offset = MPPointF.getInstance()
    offset.y = -35f

    lineDataSet.apply {
        valueFormatter = YValueFormatter()
        setDrawValues(true)
        fillDrawable = appContext.resources.getDrawable(R.drawable.gradient_night_chart, null)
        setDrawFilled(true)
        setDrawIcons(true)
        setCircleColor(color)
        mode = LineDataSet.Mode.HORIZONTAL_BEZIER
        this.color = color // line color
        iconsOffset = offset
        lineWidth = 3f
        valueTextSize = 9f
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            valueTypeface = appContext.resources.getFont(R.font.work_sans_medium)
        }
    }

    // create a LineData object using our LineDataSet
    val data = LineData(lineDataSet)
    data.apply {
        setValueTextColor(R.color.colorPrimary)
        setValueTextSize(15f)
    }
    return data
}

private fun determineSummaryIcon(icon: String): Int {
    return when (icon) {
        "clear-day" -> R.drawable.ic_sun
        "clear-night" -> R.drawable.ic_moon
        "rain" -> R.drawable.ic_precipitation
        "snow" -> R.drawable.ic_snowflake
        "sleet" -> R.drawable.ic_sleet
        "wind" -> R.drawable.ic_wind_speed
        "fog" -> R.drawable.ic_fog
        "cloudy" -> R.drawable.ic_cloud_coverage
        "partly-cloudy-day" -> R.drawable.ic_cloudy_day
        "partly-cloudy-night" -> R.drawable.ic_cloudy_night
        "hail" -> R.drawable.ic_hail
        "thunderstorm" -> R.drawable.ic_thunderstorm
        "tornado" -> R.drawable.ic_tornado
        else -> R.drawable.ic_sun
    }
}

}

LazyDeferred:

fun<T> lazyDeferred(block: suspend CoroutineScope.() -> T) : Lazy<Deferred<T>> {
    return lazy {
        GlobalScope.async {
            block.invoke(this)
        }
    }
}

ScopedFragment :

abstract class ScopedFragment : Fragment(), CoroutineScope {
private lateinit var job: Job

override val coroutineContext: CoroutineContext
    get() = job + Dispatchers.Main

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    job = Job()
}

override fun onDestroy() {
    job.cancel()
    super.onDestroy()
}
}


问:
Python color adjuster 3d numpy only
I'm trying to make an rgb color picture editor, using just numpy.
I've tried using a nested for loop, but it's really slow (over a minute).
I'm wanting to control first, second, and third element (r,g,b) of the third dimension of the nested array. Thanks

This is to just look at the numbers:

```<code>%matplotlib inline
import numpy as np

img = plt.imread('galaxy.jpg')
img = np.array(img)

for i in range(len(img)):
   for j in range(len(img[i])):
       for k in (img[i][j]):
           print(k)
</code>```

答:
Perhaps this might help you. np.ndenumerate() lets you iterate through a matrix without nested for loops. I did a quick test and my second for loop (in the example below) is slightly faster than your triple nested for loop, as far as printing is concerned. Printing is very slow so taking out the print statements might help with speed. As far as modifying these values, I added r g b a variables that can be modified to scale the various pixel values. Just a thought, but perhaps it might give you more ideas to expand on. Also, I didn't check to see which index values correspond to r, g, b, or a.

```<code>r = 1.0
g = 1.0
b = 1.0
a = 1.0

for index, pixel in np.ndenumerate(img): # <--- Acheives the same as your original code
    print(pixel)

for index, pixel in np.ndenumerate(img):
    i = index[0]
    j = index[1]
    print("{} {} {} {}".format(img[i][j][0], img[i][j][1], img[i][j][2], img[i][j][3]))

for index, pixel in np.ndenumerate(img):
    i = index[0]
    j = index[1]
    imgp[i][j][0] *= r;
    imgp[i][j][1] *= g;
    imgp[i][j][2] *= b;
    imgp[i][j][3] *= a;
</code>```

Hope this helps

Title: Python color adjuster 3d numpy only

Body:
I'm trying to make an rgb color picture editor, using just numpy.
I've tried using a nested for loop, but it's really slow (over a minute).
I'm wanting to control first, second, and third element (r,g,b) of the third dimension of the nested array. Thanks

This is to just look at the numbers:

%matplotlib inline
import numpy as np

img = plt.imread('galaxy.jpg')
img = np.array(img)

for i in range(len(img)):
   for j in range(len(img[i])):
       for k in (img[i][j]):
           print(k)

Body:
Perhaps this might help you. np.ndenumerate() lets you iterate through a matrix without nested for loops. I did a quick test and my second for loop (in the example below) is slightly faster than your triple nested for loop, as far as printing is concerned. Printing is very slow so taking out the print statements might help with speed. As far as modifying these values, I added r g b a variables that can be modified to scale the various pixel values. Just a thought, but perhaps it might give you more ideas to expand on. Also, I didn't check to see which index values correspond to r, g, b, or a.

r = 1.0
g = 1.0
b = 1.0
a = 1.0

for index, pixel in np.ndenumerate(img): # <--- Acheives the same as your original code
    print(pixel)

for index, pixel in np.ndenumerate(img):
    i = index[0]
    j = index[1]
    print("{} {} {} {}".format(img[i][j][0], img[i][j][1], img[i][j][2], img[i][j][3]))

for index, pixel in np.ndenumerate(img):
    i = index[0]
    j = index[1]
    imgp[i][j][0] *= r;
    imgp[i][j][1] *= g;
    imgp[i][j][2] *= b;
    imgp[i][j][3] *= a;

Hope this helps


问:
Using methods from another class in forms, C#
Thank you very much for the response. I have edited my post to show the QuoteMgr class. I use this mostly to read and save quotes to file; it is read back into an array of quotes called mylist. I can't figure out how to call QuoteMgr methods from within all of the four forms I have created. The only way I have found is to instantiate QuoteMgr from within one of the forms, but that won't work for the other three forms. The method I want to use in different forms is getRandomQuote() - haven't written the other methods yet.
My plan was to read data from a file, display the quote on the main form, and offer choice to add more quotes, edit one, or display another quote. A different form would be displayed, appropriate to the choice made.

At heart the problem is I don't fully grasp OOP. I understand the idea of having an abstract class to inherit methods from.  If I do this, will the different forms be able to access my array of quotes ("mylist")?  For data integrity, I think I only want one instance of my data floating around. In which case, I could have an abstract class with all of the quote manipulation methods, and use QuoteMgr only to read/write to file.

From the standpoint of learning the right way to program, is this the right design?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace Quote
    {
    class QuoteMgr
        {

```<code>    Quotes myquote = new Quotes();
    Quotes objectToSerialize = new Quotes();
    Serializer serializer = new Serializer();
    string myFile = "H:\\Dad\\Quotes\\quotes.quo";

    public QuoteMgr()
        {
        }

    static Random r = new Random();

    public void getFile()
        {
        //fills myquote.mylist with quote strings from file

        if (File.Exists(myFile))
            {
            objectToSerialize = serializer.DeSerializeObject(myFile);
            myquote.myList = objectToSerialize.QuoteList;
            //myquote.ShowQuotes();
            }
        else
            {
            FileInfo makeFile = new FileInfo(@myFile);
            makeFile.Create();
            }

        }//end of get file

    public void saveFile()
        {
        objectToSerialize.QuoteList = myquote.myList;
        serializer.SerializeObject(myFile, objectToSerialize);
        }

    public string getRandomQuote()
        {
        int x = myquote.myList.Count-1;
        return myquote.myList[r.Next(x)];
        }

    public void GUIop()
        {
        getFile();

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Form1 myMainScreen = new Form1();

        //make all other forms invisible
        myMainScreen.Visible = true;

        changeQuoteDisplayed(myMainScreen);
        Application.Run(myMainScreen);
        saveFile();
        }

    public void changeQuoteDisplayed(Form1 theForm)
        {
        string s;
        s = getRandomQuote();
        theForm.lblDisplayQuote.Text = s;
        }

    }
}
</code>```

答:
It sounds like you should move the changeQuoteDisplayed method into your Form class...it doesn't make any sense to call a method in another class with your Form as an argument, only to have the other class modify the form you passed it.  For one, you should not have public UI components inside your Form..if you must modify these from outside the form, make their data accessible through Properties.

If this is a method that all of your forms need to use, then perhaps you should allow them to inherit it through an abstract class, providing an abstract property as well that your child classes will use to implement set, making it update whatever UI component the child class needs updated on that method call.  It could look something like this:

```<code>public abstract class QuoteBase
{
         protected void changeQuoteDisplayed()
         {
             string s;
             s = getRandomQuote();
             LabelText = s;
            // theForm.lblDisplayQuote.Text = s;
          }

          public abstract String LabelText
          {
                   get; set;
          }
 }

 public class EditQuote : QuoteBase
 {
        public override String LabelText
        {
               get { return lblDisplayQuote.Text; }
               set { lblDisplayQuote.Text = value; }
        }
  }
</code>```

Now all you need to do is implement the LabelText property in all of your Quote classes to update whatever label you want without needing to send an instance of your form to some other class to get an update.

Of course, this is just a wild guess..it's hard to tell what you should actually do without more information.

Body:
Thank you very much for the response. I have edited my post to show the QuoteMgr class. I use this mostly to read and save quotes to file; it is read back into an array of quotes called mylist. I can't figure out how to call QuoteMgr methods from within all of the four forms I have created. The only way I have found is to instantiate QuoteMgr from within one of the forms, but that won't work for the other three forms. The method I want to use in different forms is getRandomQuote() - haven't written the other methods yet.
My plan was to read data from a file, display the quote on the main form, and offer choice to add more quotes, edit one, or display another quote. A different form would be displayed, appropriate to the choice made.

At heart the problem is I don't fully grasp OOP. I understand the idea of having an abstract class to inherit methods from.  If I do this, will the different forms be able to access my array of quotes ("mylist")?  For data integrity, I think I only want one instance of my data floating around. In which case, I could have an abstract class with all of the quote manipulation methods, and use QuoteMgr only to read/write to file.

From the standpoint of learning the right way to program, is this the right design?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace Quote
    {
    class QuoteMgr
        {

    Quotes myquote = new Quotes();
    Quotes objectToSerialize = new Quotes();
    Serializer serializer = new Serializer();
    string myFile = "H:\\Dad\\Quotes\\quotes.quo";

    public QuoteMgr()
        {
        }

    static Random r = new Random();

    public void getFile()
        {
        //fills myquote.mylist with quote strings from file

        if (File.Exists(myFile))
            {
            objectToSerialize = serializer.DeSerializeObject(myFile);
            myquote.myList = objectToSerialize.QuoteList;
            //myquote.ShowQuotes();
            }
        else
            {
            FileInfo makeFile = new FileInfo(@myFile);
            makeFile.Create();
            }

        }//end of get file

    public void saveFile()
        {
        objectToSerialize.QuoteList = myquote.myList;
        serializer.SerializeObject(myFile, objectToSerialize);
        }

    public string getRandomQuote()
        {
        int x = myquote.myList.Count-1;
        return myquote.myList[r.Next(x)];
        }

    public void GUIop()
        {
        getFile();

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Form1 myMainScreen = new Form1();

        //make all other forms invisible
        myMainScreen.Visible = true;

        changeQuoteDisplayed(myMainScreen);
        Application.Run(myMainScreen);
        saveFile();
        }

    public void changeQuoteDisplayed(Form1 theForm)
        {
        string s;
        s = getRandomQuote();
        theForm.lblDisplayQuote.Text = s;
        }

    }
}

Body:
It sounds like you should move the changeQuoteDisplayed method into your Form class...it doesn't make any sense to call a method in another class with your Form as an argument, only to have the other class modify the form you passed it.  For one, you should not have public UI components inside your Form..if you must modify these from outside the form, make their data accessible through Properties.

If this is a method that all of your forms need to use, then perhaps you should allow them to inherit it through an abstract class, providing an abstract property as well that your child classes will use to implement set, making it update whatever UI component the child class needs updated on that method call.  It could look something like this:

public abstract class QuoteBase
{
         protected void changeQuoteDisplayed()
         {
             string s;
             s = getRandomQuote();
             LabelText = s;
            // theForm.lblDisplayQuote.Text = s;
          }

          public abstract String LabelText
          {
                   get; set;
          }
 }

 public class EditQuote : QuoteBase
 {
        public override String LabelText
        {
               get { return lblDisplayQuote.Text; }
               set { lblDisplayQuote.Text = value; }
        }
  }

Now all you need to do is implement the LabelText property in all of your Quote classes to update whatever label you want without needing to send an instance of your form to some other class to get an update.

Of course, this is just a wild guess..it's hard to tell what you should actually do without more information.