问:
Django comment form not submitting data [ERROR: function' object has no attribute 'objects]
I have a comment form on a post page for submitting user comment. I keep getting this error:

```<code>'function' object has no attribute 'objects'
</code>```

The full trace-back:

```<code>Traceback (most recent call last):
File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\App\views.py", line 208, in AddComment
    comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)

Exception Type: AttributeError at /post/1/comment
Exception Value: 'function' object has no attribute 'objects'
</code>```

Most answers on SO refer to identical model & function names but that is not my case. This is my model:

```<code>class Comment(models.Model):
    opinion = models.CharField(max_length=2200, verbose_name='Comment', null=False)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

    def __str__(self):
        return self.comment

    class Meta:
        verbose_name_plural = 'Comments'
</code>```

My view

```<code>@login_required(login_url='Login')
def AddComment(request, id):
    post = Post.objects.filter(id=id)
    user = User.objects.get(username=request.user)
    if request.method == "POST":
        usercomment = request.POST['comment']
        comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)
        comment_obj.save()
        messages.success(request, '✅ Your Comment Was Created Successfully!')
        return redirect('Home')
    else:
        messages.error(request, "⚠ Your Comment Wasn't Created!")
        return redirect('Home')
</code>```

And my form:

```<code><form method="POST" action="{% url 'AddComment' post.id %}">
   {% csrf_token %}
   <div class="d-flex flex-row add-comment-section mt-4 mb-4">
      <img class="img-fluid img-responsive rounded-circle mr-2" src="{{ user.profile.profile_image.url }}" width="38">
      <textarea class="form-control mr-3" rows="1" name="comment" placeholder="Your Comment" required></textarea>
      <button class="btn btn-primary btn-lg" type="submit">Comment</button>
   </div>
</form>
</code>```

And lastly my URL:

```<code>urlpatterns = [
    path('post/<int:id>/comment', views.AddComment, name="AddComment"),
]
</code>```

答:
Delete user = User.objects.get(username=request.user) from your view, then change this:

```<code>comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)
</code>```

to this:

```<code>comment_obj = Comment.objects.create(opinion=usercomment, author=request.user, post=post)
</code>```

Because you should not pass id where objects are seeked (in ForeignKey we need specific object, not its id).

Also change this:

```<code>post = Post.objects.filter(id=id)
</code>```

To this:

```<code>post = Post.objects.get(id=id)
</code>```

Because you need specific object, not whole QuerySet of them.

Body:
I have a comment form on a post page for submitting user comment. I keep getting this error:

'function' object has no attribute 'objects'

The full trace-back:

Traceback (most recent call last):
File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\App\views.py", line 208, in AddComment
    comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)

Exception Type: AttributeError at /post/1/comment
Exception Value: 'function' object has no attribute 'objects'

Most answers on SO refer to identical model & function names but that is not my case. This is my model:

class Comment(models.Model):
    opinion = models.CharField(max_length=2200, verbose_name='Comment', null=False)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

    def __str__(self):
        return self.comment

    class Meta:
        verbose_name_plural = 'Comments'

My view

@login_required(login_url='Login')
def AddComment(request, id):
    post = Post.objects.filter(id=id)
    user = User.objects.get(username=request.user)
    if request.method == "POST":
        usercomment = request.POST['comment']
        comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)
        comment_obj.save()
        messages.success(request, '✅ Your Comment Was Created Successfully!')
        return redirect('Home')
    else:
        messages.error(request, "⚠ Your Comment Wasn't Created!")
        return redirect('Home')

And my form:

<form method="POST" action="{% url 'AddComment' post.id %}">
   {% csrf_token %}

      <textarea class="form-control mr-3" rows="1" name="comment" placeholder="Your Comment" required></textarea>
      <button class="btn btn-primary btn-lg" type="submit">Comment</button>

</form>

And lastly my URL:

urlpatterns = [
    path('post/<int:id>/comment', views.AddComment, name="AddComment"),
]

Body:
Delete user = User.objects.get(username=request.user) from your view, then change this:

comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)

to this:

comment_obj = Comment.objects.create(opinion=usercomment, author=request.user, post=post)

Because you should not pass id where objects are seeked (in ForeignKey we need specific object, not its id).

Also change this:

post = Post.objects.filter(id=id)

To this:

post = Post.objects.get(id=id)

Because you need specific object, not whole QuerySet of them.


来源: stackexchange

问:
KQL change order of columns in evaluate pivot
I have the following query:

```<code>let fooTable = datatable(TIMESTAMP: datetime, list_id: int, dim_count: int) [
    datetime("2022-01-17T08:00:00Z"), -1, 120,
    datetime("2022-01-17T08:00:00Z"), 1, 50,
    datetime("2022-01-17T08:00:00Z"), 2, 30,
    datetime("2022-01-17T08:00:00Z"), 8, 30,
    datetime("2022-01-17T08:00:00Z"), 2001, 30,
    datetime("2022-01-17T08:00:00Z"), 4, 30,
];
fooTable
| order by TIMESTAMP desc, dim_count desc
| evaluate pivot(list_id, take_any(dim_count), TIMESTAMP)
</code>```

This produces the following results:

```<code>TIMESTAMP                   1   -1  2   2001    4   8
2022-01-17T08:00:00Z        50  120 30  30     30   30
</code>```

Which produce almost what I need - grouping the TIMESTAMP value and creating a column for each list_id value, to use the dim_count as value.

But I expected a different order of the columns (like in the input).

```<code>TIMESTAMP                   -1  1   2   8   2001    4
2022-01-17T08:00:00Z        120 50  30  30     30   30
</code>```

How can I order the columns in such way? (the number and value of columns are dynamic).
Or, how can I control the order of the returned columns?

In reality I have more data (with more buckets of time), and I'd want to return the columns in the order of the largest sum of the column (dim_count).
So the order of the columns in the output would like:

```<code>fooTable
| summarize sum(dim_count) by list_id
| order  by  sum_dim_count desc
| project list_id
</code>```

Which produces

```<code>-1
1
2
8
2001
4
</code>```

And this is how I'd like the order of the columns (like in my expected output).

答:
If the order is based on the row_number, you can use it with the project-reorder operator, the client will need to parse the column names and remove the prefix, for example:

```<code>let fooTable = datatable(TIMESTAMP: datetime, list_id: int, dim_count: int) [
    datetime("2022-01-17T08:00:00Z"), -1, 120,
    datetime("2022-01-17T08:00:00Z"), 1, 50,
    datetime("2022-01-17T08:00:00Z"), 2, 30,
    datetime("2022-01-17T08:00:00Z"), 8, 30,
    datetime("2022-01-17T08:00:00Z"), 2001, 30,
    datetime("2022-01-17T08:00:00Z"), 4, 30,
];
fooTable
| serialize
| extend list_id = strcat(row_number(), "_", list_id)
| order by TIMESTAMP desc, dim_count desc
| evaluate pivot(list_id, take_any(dim_count), TIMESTAMP)
| project-reorder *
</code>```

TIMESTAMP
1_-1
2_1
3_2
4_8
5_2001
6_4

2022-01-17 08:00:00.0000000
120
50
30
30
30
30

ContentLicense: CC BY-SA 4.0

Body:
I have the following query:

let fooTable = datatable(TIMESTAMP: datetime, list_id: int, dim_count: int) [
    datetime("2022-01-17T08:00:00Z"), -1, 120,
    datetime("2022-01-17T08:00:00Z"), 1, 50,
    datetime("2022-01-17T08:00:00Z"), 2, 30,
    datetime("2022-01-17T08:00:00Z"), 8, 30,
    datetime("2022-01-17T08:00:00Z"), 2001, 30,
    datetime("2022-01-17T08:00:00Z"), 4, 30,
];
fooTable
| order by TIMESTAMP desc, dim_count desc
| evaluate pivot(list_id, take_any(dim_count), TIMESTAMP)

This produces the following results:

TIMESTAMP                   1   -1  2   2001    4   8
2022-01-17T08:00:00Z        50  120 30  30     30   30

Which produce almost what I need - grouping the TIMESTAMP value and creating a column for each list_id value, to use the dim_count as value.

But I expected a different order of the columns (like in the input).

TIMESTAMP                   -1  1   2   8   2001    4
2022-01-17T08:00:00Z        120 50  30  30     30   30

How can I order the columns in such way? (the number and value of columns are dynamic).
Or, how can I control the order of the returned columns?

In reality I have more data (with more buckets of time), and I'd want to return the columns in the order of the largest sum of the column (dim_count).
So the order of the columns in the output would like:

fooTable
| summarize sum(dim_count) by list_id
| order  by  sum_dim_count desc
| project list_id

Which produces

-1
1
2
8
2001
4

And this is how I'd like the order of the columns (like in my expected output).

Body:
If the order is based on the row_number, you can use it with the project-reorder operator, the client will need to parse the column names and remove the prefix, for example:

let fooTable = datatable(TIMESTAMP: datetime, list_id: int, dim_count: int) [
    datetime("2022-01-17T08:00:00Z"), -1, 120,
    datetime("2022-01-17T08:00:00Z"), 1, 50,
    datetime("2022-01-17T08:00:00Z"), 2, 30,
    datetime("2022-01-17T08:00:00Z"), 8, 30,
    datetime("2022-01-17T08:00:00Z"), 2001, 30,
    datetime("2022-01-17T08:00:00Z"), 4, 30,
];
fooTable
| serialize
| extend list_id = strcat(row_number(), "_", list_id)
| order by TIMESTAMP desc, dim_count desc
| evaluate pivot(list_id, take_any(dim_count), TIMESTAMP)
| project-reorder *

TIMESTAMP
1_-1
2_1
3_2
4_8
5_2001
6_4

2022-01-17 08:00:00.0000000
120
50
30
30
30
30


问:
Recommended aplications for software development
In a business context, which applications do you recomend for:

Version Control

Time Management

Knowledge Base

Compared with the possible solutions, what are their main advantages?

答:
Version control is either Subversion, Mercurial, or Git.  The latter two are the most modern.

I'd recommend Fog Creek's FogBugz for time management.  It'll help with your estimating, too.

Don't have anything about knowledge management.  Try a wiki.

ContentLicense: CC BY-SA 3.0


问:
Give a new url to the browser with Swift macOS
I could find a way to open a specific browser (with macOS and Swift):

```<code>@IBAction func frx(_ sender: NSButton) {
      NSWorkspace.shared.open(URL(fileURLWithPath: "/Applications/Firefox.app"))
}
</code>```

Is it possible to give to that Firefox window a new url in a posterior moment and reload the page? (Give the address not when I launch the application but later)

答:
```<code>struct Firefox {
    static func open(path: String) {
        let ff_url = NSURL(fileURLWithPath: "/Applications/Firefox.app", isDirectory: true) as URL

        if let www_url = URL(string: path) {
            NSWorkspace.shared.open([www_url], withApplicationAt: ff_url, configuration: NSWorkspace.OpenConfiguration()) { app, error in
                if let error = error {
                    // handle error
                }
                if let _ = app {
                    // handle success
                }
            }
        } else {
            // handle error
        }
    }
}
</code>```

Body:
I could find a way to open a specific browser (with macOS and Swift):

@IBAction func frx(_ sender: NSButton) {
      NSWorkspace.shared.open(URL(fileURLWithPath: "/Applications/Firefox.app"))
}

Is it possible to give to that Firefox window a new url in a posterior moment and reload the page? (Give the address not when I launch the application but later)


问:
Two CSV files with data in different orders (No Pandas)
I have two csv files simulating patient data that I need to read in and compare.

```<code>
Without using Pandas, I need to sort the second file by Subject_ID and append the sex of the patient to the first csv file. I don't know where to start without using Pandas. Any ideas?

So far my plan is to somehow work with a dictionary to try to re-group the second file.

</code>```

with open('Patient_Sex.csv','r') as file_sex, open('Patient_FBG.csv','r') as file_fbg:
patient_reader = csv.DictReader(file_sex)
fbg_reader = csv.DictReader(file_fbg)

```<code>
After this, it gets really muddy for me.
</code>```

答:
You can do this without importing any modules by reading the csv files as lists of lines, and append lines in the main file with the sex upon a matching name:</p>
```<code>with open('test1.csv') as csvfile:
    main_csv = [i.rstrip() for i in csvfile.readlines()]

with open('test2.csv') as csvfile:
    second_csv = [i.rstrip() for i in csvfile.readlines()]

for n, i in enumerate(main_csv):
    if n == 0:
        main_csv[n] = main_csv[n] + ',SEX'
    else:
        patient = i.split(',')[0]
        hits = [line.split(',')[-1] for line in second_csv if line.startswith(patient)]
        if hits:
            main_csv[n] = main_csv[n] + ',' + hits[0]
        else:
            main_csv[n] = main_csv[n] + ','

with open('test.csv', 'w') as f:
    f.write('\n'.join(main_csv))
</code>```

Body:
I have two csv files simulating patient data that I need to read in and compare.

Without using Pandas, I need to sort the second file by Subject_ID and append the sex of the patient to the first csv file. I don't know where to start without using Pandas. Any ideas?

So far my plan is to somehow work with a dictionary to try to re-group the second file.

with open('Patient_Sex.csv','r') as file_sex, open('Patient_FBG.csv','r') as file_fbg:
patient_reader = csv.DictReader(file_sex)
fbg_reader = csv.DictReader(file_fbg)

After this, it gets really muddy for me.

Body:
You can do this without importing any modules by reading the csv files as lists of lines, and append lines in the main file with the sex upon a matching name:

with open('test1.csv') as csvfile:
    main_csv = [i.rstrip() for i in csvfile.readlines()]

with open('test2.csv') as csvfile:
    second_csv = [i.rstrip() for i in csvfile.readlines()]

for n, i in enumerate(main_csv):
    if n == 0:
        main_csv[n] = main_csv[n] + ',SEX'
    else:
        patient = i.split(',')[0]
        hits = [line.split(',')[-1] for line in second_csv if line.startswith(patient)]
        if hits:
            main_csv[n] = main_csv[n] + ',' + hits[0]
        else:
            main_csv[n] = main_csv[n] + ','

with open('test.csv', 'w') as f:
    f.write('\n'.join(main_csv))


问:
Golang: default HTTP client doesn't handle compression
I'm trying to do an HTTP request and have golang add accept-encoding header and decompress the response automatically if it is compressed. I was under the impression that the default HTTP client should handle it transparently? However it doesn't appear to:

```<code>    req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
    // req.Header.Add("Accept-Encoding", "gzip")
    client := &http.Client{}
    resp, _ := client.Do(req)
    println(resp.Header.Get("Content-Encoding"))
</code>```

If I add the Accept-Encoding manually, it sends the header, but I have to uncompress the response manually.

答:
If the Transport requests gzip on its own and gets a gzipped response, then the response is transparently decompressed. The transport removes the Content-Encoding header from the response in this case.
Check the Response. Uncompressed field to determine if the response was uncompressed.

```<code>req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
resp, _ := http.DefaultClient.Do(req)
fmt.Println(resp.Uncompressed) // prints true
fmt.Println(resp.Header.Get("Content-Encoding"))  // prints blank line
</code>```

If the application explicitly requests gzip, then the response is returned as is.

```<code>req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
req.Header.Add("Accept-Encoding", "gzip")
client := &http.Client{}
resp, _ := client.Do(req)
fmt.Println(resp.Uncompressed)  // prints false
fmt.Println(resp.Header.Get("Content-Encoding")) prints gzip
</code>```

Body:
I'm trying to do an HTTP request and have golang add accept-encoding header and decompress the response automatically if it is compressed. I was under the impression that the default HTTP client should handle it transparently? However it doesn't appear to:

    req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
    // req.Header.Add("Accept-Encoding", "gzip")
    client := &http.Client{}
    resp, _ := client.Do(req)
    println(resp.Header.Get("Content-Encoding"))

If I add the Accept-Encoding manually, it sends the header, but I have to uncompress the response manually.

Body:
If the Transport requests gzip on its own and gets a gzipped response, then the response is transparently decompressed. The transport removes the Content-Encoding header from the response in this case.
Check the Response. Uncompressed field to determine if the response was uncompressed.

req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
resp, _ := http.DefaultClient.Do(req)
fmt.Println(resp.Uncompressed) // prints true
fmt.Println(resp.Header.Get("Content-Encoding"))  // prints blank line

If the application explicitly requests gzip, then the response is returned as is.

req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
req.Header.Add("Accept-Encoding", "gzip")
client := &http.Client{}
resp, _ := client.Do(req)
fmt.Println(resp.Uncompressed)  // prints false
fmt.Println(resp.Header.Get("Content-Encoding")) prints gzip


问:
Run Playwright.NET tests in Docker container
I have the following Dockerfile:

```<code>FROM mcr.microsoft.com/dotnet/runtime:5.0-buster-slim AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["PlaywrightSharp.csproj", "PlaywrightSharp/"]
RUN dotnet restore "PlaywrightSharp/PlaywrightSharp.csproj"
COPY . "/src/PlaywrightSharp"
WORKDIR "/src/PlaywrightSharp"
RUN apt-get update -yq && apt-get upgrade -yq && apt-get install -yq curl git nano
RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - && apt-get install -yq nodejs build-essential
RUN npm install -g npm

RUN dotnet add package Microsoft.Playwright
RUN dotnet build "PlaywrightSharp.csproj" -c Release -o /app/build
RUN npx playwright install-deps
RUN npx playwright install

RUN dotnet test --no-build
</code>```

I build the image using the following command:

```<code>docker build -t sarbo/playwrightsharp .
</code>```

Everything is ok but when test execution is started I get:

```<code>#19 1.227 Starting test execution, please wait...
#19 1.263 A total of 1 test files matched the specified pattern.
#19 3.223   Failed Main [711 ms]
#19 3.223   Error Message:
#19 3.223    Microsoft.Playwright.PlaywrightException :
#19 3.223 ╔════════════════════════════════════════════════════════════╗
#19 3.223 ║ Host system is missing a few dependencies to run browsers. ║
#19 3.223 ║ Please install them with the following command:            ║
#19 3.223 ║                                                            ║
#19 3.223 ║     playwright install-deps                                ║
#19 3.223 ║                                                            ║
#19 3.223 ║ <3 Playwright Team                                         ║
#19 3.223 ╚════════════════════════════════════════════════════════════╝
#19 3.223   Stack Trace:
#19 3.223      at Microsoft.Playwright.Transport.Connection.SendMessageToServerAsync[T](String guid, String method, Object args)
#19 3.223    at Microsoft.Playwright.Core.BrowserType.LaunchAsync(BrowserTypeLaunchOptions options)
#19 3.223    at PlaywrightSharp.Tests.Main() in /Users/sarbo/Documents/Projects/PlaywrightDemo/PlaywrightSharp/UnitTest1.cs:line 96
#19 3.223    at NUnit.Framework.Internal.TaskAwaitAdapter.GenericAdapter`1.BlockUntilCompleted()
#19 3.223    at NUnit.Framework.Internal.MessagePumpStrategy.NoMessagePumpStrategy.WaitForCompletion(AwaitAdapter awaiter)
#19 3.223    at NUnit.Framework.Internal.AsyncToSyncAdapter.Await(Func`1 invoke)
#19 3.223    at NUnit.Framework.Internal.Commands.TestMethodCommand.RunTestMethod(TestExecutionContext context)
#19 3.223    at NUnit.Framework.Internal.Commands.TestMethodCommand.Execute(TestExecutionContext context)
#19 3.223    at NUnit.Framework.Internal.Commands.BeforeAndAfterTestCommand.<>c__DisplayClass1_0.<Execute>b__0()
#19 3.223    at NUnit.Framework.Internal.Commands.BeforeAndAfterTestCommand.RunTestMethodInThreadAbortSafeZone(TestExecutionContext context, Action action)
#19 3.224   Failed Test1 [362 ms]
</code>```

Line 96 from UnitTest1.cs:

```<code>await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
    Headless = true,
});
</code>```

Is there another way to install those dependencies that required to run Playwright tests in Docker? Tests are running on local environment without any issues but when I try to launch the browser instance inside container the error is thrown.

答:
Finally I was able to find a way to run the tests inside a Docker container using a custom image. Here is what I've done:

```<code>FROM mcr.microsoft.com/dotnet/sdk:5.0.404-focal AS build
WORKDIR /src
COPY ["PlaywrightSharp/PlaywrightSharp.csproj", "PlaywrightSharp/"]
RUN dotnet restore "PlaywrightSharp/PlaywrightSharp.csproj"

COPY . .
WORKDIR "/src/PlaywrightSharp"

RUN apt-get update -yq && apt-get upgrade -yq && apt-get install -yq curl git nano
RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - && apt-get install -yq nodejs build-essential
RUN npm install -g npm

RUN apt-get install -y wget xvfb unzip

# Set up the Chrome PPA
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list

# Update the package list and install chrome
RUN apt-get update -y
RUN apt-get install -y google-chrome-stable
RUN apt-get install -y firefox

#RUN dotnet add package Microsoft.Playwright
RUN dotnet build "PlaywrightSharp.csproj" -c Release -o /app/build
RUN npx playwright install-deps
RUN npx playwright install

FROM build AS testrunner
WORKDIR "/src/PlaywrightSharp"
CMD ["dotnet", "test", "--no-restore", "--settings:Firefox.runsettings", "--logger:trx"]
</code>```

It looks like npx playwright install-deps was not enough to run the tests and I had to install Chrome and Firefox also.

Body:
I have the following Dockerfile:

FROM mcr.microsoft.com/dotnet/runtime:5.0-buster-slim AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["PlaywrightSharp.csproj", "PlaywrightSharp/"]
RUN dotnet restore "PlaywrightSharp/PlaywrightSharp.csproj"
COPY . "/src/PlaywrightSharp"
WORKDIR "/src/PlaywrightSharp"
RUN apt-get update -yq && apt-get upgrade -yq && apt-get install -yq curl git nano
RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - && apt-get install -yq nodejs build-essential
RUN npm install -g npm

RUN dotnet add package Microsoft.Playwright
RUN dotnet build "PlaywrightSharp.csproj" -c Release -o /app/build
RUN npx playwright install-deps
RUN npx playwright install

RUN dotnet test --no-build

I build the image using the following command:

docker build -t sarbo/playwrightsharp .

Everything is ok but when test execution is started I get:

#19 1.227 Starting test execution, please wait...
#19 1.263 A total of 1 test files matched the specified pattern.
#19 3.223   Failed Main [711 ms]
#19 3.223   Error Message:
#19 3.223    Microsoft.Playwright.PlaywrightException :
#19 3.223 ╔════════════════════════════════════════════════════════════╗
#19 3.223 ║ Host system is missing a few dependencies to run browsers. ║
#19 3.223 ║ Please install them with the following command:            ║
#19 3.223 ║                                                            ║
#19 3.223 ║     playwright install-deps                                ║
#19 3.223 ║                                                            ║
#19 3.223 ║ <3 Playwright Team                                         ║
#19 3.223 ╚════════════════════════════════════════════════════════════╝
#19 3.223   Stack Trace:
#19 3.223      at Microsoft.Playwright.Transport.Connection.SendMessageToServerAsync[T](String guid, String method, Object args)
#19 3.223    at Microsoft.Playwright.Core.BrowserType.LaunchAsync(BrowserTypeLaunchOptions options)
#19 3.223    at PlaywrightSharp.Tests.Main() in /Users/sarbo/Documents/Projects/PlaywrightDemo/PlaywrightSharp/UnitTest1.cs:line 96
#19 3.223    at NUnit.Framework.Internal.TaskAwaitAdapter.GenericAdapter`1.BlockUntilCompleted()
#19 3.223    at NUnit.Framework.Internal.MessagePumpStrategy.NoMessagePumpStrategy.WaitForCompletion(AwaitAdapter awaiter)
#19 3.223    at NUnit.Framework.Internal.AsyncToSyncAdapter.Await(Func`1 invoke)
#19 3.223    at NUnit.Framework.Internal.Commands.TestMethodCommand.RunTestMethod(TestExecutionContext context)
#19 3.223    at NUnit.Framework.Internal.Commands.TestMethodCommand.Execute(TestExecutionContext context)
#19 3.223    at NUnit.Framework.Internal.Commands.BeforeAndAfterTestCommand.<>c__DisplayClass1_0.<Execute>b__0()
#19 3.223    at NUnit.Framework.Internal.Commands.BeforeAndAfterTestCommand.RunTestMethodInThreadAbortSafeZone(TestExecutionContext context, Action action)
#19 3.224   Failed Test1 [362 ms]

Line 96 from UnitTest1.cs:

await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
    Headless = true,
});

Is there another way to install those dependencies that required to run Playwright tests in Docker? Tests are running on local environment without any issues but when I try to launch the browser instance inside container the error is thrown.

Body:
Finally I was able to find a way to run the tests inside a Docker container using a custom image. Here is what I've done:

FROM mcr.microsoft.com/dotnet/sdk:5.0.404-focal AS build
WORKDIR /src
COPY ["PlaywrightSharp/PlaywrightSharp.csproj", "PlaywrightSharp/"]
RUN dotnet restore "PlaywrightSharp/PlaywrightSharp.csproj"

COPY . .
WORKDIR "/src/PlaywrightSharp"

RUN apt-get update -yq && apt-get upgrade -yq && apt-get install -yq curl git nano
RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - && apt-get install -yq nodejs build-essential
RUN npm install -g npm

RUN apt-get install -y wget xvfb unzip

# Set up the Chrome PPA
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list

# Update the package list and install chrome
RUN apt-get update -y
RUN apt-get install -y google-chrome-stable
RUN apt-get install -y firefox

#RUN dotnet add package Microsoft.Playwright
RUN dotnet build "PlaywrightSharp.csproj" -c Release -o /app/build
RUN npx playwright install-deps
RUN npx playwright install

FROM build AS testrunner
WORKDIR "/src/PlaywrightSharp"
CMD ["dotnet", "test", "--no-restore", "--settings:Firefox.runsettings", "--logger:trx"]

It looks like npx playwright install-deps was not enough to run the tests and I had to install Chrome and Firefox also.


问:
How to determine the location of a touch using view property
I'm trying to develop some simple game apps. For a Pong-styled game, I have a moving ball that stays in bounds and two paddles. I implemented code that moves paddle 1 so that it reflects the ball as expected.

When I tried to add the same behavior to the other paddle, I tried this:

```<code>UITouch *touch = [[event allTouches]anyObject]; // Picks up the touch

CGPoint location = [touch locationInView:self.view]; // Gets coordinates
// to help move the paddle on the X axis; Y axis is determined by the paddle,
// so it only moves along one axis

if ([touch view] == paddle2) {
    // move the second paddle
    ...
}

else {
    // move the first paddle
    ...
}
</code>```

However, any touches only move paddle1, indicating the condition is never activated. Based on the documentation, I thought that by sending the [touch view] message, the image view that was touched would return its own name.
What am I doing wrong? Is a simpler way to do this?

答:
Do not use different views for the paddles, use one host view with different CALayers for drawing you objects.

You can move you paddles by assigning new origin to the layers.
The view should proces the following methods

```<code>- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
</code>```

to find out where you touched it.
Assuming you know the frames of you paddles you can decide whether you hit them with the touch or not.

I hope this helps.

Body:
I'm trying to develop some simple game apps. For a Pong-styled game, I have a moving ball that stays in bounds and two paddles. I implemented code that moves paddle 1 so that it reflects the ball as expected.

When I tried to add the same behavior to the other paddle, I tried this:

UITouch *touch = [[event allTouches]anyObject]; // Picks up the touch

CGPoint location = [touch locationInView:self.view]; // Gets coordinates
// to help move the paddle on the X axis; Y axis is determined by the paddle,
// so it only moves along one axis

if ([touch view] == paddle2) {
    // move the second paddle
    ...
}

else {
    // move the first paddle
    ...
}

However, any touches only move paddle1, indicating the condition is never activated. Based on the documentation, I thought that by sending the [touch view] message, the image view that was touched would return its own name.
What am I doing wrong? Is a simpler way to do this?

Body:
Do not use different views for the paddles, use one host view with different CALayers for drawing you objects.

You can move you paddles by assigning new origin to the layers.
The view should proces the following methods

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

to find out where you touched it.
Assuming you know the frames of you paddles you can decide whether you hit them with the touch or not.

I hope this helps.


问:
How can I solve - Uncaught TypeError: removeIndividualBook is not a function?
I have removeIndividualBook in index.js which removes individual book. This functionality was working fine from Book component.

I am creating new component Quantity and trying to access removeIndividualBook  there. I am passing removeIndividualBook  as prop from index.js to Book.js to Quantity.js.

In Quantity.js I am getting Uncaught TypeError: removeIndividualBook is not a function

index.js

```<code>  // Remove Individual book
  const removeIndividualBook = (id) => {
    const updatedBookData = booksData.filter((book) => {
      return book.id !== id;
    });
    setBooksData(updatedBookData);
  };

<Book key={index} {...book} removeIndividualBook={removeIndividualBook}></Book>
</code>```

Book.js

```<code>const Book = ({description,id,removeIndividualBook}) => {
  const clickHandler = () => {
    alert(description);
  };
      <Quantity id={id} removeIndividualBook={removeIndividualBook} />

</code>```

Quantity.js

```<code>const Quantity = (id, removeIndividualBook) => {const Quantity = (id, removeIndividualBook) => {}

return (
    <>
      <button
        className="button" onClick={() => removeIndividualBook(id)}> ------>>> Error
</code>```

答:
I reproduced somehow your components with a code snippet.

I think your problem is because you are not destructuring props correctly, (id, removeIndividualBook), they should be ({id, removeIndividualBook}).

Here is the link that you can see that it works properly:

Code Snippet Link

Hope this solves your issue!

Body:
I have removeIndividualBook in index.js which removes individual book. This functionality was working fine from Book component.

I am creating new component Quantity and trying to access removeIndividualBook  there. I am passing removeIndividualBook  as prop from index.js to Book.js to Quantity.js.

In Quantity.js I am getting Uncaught TypeError: removeIndividualBook is not a function

index.js

  // Remove Individual book
  const removeIndividualBook = (id) => {
    const updatedBookData = booksData.filter((book) => {
      return book.id !== id;
    });
    setBooksData(updatedBookData);
  };

<Book key={index} {...book} removeIndividualBook={removeIndividualBook}></Book>

Book.js

const Book = ({description,id,removeIndividualBook}) => {
  const clickHandler = () => {
    alert(description);
  };
      <Quantity id={id} removeIndividualBook={removeIndividualBook} />

Quantity.js

const Quantity = (id, removeIndividualBook) => {const Quantity = (id, removeIndividualBook) => {}

return (
    <>
      <button
        className="button" onClick={() => removeIndividualBook(id)}> ------>>> Error


问:
Does Electron support drag-and-dropping a file path into another application?
In C# WinForms, I could do this

```<code>var data = new DataObject(DataFormats.FileDrop, filePaths);
myControl.DoDragDrop(data, DragDropEffects.Copy);
</code>```

to make another application, such as Notepad, open the file specified by filePaths. The code is similar in WPF or even in JavaFX. The file path can be any arbitrary file path that is accessible within the system, such as C:\Windows\win.ini or \\myFileServer\sharedDir\sharedFile.txt. I mean making Notepad OPEN the file, NOT displaying the file path text in its editing area. That is, I am d&d'ing a file path, not a string that contains the file path.

Can I do the same thing if I make a desktop application with Electron (only for desktops; don't care about web/mobile)? I have tested it with VS Code, which is said to be created with Electron, and when I dragged a file from its "Explorer" into Notepad, nothing happened. When I did it into Notepad++, it just displayed the file path string in its editing area, so I am guessing Electron doesn't support it, but I want to make it sure.

答:
Yes, there even is a full example in the Electron documentation about this.

Short summary of the example code: when a specific DOM element is being dragged, the renderer sends an event to the main process. For the dragstart event to fire, the DOM element needs to have the attribute draggable="true". In this example, we pass the filename of the file to be dragged along in the message to the main process.

```<code>document.getElementById("foo").ondragstart = event => {
    event.preventDefault();
    ipcRenderer.send("my-drag-start", "test-file.txt");
}
</code>```

The main process handles the IPC message from the renderer and starts the drag operation. Note that you need to specify an icon to be attached to the cursor during the drag operation, triggering an error message if left out.

```<code>ipcMain.on("my-drag-start", (event, filePath) => {
    event.sender.startDrag({
        file: path.join(__dirname, filePath),
        icon: path.join(__dirname, "dnd.png"),
    });
});
</code>```

Body:
In C# WinForms, I could do this

var data = new DataObject(DataFormats.FileDrop, filePaths);
myControl.DoDragDrop(data, DragDropEffects.Copy);

to make another application, such as Notepad, open the file specified by filePaths. The code is similar in WPF or even in JavaFX. The file path can be any arbitrary file path that is accessible within the system, such as C:\Windows\win.ini or \\myFileServer\sharedDir\sharedFile.txt. I mean making Notepad OPEN the file, NOT displaying the file path text in its editing area. That is, I am d&d'ing a file path, not a string that contains the file path.

Can I do the same thing if I make a desktop application with Electron (only for desktops; don't care about web/mobile)? I have tested it with VS Code, which is said to be created with Electron, and when I dragged a file from its "Explorer" into Notepad, nothing happened. When I did it into Notepad++, it just displayed the file path string in its editing area, so I am guessing Electron doesn't support it, but I want to make it sure.

Body:
Yes, there even is a full example in the Electron documentation about this.

Short summary of the example code: when a specific DOM element is being dragged, the renderer sends an event to the main process. For the dragstart event to fire, the DOM element needs to have the attribute draggable="true". In this example, we pass the filename of the file to be dragged along in the message to the main process.

document.getElementById("foo").ondragstart = event => {
    event.preventDefault();
    ipcRenderer.send("my-drag-start", "test-file.txt");
}

The main process handles the IPC message from the renderer and starts the drag operation. Note that you need to specify an icon to be attached to the cursor during the drag operation, triggering an error message if left out.

ipcMain.on("my-drag-start", (event, filePath) => {
    event.sender.startDrag({
        file: path.join(__dirname, filePath),
        icon: path.join(__dirname, "dnd.png"),
    });
});


问:
How to get access to JwtToken to check with blacklist within nestjs passport strategy?
I'm trying to check for blacklisted JWT tokens within JWTStrategy. jwtFromRequest doesn't take an async function, so I can't check it there.

validate function gives access to JWT payload and not the token.

Below is my sample code.

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService<AppJWTSettings>,
    @Inject(CACHE_MANAGER) private readonly cache: Cache,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), // Returns the encoded JWT string or null.
      ignoreExpiration: false, // validate the expiration of the token.
      // https://docs.nestjs.com/techniques/authentication#implementing-passport-jwt
      // PEM-encoded public key
      secretOrKey: configService.get<string>('JWT_PUBLIC_KEY'),
      algorithms: ['RS256'],
    });
  }

  /**
   * Passport will build a user object based on the return value of our validate() method,
   * and attach it as a property on the Request object.
   *
   * @param payload JWT payload
   */
  async validate(payload: JwtPayload): Promise<JwtUser> {
    const user = { id: payload.sub, iat: payload.iat };
    return user;
  }
}
```

答:
There is one option with secretOrKeyProvider. Here is an example:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService<AppJWTSettings>,
    @Inject(CACHE_MANAGER) private readonly cache: Cache,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), // Returns the encoded JWT string or null.
      ignoreExpiration: false, // validate the expiration of the token.
      // https://docs.nestjs.com/techniques/authentication#implementing-passport-jwt
      // PEM-encoded public key
      secretOrKeyProvider: (
        _request: Request,
        rawJwtToken: any,
        done: (err: any, secretOrKey?: string | Buffer) => void,
      ) => {
        // Check if your token is blocked here!!!
        void isBlocked(rawJwtToken).then(isBlocked => {
          if (isBlocked) {
            done(new Error("This token is blocked"));
          } else {
            done(null, configService.get<string>('JWT_PUBLIC_KEY'));
          }
        });
      },
      algorithms: ['RS256'],
    });
  }

  /**
   * Passport will build a user object based on the return value of our validate() method,
   * and attach it as a property on the Request object.
   *
   * @param payload JWT payload
   */
  async validate(payload: JwtPayload): Promise<JwtUser> {
    const user = { id: payload.sub, iat: payload.iat };
    return user;
  }
}
```


问:
Mermaid CLI - how do you escape characters?
I'm using the Mermaid CLI to generate a flowchart (http://knsv.github.io/mermaid/flowchart.html).  It works great, but I can't figure out how to get special characters (percent signs, parenthesis, etc) working as text within a node.

For illustration purposes here is a sample flowchart definition for Mermaid (filename is example.mermaid):

```<code>graph TD
question1{Gas tank less than 1/8?}
action1[Fill tank to 100%]
question1-- Yes -->action1
</code>```

When I run mermaid on that file, I get this error (it blows up on the percent sign):

```<code>My-MacBook-Pro:mermaid mark$ mermaid example.mermaid
Error: Parse error on line 3:
...on1[Fill tank to 100%]question1-- Yes -
-----------------------^
Expecting 'QUOTE', 'TAG_END', 'TAG_START', 'MULT', 'EQUALS', 'PLUS', 'DOT', 'BRKT', 'COLON', 'ALPHA', 'COMMA', 'NUM', 'CLICK', 'CLASS', 'CLASSDEF', 'LINKSTYLE', 'STYLE', 'PIPE', 'THICK_ARROW_OPEN', 'THICK_ARROW_CROSS', 'THICK_ARROW_CIRCLE', 'THICK_ARROW_POINT', 'DOTTED_ARROW_OPEN', 'DOTTED_ARROW_CROSS', 'DOTTED_ARROW_CIRCLE', 'DOTTED_ARROW_POINT', 'ARROW_OPEN', 'ARROW_CROSS', 'ARROW_CIRCLE', 'ARROW_POINT', '==', '-.', '--', 'MINUS', 'DIAMOND_STOP', 'DIAMOND_START', 'PE', 'PS', 'SQE', 'SQS', 'end', 'subgraph', 'NEWLINE', 'TAGSTART', 'TAGEND', 'DIR', 'SPACE', 'GRAPH', 'EOF', 'SEMI', got 'PCT'

  ../dist/mermaid.full.js:14712 in parseError
  ../dist/mermaid.full.js:14782 in parse
  ../dist/mermaid.full.js:13260
  ../dist/mermaid.full.js:16846
  ../dist/mermaid.full.js:16889
  phantomjs://webpage.evaluate():23 in executeInPage
  phantomjs://webpage.evaluate():29
  phantomjs://webpage.evaluate():29
PHANTOM ERROR: TypeError: 'null' is not an object (evaluating 'element.setAttribute')
TRACE:
 -> /usr/local/lib/node_modules/mermaid/lib/phantomscript.js: 149 (in function resolveSVGElement)
 -> /usr/local/lib/node_modules/mermaid/lib/phantomscript.js: 69
</code>```

I tried escaping the percent sign, like this:

```<code>action1[Fill tank to 100&]
</code>```

But then I get the same error on the semicolon.  Any thoughts on how I can escape those characters to make it work?  Thanks!

答:
Here are more examples of escaping / quoting special characters. The code

```<code>flowchart LR
  A["For most symbols double quotes are enough: ```~`!@#$%^*()[]{}|\/:;'?<>,.+=-_"]
  B["["&quot;&lt;
&gt;&amp;&frac12;#35;189;"]"]
  B --> C[""<
>&½#189;"]
```

produces

Using this method most unicode characters (including non-ASCII) can be included using either unicode entity or markdown #code; syntax (both ways are illustrated using the character ½ in the diagram above). See also the official documentation.

Disclaimer: I didn't test it in Mermaid CLI. Tested in markdown-viewer and Mermaid live editor.

Body:
I'm using the Mermaid CLI to generate a flowchart (http://knsv.github.io/mermaid/flowchart.html).  It works great, but I can't figure out how to get special characters (percent signs, parenthesis, etc) working as text within a node.

For illustration purposes here is a sample flowchart definition for Mermaid (filename is example.mermaid):

graph TD
question1{Gas tank less than 1/8?}
action1[Fill tank to 100%]
question1-- Yes -->action1

When I run mermaid on that file, I get this error (it blows up on the percent sign):

My-MacBook-Pro:mermaid mark$ mermaid example.mermaid
Error: Parse error on line 3:
...on1[Fill tank to 100%]question1-- Yes -
-----------------------^
Expecting 'QUOTE', 'TAG_END', 'TAG_START', 'MULT', 'EQUALS', 'PLUS', 'DOT', 'BRKT', 'COLON', 'ALPHA', 'COMMA', 'NUM', 'CLICK', 'CLASS', 'CLASSDEF', 'LINKSTYLE', 'STYLE', 'PIPE', 'THICK_ARROW_OPEN', 'THICK_ARROW_CROSS', 'THICK_ARROW_CIRCLE', 'THICK_ARROW_POINT', 'DOTTED_ARROW_OPEN', 'DOTTED_ARROW_CROSS', 'DOTTED_ARROW_CIRCLE', 'DOTTED_ARROW_POINT', 'ARROW_OPEN', 'ARROW_CROSS', 'ARROW_CIRCLE', 'ARROW_POINT', '==', '-.', '--', 'MINUS', 'DIAMOND_STOP', 'DIAMOND_START', 'PE', 'PS', 'SQE', 'SQS', 'end', 'subgraph', 'NEWLINE', 'TAGSTART', 'TAGEND', 'DIR', 'SPACE', 'GRAPH', 'EOF', 'SEMI', got 'PCT'

  ../dist/mermaid.full.js:14712 in parseError
  ../dist/mermaid.full.js:14782 in parse
  ../dist/mermaid.full.js:13260
  ../dist/mermaid.full.js:16846
  ../dist/mermaid.full.js:16889
  phantomjs://webpage.evaluate():23 in executeInPage
  phantomjs://webpage.evaluate():29
  phantomjs://webpage.evaluate():29
PHANTOM ERROR: TypeError: 'null' is not an object (evaluating 'element.setAttribute')
TRACE:
 -> /usr/local/lib/node_modules/mermaid/lib/phantomscript.js: 149 (in function resolveSVGElement)
 -> /usr/local/lib/node_modules/mermaid/lib/phantomscript.js: 69

I tried escaping the percent sign, like this:

action1[Fill tank to 100&]

But then I get the same error on the semicolon.  Any thoughts on how I can escape those characters to make it work?  Thanks!

Body:
Here are more examples of escaping / quoting special characters. The code

flowchart LR
  A["For most symbols double quotes are enough: ```~`!@#$%^*()[]{}|\/:;'?<>,.+=-_"]
  B["[&quot;&amp;quot;&amp;lt;&lt;br&gt;&amp;gt;&amp;amp;&amp;frac12;#35;189;&quot;]"]
  B --> C["&quot;&lt;<br>&gt;&amp;&frac12;#189;"]

produces

Using this method most unicode characters (including non-ASCII) can be included using either unicode entity or markdown #code; syntax (both ways are illustrated using the character ½ in the diagram above). See also the official documentation.

Disclaimer: I didn't test it in Mermaid CLI. Tested in markdown-viewer and Mermaid live editor.


问:
display list that in each row 1 li
How can I display the list that in each line I will have one li and not 2 li in one row?

                    corona

```

答:
You can simply wrap your images into individual
 elements, and they will appear below each other:

                    corona

```

Title: display list that in each row 1 li

Body:
You can simply wrap your images into individual <li> elements, and they will appear below each other:

<div class="recent_questions promoted_questions pblock">
    <ul class="vertical_menu main_questions">
        <li>
            <span class="header">
                <a href="covid.php">
                    corona
                    <img src="photos/Covid.gif">
                </a>
            </span>
        </li>
        <li>
            <span class="questions">
                <span class="big_image">
                    <img class="photo_sub" src="photos/covid.jpg" />
                </span>
            </span>
        </li>
    </ul>
</div>


问:
PG::UndefinedTable: ERROR: relation "..." does not exist
I know this has been asked so many times but I have tried many solutions with no luck. I have a Rails app deployed on Heroku, it works locally but I get "We're sorry, but something went wrong." when I try to launch it on Heroku.

I have tried

```<code>heroku run rake db:migrate
heroku restart
heroku open
</code>```

but the table already exists in schema

I have tried:

```<code>rake db:reset
</code>```

and
    rake db:drop db:create db:migrate

I know that by default, changes are done in the development environment, could this be the reason? I'm running the changes in the development env but the 'heroku open' opens the prod env?

 Update, the complete snippet for heroku logs:
heroku logs

```<code>    2015-12-12T05:47:57.814680+00:00 app[web.1]:    /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:32:in `start'
2015-12-12T05:47:57.814679+00:00 app[web.1]:    /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:170:in `block in start'
2015-12-12T05:47:57.814682+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/server.rb:264:in `start'
2015-12-12T05:47:57.814680+00:00 app[web.1]:    /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:160:in `start'
2015-12-12T05:47:57.814683+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands/server.rb:69:in `start'
2015-12-12T05:47:57.814681+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb:14:in `run'
2015-12-12T05:47:57.814684+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands/commands_tasks.rb:81:in `block in server'
2015-12-12T05:47:57.814685+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands/commands_tasks.rb:76:in `tap'
2015-12-12T05:47:57.814686+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands/commands_tasks.rb:76:in `server'
2015-12-12T05:47:57.814686+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
2015-12-12T05:47:57.814687+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands.rb:17:in `<top (required)>'
2015-12-12T05:47:57.814688+00:00 app[web.1]:    bin/rails:8:in `require'
2015-12-12T05:47:57.814688+00:00 app[web.1]:    bin/rails:8:in `<main>'
2015-12-12T05:47:57.814711+00:00 app[web.1]: [2015-12-12 05:47:57] INFO  going to shutdown ...
2015-12-12T05:47:57.814800+00:00 app[web.1]: Exiting
2015-12-12T05:47:57.814767+00:00 app[web.1]: [2015-12-12 05:47:57] INFO  WEBrick::HTTPServer#start done.
2015-12-12T05:47:58.668656+00:00 heroku[web.1]: Process exited with status 143
2015-12-12T15:25:42.166048+00:00 heroku[web.1]: Unidling
2015-12-12T15:25:42.166363+00:00 heroku[web.1]: State changed from down to starting
2015-12-12T15:25:43.961413+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 31053 -e production`
2015-12-12T15:25:47.675210+00:00 app[web.1]: [2015-12-12 15:25:47] INFO  WEBrick 1.3.1
2015-12-12T15:25:47.675235+00:00 app[web.1]: [2015-12-12 15:25:47] INFO  ruby 2.0.0 (2014-11-13) [x86_64-linux]
2015-12-12T15:25:47.675544+00:00 app[web.1]: [2015-12-12 15:25:47] INFO  WEBrick::HTTPServer#start: pid=3 port=31053
2015-12-12T15:25:48.347999+00:00 heroku[web.1]: State changed from starting to up
2015-12-12T15:25:49.238228+00:00 app[web.1]: => Booting WEBrick
2015-12-12T15:25:49.238232+00:00 app[web.1]: => Rails 4.1.6 application starting in production on http://0.0.0.0:31053
2015-12-12T15:25:49.238233+00:00 app[web.1]: => Run `rails server -h` for more startup options
2015-12-12T15:25:49.238235+00:00 app[web.1]: => Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
2015-12-12T15:25:49.238235+00:00 app[web.1]: => Ctrl-C to shutdown server
2015-12-12T15:25:49.238236+00:00 app[web.1]: Started GET "/" for 98.196.181.134 at 2015-12-12 15:25:49 +0000
2015-12-12T15:25:49.371270+00:00 app[web.1]: Processing by UsersController#index as HTML
2015-12-12T15:25:49.385278+00:00 heroku[router]: at=info method=GET path="/" host=appname.herokuapp.com request_id=276e00fc-cadd-4b08-ac52-6d72099c9c2e fwd="98.196.181.134" dyno=web.1 connect=1ms service=156ms status=500 bytes=1754
2015-12-12T15:25:49.384220+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:25:49.384216+00:00 app[web.1]: PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:25:49.384221+00:00 app[web.1]:                                   ^
2015-12-12T15:25:49.384222+00:00 app[web.1]: : SELECT "users".* FROM "users"
2015-12-12T15:25:49.384742+00:00 app[web.1]:   Rendered users/index.html.erb within layouts/application (3.7ms)
2015-12-12T15:25:49.384868+00:00 app[web.1]: Completed 500 Internal Server Error in 14ms
2015-12-12T15:25:49.387101+00:00 app[web.1]:
2015-12-12T15:25:49.387105+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:25:49.387103+00:00 app[web.1]: ActionView::Template::Error (PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:25:49.387105+00:00 app[web.1]:                                   ^
2015-12-12T15:25:49.387106+00:00 app[web.1]: : SELECT "users".* FROM "users"):
2015-12-12T15:25:49.387107+00:00 app[web.1]:     15:
2015-12-12T15:25:49.387107+00:00 app[web.1]:     14:   </thead>
2015-12-12T15:25:49.387110+00:00 app[web.1]:     17:     <% @users.each do |user| %>
2015-12-12T15:25:49.387110+00:00 app[web.1]:     18:       <tr>
2015-12-12T15:25:49.387108+00:00 app[web.1]:     16:   <tbody>
2015-12-12T15:25:49.387112+00:00 app[web.1]:     20:         <td><%= user.address %></td>
2015-12-12T15:25:49.387111+00:00 app[web.1]:     19:         <td><%= user.name %></td>
2015-12-12T15:25:49.387116+00:00 app[web.1]:   app/views/users/index.html.erb:17:in `_app_views_users_index_html_erb___3405507757113956440_70276178207640'
2015-12-12T15:25:49.387118+00:00 app[web.1]:
2015-12-12T15:25:49.387117+00:00 app[web.1]:
2015-12-12T15:27:59.501112+00:00 heroku[router]: at=info method=GET path="/" host=appname.herokuapp.com request_id=279ab493-5a01-4b89-b0a8-cbc9cb51fe83 fwd="98.196.181.134" dyno=web.1 connect=0ms service=18ms status=500 bytes=1754
2015-12-12T15:27:59.486906+00:00 app[web.1]: Started GET "/" for 98.196.181.134 at 2015-12-12 15:27:59 +0000
2015-12-12T15:27:59.496321+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:27:59.496322+00:00 app[web.1]:                                   ^
2015-12-12T15:27:59.496318+00:00 app[web.1]: PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:27:59.496323+00:00 app[web.1]: : SELECT "users".* FROM "users"
2015-12-12T15:27:59.499226+00:00 app[web.1]:
2015-12-12T15:27:59.496875+00:00 app[web.1]:   Rendered users/index.html.erb within layouts/application (2.7ms)
2015-12-12T15:27:59.496993+00:00 app[web.1]: Completed 500 Internal Server Error in 4ms
2015-12-12T15:27:59.499229+00:00 app[web.1]: ActionView::Template::Error (PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:27:59.499231+00:00 app[web.1]:                                   ^
2015-12-12T15:27:59.499230+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:27:59.499231+00:00 app[web.1]: : SELECT "users".* FROM "users"):
2015-12-12T15:27:59.499233+00:00 app[web.1]:     16:   <tbody>
2015-12-12T15:27:59.499232+00:00 app[web.1]:     14:   </thead>
2015-12-12T15:27:59.499233+00:00 app[web.1]:     15:
2015-12-12T15:27:59.499234+00:00 app[web.1]:     17:     <% @users.each do |user| %>
2015-12-12T15:27:59.499235+00:00 app[web.1]:     18:       <tr>
2015-12-12T15:27:59.499239+00:00 app[web.1]:
2015-12-12T15:27:59.499237+00:00 app[web.1]:     20:         <td><%= user.address %></td>
2015-12-12T15:27:59.499236+00:00 app[web.1]:     19:         <td><%= user.name %></td>
2015-12-12T15:27:59.499239+00:00 app[web.1]:   app/views/users/index.html.erb:17:in `_app_views_users_index_html_erb___3405507757113956440_70276178207640'
2015-12-12T15:27:59.499240+00:00 app[web.1]:
2015-12-12T15:27:59.493196+00:00 app[web.1]: Processing by UsersController#index as HTML
2015-12-12T15:28:02.359919+00:00 app[web.1]: Started GET "/" for 98.196.181.134 at 2015-12-12 15:28:02 +0000
2015-12-12T15:28:02.366634+00:00 app[web.1]: PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:28:02.366638+00:00 app[web.1]:                                   ^
2015-12-12T15:28:02.366639+00:00 app[web.1]: : SELECT "users".* FROM "users"
2015-12-12T15:28:02.366637+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:28:02.367435+00:00 app[web.1]:   Rendered users/index.html.erb within layouts/application (3.1ms)
2015-12-12T15:28:02.367587+00:00 app[web.1]: Completed 500 Internal Server Error in 4ms
2015-12-12T15:28:02.369955+00:00 app[web.1]:
2015-12-12T15:28:02.369959+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:28:02.370984+00:00 heroku[router]: at=info method=GET path="/" host=appname.herokuapp.com request_id=2b1fbddf-0ef7-4d8c-9107-9e67a2a1ca6a fwd="98.196.181.134" dyno=web.1 connect=0ms service=14ms status=500 bytes=1754
2015-12-12T15:28:02.369958+00:00 app[web.1]: ActionView::Template::Error (PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:28:02.363203+00:00 app[web.1]: Processing by UsersController#index as HTML
2015-12-12T15:28:02.369960+00:00 app[web.1]:                                   ^
2015-12-12T15:28:02.369960+00:00 app[web.1]: : SELECT "users".* FROM "users"):
2015-12-12T15:28:02.369961+00:00 app[web.1]:     14:   </thead>
2015-12-12T15:28:02.369962+00:00 app[web.1]:     15:
2015-12-12T15:28:02.369963+00:00 app[web.1]:     17:     <% @users.each do |user| %>
2015-12-12T15:28:02.369964+00:00 app[web.1]:     18:       <tr>
2015-12-12T15:28:02.369962+00:00 app[web.1]:     16:   <tbody>
2015-12-12T15:28:02.369964+00:00 app[web.1]:     19:         <td><%= user.name %></td>
2015-12-12T15:28:02.369965+00:00 app[web.1]:     20:         <td><%= user.address %></td>
2015-12-12T15:28:02.369966+00:00 app[web.1]:   app/views/users/index.html.erb:17:in `_app_views_users_index_html_erb___3405507757113956440_70276178207640'
2015-12-12T15:28:02.369967+00:00 app[web.1]:
2015-12-12T15:28:02.369967+00:00 app[web.1]:
</code>```

 Update: Following on @Vincent's answer, I can tell that the table is not being created on Heroku upon migration, so I tried loading the db from schema.rb since my schema has the table,

```<code>$ rake db:schema:load RAILS_ENV=production --trace
** Invoke db:schema:load (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:schema:load
-- enable_extension("plpgsql")
   -> 0.1872s
-- create_table("users", {:force=>true})
   -> 0.1565s
-- initialize_schema_migrations_table()
   -> 0.0876s
$ heroku restart
Restarting dynos... done
$ heroku open
Opening appname... done
$ heroku pg:psql
---> Connecting to HEROKU_POSTGRESQL_WHITE_URL (DATABASE_URL)
psql (9.4.5, server 9.3.9)

appname::WHITE=> \d
                  List of relations
 Schema |       Name        | Type  |     Owner
--------+-------------------+-------+----------------
 public | schema_migrations | table | ownername
(1 row)

$ heroku run rails c
Running rails c on appname... up, run.1689
Loading production environment (Rails 4.1.6)
irb(main):001:0> ActiveRecord::Base.connection.tables
=> ["schema_migrations"]
irb(main):002:0>
</code>```

As you can see, the table users wasn't created. Also, schema_migrations is empty.

What am I missing? Why is not the table users being created in the prod env?

答:
ActionView::Template::Error (PG::UndefinedTable: ERROR:  relation "users" does not exist

Probably you deployed the rails app in Heroku missing the database.

For rails > 6: heroku run rails db:migrate

Body:
I know this has been asked so many times but I have tried many solutions with no luck. I have a Rails app deployed on Heroku, it works locally but I get "We're sorry, but something went wrong." when I try to launch it on Heroku.

I have tried

heroku run rake db:migrate
heroku restart
heroku open

but the table already exists in schema

I have tried:

rake db:reset

and
    rake db:drop db:create db:migrate

I know that by default, changes are done in the development environment, could this be the reason? I'm running the changes in the development env but the 'heroku open' opens the prod env?

 Update, the complete snippet for heroku logs:
heroku logs

    2015-12-12T05:47:57.814680+00:00 app[web.1]:    /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:32:in `start'
2015-12-12T05:47:57.814679+00:00 app[web.1]:    /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:170:in `block in start'
2015-12-12T05:47:57.814682+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/server.rb:264:in `start'
2015-12-12T05:47:57.814680+00:00 app[web.1]:    /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:160:in `start'
2015-12-12T05:47:57.814683+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands/server.rb:69:in `start'
2015-12-12T05:47:57.814681+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb:14:in `run'
2015-12-12T05:47:57.814684+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands/commands_tasks.rb:81:in `block in server'
2015-12-12T05:47:57.814685+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands/commands_tasks.rb:76:in `tap'
2015-12-12T05:47:57.814686+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands/commands_tasks.rb:76:in `server'
2015-12-12T05:47:57.814686+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
2015-12-12T05:47:57.814687+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.6/lib/rails/commands.rb:17:in `<top (required)>'
2015-12-12T05:47:57.814688+00:00 app[web.1]:    bin/rails:8:in `require'
2015-12-12T05:47:57.814688+00:00 app[web.1]:    bin/rails:8:in `'
2015-12-12T05:47:57.814711+00:00 app[web.1]: [2015-12-12 05:47:57] INFO  going to shutdown ...
2015-12-12T05:47:57.814800+00:00 app[web.1]: Exiting
2015-12-12T05:47:57.814767+00:00 app[web.1]: [2015-12-12 05:47:57] INFO  WEBrick::HTTPServer#start done.
2015-12-12T05:47:58.668656+00:00 heroku[web.1]: Process exited with status 143
2015-12-12T15:25:42.166048+00:00 heroku[web.1]: Unidling
2015-12-12T15:25:42.166363+00:00 heroku[web.1]: State changed from down to starting
2015-12-12T15:25:43.961413+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 31053 -e production`
2015-12-12T15:25:47.675210+00:00 app[web.1]: [2015-12-12 15:25:47] INFO  WEBrick 1.3.1
2015-12-12T15:25:47.675235+00:00 app[web.1]: [2015-12-12 15:25:47] INFO  ruby 2.0.0 (2014-11-13) [x86_64-linux]
2015-12-12T15:25:47.675544+00:00 app[web.1]: [2015-12-12 15:25:47] INFO  WEBrick::HTTPServer#start: pid=3 port=31053
2015-12-12T15:25:48.347999+00:00 heroku[web.1]: State changed from starting to up
2015-12-12T15:25:49.238228+00:00 app[web.1]: => Booting WEBrick
2015-12-12T15:25:49.238232+00:00 app[web.1]: => Rails 4.1.6 application starting in production on http://0.0.0.0:31053
2015-12-12T15:25:49.238233+00:00 app[web.1]: => Run `rails server -h` for more startup options
2015-12-12T15:25:49.238235+00:00 app[web.1]: => Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
2015-12-12T15:25:49.238235+00:00 app[web.1]: => Ctrl-C to shutdown server
2015-12-12T15:25:49.238236+00:00 app[web.1]: Started GET "/" for 98.196.181.134 at 2015-12-12 15:25:49 +0000
2015-12-12T15:25:49.371270+00:00 app[web.1]: Processing by UsersController#index as HTML
2015-12-12T15:25:49.385278+00:00 heroku[router]: at=info method=GET path="/" host=appname.herokuapp.com request_id=276e00fc-cadd-4b08-ac52-6d72099c9c2e fwd="98.196.181.134" dyno=web.1 connect=1ms service=156ms status=500 bytes=1754
2015-12-12T15:25:49.384220+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:25:49.384216+00:00 app[web.1]: PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:25:49.384221+00:00 app[web.1]:                                   ^
2015-12-12T15:25:49.384222+00:00 app[web.1]: : SELECT "users".* FROM "users"
2015-12-12T15:25:49.384742+00:00 app[web.1]:   Rendered users/index.html.erb within layouts/application (3.7ms)
2015-12-12T15:25:49.384868+00:00 app[web.1]: Completed 500 Internal Server Error in 14ms
2015-12-12T15:25:49.387101+00:00 app[web.1]:
2015-12-12T15:25:49.387105+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:25:49.387103+00:00 app[web.1]: ActionView::Template::Error (PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:25:49.387105+00:00 app[web.1]:                                   ^
2015-12-12T15:25:49.387106+00:00 app[web.1]: : SELECT "users".* FROM "users"):
2015-12-12T15:25:49.387107+00:00 app[web.1]:     15:
2015-12-12T15:25:49.387107+00:00 app[web.1]:     14:

2015-12-12T15:25:49.387110+00:00 app[web.1]:     17:     <% @users.each do |user| %>
2015-12-12T15:25:49.387110+00:00 app[web.1]:     18:

2015-12-12T15:25:49.387108+00:00 app[web.1]:     16:

2015-12-12T15:25:49.387112+00:00 app[web.1]:     20:         <%= user.address %>
2015-12-12T15:25:49.387111+00:00 app[web.1]:     19:         <%= user.name %>
2015-12-12T15:25:49.387116+00:00 app[web.1]:   app/views/users/index.html.erb:17:in `_app_views_users_index_html_erb___3405507757113956440_70276178207640'
2015-12-12T15:25:49.387118+00:00 app[web.1]:
2015-12-12T15:25:49.387117+00:00 app[web.1]:
2015-12-12T15:27:59.501112+00:00 heroku[router]: at=info method=GET path="/" host=appname.herokuapp.com request_id=279ab493-5a01-4b89-b0a8-cbc9cb51fe83 fwd="98.196.181.134" dyno=web.1 connect=0ms service=18ms status=500 bytes=1754
2015-12-12T15:27:59.486906+00:00 app[web.1]: Started GET "/" for 98.196.181.134 at 2015-12-12 15:27:59 +0000
2015-12-12T15:27:59.496321+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:27:59.496322+00:00 app[web.1]:                                   ^
2015-12-12T15:27:59.496318+00:00 app[web.1]: PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:27:59.496323+00:00 app[web.1]: : SELECT "users".* FROM "users"
2015-12-12T15:27:59.499226+00:00 app[web.1]:
2015-12-12T15:27:59.496875+00:00 app[web.1]:   Rendered users/index.html.erb within layouts/application (2.7ms)
2015-12-12T15:27:59.496993+00:00 app[web.1]: Completed 500 Internal Server Error in 4ms
2015-12-12T15:27:59.499229+00:00 app[web.1]: ActionView::Template::Error (PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:27:59.499231+00:00 app[web.1]:                                   ^
2015-12-12T15:27:59.499230+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:27:59.499231+00:00 app[web.1]: : SELECT "users".* FROM "users"):
2015-12-12T15:27:59.499233+00:00 app[web.1]:     16:

2015-12-12T15:27:59.499232+00:00 app[web.1]:     14:

2015-12-12T15:27:59.499233+00:00 app[web.1]:     15:
2015-12-12T15:27:59.499234+00:00 app[web.1]:     17:     <% @users.each do |user| %>
2015-12-12T15:27:59.499235+00:00 app[web.1]:     18:

2015-12-12T15:27:59.499239+00:00 app[web.1]:
2015-12-12T15:27:59.499237+00:00 app[web.1]:     20:         <%= user.address %>
2015-12-12T15:27:59.499236+00:00 app[web.1]:     19:         <%= user.name %>
2015-12-12T15:27:59.499239+00:00 app[web.1]:   app/views/users/index.html.erb:17:in `_app_views_users_index_html_erb___3405507757113956440_70276178207640'
2015-12-12T15:27:59.499240+00:00 app[web.1]:
2015-12-12T15:27:59.493196+00:00 app[web.1]: Processing by UsersController#index as HTML
2015-12-12T15:28:02.359919+00:00 app[web.1]: Started GET "/" for 98.196.181.134 at 2015-12-12 15:28:02 +0000
2015-12-12T15:28:02.366634+00:00 app[web.1]: PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:28:02.366638+00:00 app[web.1]:                                   ^
2015-12-12T15:28:02.366639+00:00 app[web.1]: : SELECT "users".* FROM "users"
2015-12-12T15:28:02.366637+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:28:02.367435+00:00 app[web.1]:   Rendered users/index.html.erb within layouts/application (3.1ms)
2015-12-12T15:28:02.367587+00:00 app[web.1]: Completed 500 Internal Server Error in 4ms
2015-12-12T15:28:02.369955+00:00 app[web.1]:
2015-12-12T15:28:02.369959+00:00 app[web.1]: LINE 1: SELECT "users".* FROM "users"
2015-12-12T15:28:02.370984+00:00 heroku[router]: at=info method=GET path="/" host=appname.herokuapp.com request_id=2b1fbddf-0ef7-4d8c-9107-9e67a2a1ca6a fwd="98.196.181.134" dyno=web.1 connect=0ms service=14ms status=500 bytes=1754
2015-12-12T15:28:02.369958+00:00 app[web.1]: ActionView::Template::Error (PG::UndefinedTable: ERROR:  relation "users" does not exist
2015-12-12T15:28:02.363203+00:00 app[web.1]: Processing by UsersController#index as HTML
2015-12-12T15:28:02.369960+00:00 app[web.1]:                                   ^
2015-12-12T15:28:02.369960+00:00 app[web.1]: : SELECT "users".* FROM "users"):
2015-12-12T15:28:02.369961+00:00 app[web.1]:     14:

2015-12-12T15:28:02.369962+00:00 app[web.1]:     15:
2015-12-12T15:28:02.369963+00:00 app[web.1]:     17:     <% @users.each do |user| %>
2015-12-12T15:28:02.369964+00:00 app[web.1]:     18:

2015-12-12T15:28:02.369962+00:00 app[web.1]:     16:

2015-12-12T15:28:02.369964+00:00 app[web.1]:     19:         <%= user.name %>
2015-12-12T15:28:02.369965+00:00 app[web.1]:     20:         <%= user.address %>
2015-12-12T15:28:02.369966+00:00 app[web.1]:   app/views/users/index.html.erb:17:in `_app_views_users_index_html_erb___3405507757113956440_70276178207640'
2015-12-12T15:28:02.369967+00:00 app[web.1]:
2015-12-12T15:28:02.369967+00:00 app[web.1]:

 Update: Following on @Vincent's answer, I can tell that the table is not being created on Heroku upon migration, so I tried loading the db from schema.rb since my schema has the table,

$ rake db:schema:load RAILS_ENV=production --trace
** Invoke db:schema:load (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:schema:load
-- enable_extension("plpgsql")
   -> 0.1872s
-- create_table("users", {:force=>true})
   -> 0.1565s
-- initialize_schema_migrations_table()
   -> 0.0876s
$ heroku restart
Restarting dynos... done
$ heroku open
Opening appname... done
$ heroku pg:psql
---> Connecting to HEROKU_POSTGRESQL_WHITE_URL (DATABASE_URL)
psql (9.4.5, server 9.3.9)

appname::WHITE=> \d
                  List of relations
 Schema |       Name        | Type  |     Owner
--------+-------------------+-------+----------------
 public | schema_migrations | table | ownername
(1 row)

$ heroku run rails c
Running rails c on appname... up, run.1689
Loading production environment (Rails 4.1.6)
irb(main):001:0> ActiveRecord::Base.connection.tables
=> ["schema_migrations"]
irb(main):002:0>

As you can see, the table users wasn't created. Also, schema_migrations is empty.

What am I missing? Why is not the table users being created in the prod env?


问:
VSCode breakpoint is not triggering in simple angular 13 app
I could use some help finding out what specifically is keeping vscode debug/breakpoints from working in this small angular 13 project:

https://github.com/eostermueller/angularFlatTreeExample02

The README.md has instructions on how to reproduce the issue.
There isn't much code there -- so it's particularly frustrating that such a trivial example isn't working.

So I recreated the project from scratch:

https://github.com/eostermueller/angularFlatTreeExample01

...and lo and behold, debug/breakpoints are working just fine!

The tsconfig.json files are identical:

https://github.com/eostermueller/angularFlatTreeExample01/blob/main/tsconfig.json
https://github.com/eostermueller/angularFlatTreeExample02/blob/main/tsconfig.json

and vscode launch.json files are pretty similar:

https://github.com/eostermueller/angularFlatTreeExample01/blob/main/.vscode/launch.json
https://github.com/eostermueller/angularFlatTreeExample02/blob/main/.vscode/launch.json

There are a number of small angular version differences inside the package.json files.  The broken one has 13.0-ish dependencies and the working one has 13.1-ish.

Also interesting (and ironic) is that in the working example, we have this in package.json:
https://github.com/eostermueller/angularFlatTreeExample01/blob/main/package.json

```<code>{
  "name": "flat-tree-example-with-debugging",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
</code>```

...and note that '--open' parameter that launches the browser is absent from the last line, yet when I run the browser actually opens, displays the page and then focus moves to vscode and the proper breakpoint.

To contrast, in the broken example package.json:

https://github.com/eostermueller/angularFlatTreeExample02/blob/main/package.json

...I had to add the --open parameter to get the browser to open.  So perhaps this is part of the problem, I sure don't know.

In related news, I spent a lot of time looking at vscode trace output (with a different angular project) looking for issues on my side setting sourceMap to true.  I created a vscode issue on github here: https://github.com/microsoft/vscode-js-debug/issues/1178 but it didn't go anywhere :-(.

Followup

Feb 6 / 2:20pm CST.
I just copied the package.json to the broken project and ran "npm install --force".  Didn't help.  The debugging/breakpoints still don't work, and the browser does not launch as it does in the working project.
So this resolved the minor angular version differences mentioned above as well as as insuring both working/broken use  "start": "ng serve", ...and it's debugging/breakpoints still don't work.

答:
Finally figured it out.  kdiff3 pointed out that the broken example was missing .vscode/tasks.json file.  Here is the file from the working version:

https://github.com/eostermueller/angularFlatTreeExample01/blob/main/.vscode/tasks.json

I copied it into place on the broken example and it worked fine!! ....crazy that vscode didn't display any errors complaining about missing/unresolved tasks.  This file was created auto-magically for me in the working example, and I don't remember deleting this in the broken example.

Perhaps older versions of vscode didn't create this?

I created this vscode enhancement request

https://github.com/microsoft/vscode-js-debug/issues/1194

...to get an error message when tasks.json is missing or launch.json references some non-existent task.

Body:
I could use some help finding out what specifically is keeping vscode debug/breakpoints from working in this small angular 13 project:

https://github.com/eostermueller/angularFlatTreeExample02

The README.md has instructions on how to reproduce the issue.
There isn't much code there -- so it's particularly frustrating that such a trivial example isn't working.

So I recreated the project from scratch:

https://github.com/eostermueller/angularFlatTreeExample01

...and lo and behold, debug/breakpoints are working just fine!

The tsconfig.json files are identical:

https://github.com/eostermueller/angularFlatTreeExample01/blob/main/tsconfig.json
https://github.com/eostermueller/angularFlatTreeExample02/blob/main/tsconfig.json

and vscode launch.json files are pretty similar:

https://github.com/eostermueller/angularFlatTreeExample01/blob/main/.vscode/launch.json
https://github.com/eostermueller/angularFlatTreeExample02/blob/main/.vscode/launch.json

There are a number of small angular version differences inside the package.json files.  The broken one has 13.0-ish dependencies and the working one has 13.1-ish.

Also interesting (and ironic) is that in the working example, we have this in package.json:
https://github.com/eostermueller/angularFlatTreeExample01/blob/main/package.json

{
  "name": "flat-tree-example-with-debugging",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",

...and note that '--open' parameter that launches the browser is absent from the last line, yet when I run the browser actually opens, displays the page and then focus moves to vscode and the proper breakpoint.

To contrast, in the broken example package.json:

https://github.com/eostermueller/angularFlatTreeExample02/blob/main/package.json

...I had to add the --open parameter to get the browser to open.  So perhaps this is part of the problem, I sure don't know.

In related news, I spent a lot of time looking at vscode trace output (with a different angular project) looking for issues on my side setting sourceMap to true.  I created a vscode issue on github here: https://github.com/microsoft/vscode-js-debug/issues/1178 but it didn't go anywhere :-(.

Followup

Feb 6 / 2:20pm CST.
I just copied the package.json to the broken project and ran "npm install --force".  Didn't help.  The debugging/breakpoints still don't work, and the browser does not launch as it does in the working project.
So this resolved the minor angular version differences mentioned above as well as as insuring both working/broken use  "start": "ng serve", ...and it's debugging/breakpoints still don't work.


问:
Enabling forced choice in jsPsychSurveyLikert
I am new to jsPsych and wonder if there is a way to enable forced choice in the jsPsychSurveyLikert in 7.1.2. I want to avoid missing data and therefore I would like to specify this. For example for jsPsychMultiChoice it is possible to do this by setting required to true.

Here is a reproducible example:

```<code>var trial = {
    type: jsPsychSurveyLikert,
    required: true,
    questions: [
        {prompt: '"Do you cook?"', labels: ["Yes","No"]}
    ]
}
</code>```

Thank you very much for helping me!

答:
You can set the required parameter inside the questions, like this:

var trial = {
    type: jsPsychSurveyLikert,
    questions: [
        {prompt: '"Do you cook?"', labels: ["Yes","No"], required: true}
    ]
}
```

This allows you to make some questions required and others optional.

Body:
I am new to jsPsych and wonder if there is a way to enable forced choice in the jsPsychSurveyLikert in 7.1.2. I want to avoid missing data and therefore I would like to specify this. For example for jsPsychMultiChoice it is possible to do this by setting required to true.

Here is a reproducible example:

var trial = {
    type: jsPsychSurveyLikert,
    required: true,
    questions: [
        {prompt: '"Do you cook?"', labels: ["Yes","No"]}
    ]
}

Thank you very much for helping me!

Body:
You can set the required parameter inside the questions, like this:

var trial = {
    type: jsPsychSurveyLikert,
    questions: [
        {prompt: '"Do you cook?"', labels: ["Yes","No"], required: true}
    ]
}

This allows you to make some questions required and others optional.


问:
CNN program has been computing for too long and not giving any output
I've implemented the following code in Jupyter notebook, and it has been over 90 mins, the programme is still running, and I've not gotten any output.

I'm working with mid-2012 MacBook Pro.
4 GB ram.
I've checked the activity monitor, memory pressure is in the yellow zone, so that means, the means, the mac is not running out of memory, and I don't know what to do now.

The program implements CNN model over CIFAR-10 dataset.

```<code>import sys
from matplotlib import pyplot
from keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Dense
from keras.layers import Flatten
from tensorflow.keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dropout
from keras.layers import BatchNormalization
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

# load train and test dataset
def load_dataset():
    # load dataset
    (trainX, trainY), (testX, testY) = cifar10.load_data()
    # one hot encode target values
    trainY = to_categorical(trainY)
    testY = to_categorical(testY)
    return trainX, trainY, testX, testY

# scale pixels
def prep_pixels(train, test):
    # convert from integers to floats
    train_norm = train.astype('float32')
    test_norm = test.astype('float32')
    # normalize to range 0-1
    train_norm = train_norm / 255.0
    test_norm = test_norm / 255.0
    # return normalized images
    return train_norm, test_norm

# define cnn model
def define_model():
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(32, 32, 3)))
    model.add(BatchNormalization())
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.2))
    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.3))
    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.4))
    model.add(Flatten())
    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))
    model.add(BatchNormalization())
    model.add(Dropout(0.5))
    model.add(Dense(10, activation='softmax'))
    # compile model
    opt = SGD(lr=0.001, momentum=0.9)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

# plot diagnostic learning curves
def summarize_diagnostics(history):
    # plot loss
    pyplot.subplot(211)
    pyplot.title('Cross Entropy Loss')
    pyplot.plot(history.history['loss'], color='blue', label='train')
    pyplot.plot(history.history['val_loss'], color='orange', label='test')
    # plot accuracy
    pyplot.subplot(212)
    pyplot.title('Classification Accuracy')
    pyplot.plot(history.history['accuracy'], color='blue', label='train')
    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')
    # save plot to file
    filename = sys.argv[0].split('/')[-1]
    pyplot.savefig(filename + '_plot.png')
    pyplot.close()

# run the test harness for evaluating a model
def run_test_harness():
    # load dataset
    trainX, trainY, testX, testY = load_dataset()
    # prepare pixel data
    trainX, testX = prep_pixels(trainX, testX)
    # define model
    model = define_model()
    # create data generator
    datagen = ImageDataGenerator(width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)
    # prepare iterator
    it_train = datagen.flow(trainX, trainY, batch_size=64)
    # fit model
    steps = int(trainX.shape[0] / 64)
    history = model.fit_generator(it_train, steps_per_epoch=steps, epochs=100, validation_data=(testX, testY), verbose=0)
    # evaluate model
    _, acc = model.evaluate(testX, testY, verbose=0)
    print('> %.3f' % (acc * 100.0))
    # learning curves
    summarize_diagnostics(history)

# entry point, run the test harness
run_test_harness()```

```

答:
The reason your model is taking so long to train is because:

You are training a large model with many layers for 100 epochs

You are using a relatively low performance computer (from what I found googling it only has a 2.5 GHZ processor.)

You can make it train faster by using an a free cloud environment that has GPUs and TPUs like Google Colab (https://colab.research.google.com/), or even better a Kaggle notebook which allows you to train for longer periods of time. If you want to run it on your mac you could try making the model smaller or decreasing the number of epochs you are training for.

It should be easy to port your notebook to a Google Colab or Kaggle notebook. You will need to create a google account for Google Colab or a seperate account for Kaggle.

Hope this helped!

Body:
I've implemented the following code in Jupyter notebook, and it has been over 90 mins, the programme is still running, and I've not gotten any output.

I'm working with mid-2012 MacBook Pro.
4 GB ram.
I've checked the activity monitor, memory pressure is in the yellow zone, so that means, the means, the mac is not running out of memory, and I don't know what to do now.

The program implements CNN model over CIFAR-10 dataset.

import sys
from matplotlib import pyplot
from keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Dense
from keras.layers import Flatten
from tensorflow.keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dropout
from keras.layers import BatchNormalization
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

# load train and test dataset
def load_dataset():
    # load dataset
    (trainX, trainY), (testX, testY) = cifar10.load_data()
    # one hot encode target values
    trainY = to_categorical(trainY)
    testY = to_categorical(testY)
    return trainX, trainY, testX, testY

# scale pixels
def prep_pixels(train, test):
    # convert from integers to floats
    train_norm = train.astype('float32')
    test_norm = test.astype('float32')
    # normalize to range 0-1
    train_norm = train_norm / 255.0
    test_norm = test_norm / 255.0
    # return normalized images
    return train_norm, test_norm

# define cnn model
def define_model():
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(32, 32, 3)))
    model.add(BatchNormalization())
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.2))
    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.3))
    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.4))
    model.add(Flatten())
    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))
    model.add(BatchNormalization())
    model.add(Dropout(0.5))
    model.add(Dense(10, activation='softmax'))
    # compile model
    opt = SGD(lr=0.001, momentum=0.9)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

# plot diagnostic learning curves
def summarize_diagnostics(history):
    # plot loss
    pyplot.subplot(211)
    pyplot.title('Cross Entropy Loss')
    pyplot.plot(history.history['loss'], color='blue', label='train')
    pyplot.plot(history.history['val_loss'], color='orange', label='test')
    # plot accuracy
    pyplot.subplot(212)
    pyplot.title('Classification Accuracy')
    pyplot.plot(history.history['accuracy'], color='blue', label='train')
    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')
    # save plot to file
    filename = sys.argv[0].split('/')[-1]
    pyplot.savefig(filename + '_plot.png')
    pyplot.close()

# run the test harness for evaluating a model
def run_test_harness():
    # load dataset
    trainX, trainY, testX, testY = load_dataset()
    # prepare pixel data
    trainX, testX = prep_pixels(trainX, testX)
    # define model
    model = define_model()
    # create data generator
    datagen = ImageDataGenerator(width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)
    # prepare iterator
    it_train = datagen.flow(trainX, trainY, batch_size=64)
    # fit model
    steps = int(trainX.shape[0] / 64)
    history = model.fit_generator(it_train, steps_per_epoch=steps, epochs=100, validation_data=(testX, testY), verbose=0)
    # evaluate model
    _, acc = model.evaluate(testX, testY, verbose=0)
    print('> %.3f' % (acc * 100.0))
    # learning curves
    summarize_diagnostics(history)

# entry point, run the test harness
run_test_harness()```


答: You can convert the tuples to strings by str(tuple) function and count each of them using dictionary.

Title: Can I count identical tuples of strings in my list?

Body:
I have generated a list of tuples from a separate code to show which pairs of numbers converge (in certain equations) given different combinations of variables. I need a way to count how many of each sequence or tuple there are here in my list.  Because of the way I generated the variables to begin with, the tuples are strings.

If ('1','3') is in the list 8 times, I would want to be able to return ('1''3') and the count.

converge_list=[('1', '3'), ('1', '7'), ('2', '6'), ('3', '5'), ('7', '9'), ('1', '3'), ('1', '7'), ('2', '6'), ('3', '5'), ('7', '9'), ('1', '3'), ('1', '7'), ('1', '9'), ('2', '6'), ('3', '9'), ('5', '9'), ('1', '3'), ('1', '7'), ('2', '6'), ('3', '5'), ('7', '9'), ('1', '3'), ('1', '5'), ('1', '7'), ('2', '6'), ('3', '5'), ('3', '9'), ('1', '3'), ('1', '7'), ('1', '9'), ('2', '6'), ('3', '9'), ('5', '9'), ('1', '3'), ('1', '7'), ('2', '6'), ('3', '7'), ('1', '3'), ('1', '7'), ('2', '6'), ('3', '5'), ('3', '9'), ('7', '9'), ('1', '3'), ('1', '7'), ('1', '9'), ('2', '6'), ('3', '5'), ('3', '9'), ('7', '9'), ('1', '3'), ('1', '5'), ('1', '7'), ('2', '6'), ('3', '5'), ('3', '9')]


问:
Plotting different columns in same R graph
I guess this question is rather simple but I have a dataframe with 3 columns (A, B and C). A is the name, B has a numeric value, and C is also has a numeric value. The values of each B and C relate to the correspondent line in A

I need to plot a bar graph that allows to observe for each A, the B bar and the C bar next to each other.

Thanks a lot!

答:
Here is an example with ggplot2 that you could work on:

```<code># creating the dataframe
A <- c("First", "Second", "Third", "Fourth")
B <- c(44, 54, 32, 45)
C <- c(23, 12, 45, 34)

df <- data.frame(A, B, C)

# creating the plot with ggplot2

library(tidyverse)

df %>%
  mutate(A = as_factor(A)) %>%
  pivot_longer(
    cols=-A,
    names_to = "Numeric value",
    values_to = "value"
  ) %>%
  ggplot(aes(x=A, y=value, fill=`Numeric value`))+
  geom_col(position = position_dodge())
</code>```

Body:
Here is an example with ggplot2 that you could work on:

# creating the dataframe
A <- c("First", "Second", "Third", "Fourth")
B <- c(44, 54, 32, 45)
C <- c(23, 12, 45, 34)

df <- data.frame(A, B, C)

# creating the plot with ggplot2

library(tidyverse)

df %>%
  mutate(A = as_factor(A)) %>%
  pivot_longer(
    cols=-A,
    names_to = "Numeric value",
    values_to = "value"
  ) %>%
  ggplot(aes(x=A, y=value, fill=`Numeric value`))+
  geom_col(position = position_dodge())


问:
JS: using object from parent class
I am having two classes and want to have an Object with values that are available for both classes. This is my sample code:

class Class1 {

  constructor() {
   this.things = [];
   this.testValue = "one two three";
  }

  doThings() {

        for(let i = 0; i < 10; i++) {
            this.things[i] = "test "+i;
        }

    console.log("Class 1 doThings(): ", this.things);

  }

  getContent() {
      console.log("getContent Class1: ", this.things);
  }

}

class Class2 extends Class1 {

  constructor(elmnt){
    super();
  }

  getContent() {
      console.log("Class 2 getContent(): ", this.things);
  }

  getValue() {

    console.log("Value: ", this.testValue)

  }

}

let handle1 = new Class1();
let handle2 = new Class2();

handle1.getContent(); // empty because this.things() did not run
handle1.doThings(); // create things...
handle1.getContent(); // this shows the things

handle2.getContent(); // this is empty even is doThings() is called before to produce things...

handle2.getValue();```

Why is handle2.getContent() not showing the Things-Array? And (more important) what would be right?

i think the super() overrides the this.things... Is that true? how could i prevent this?

答:
Just because you ran doThings() in handle1, doesn't mean doThings() was run in handle2.
For you to get the output you want, you need to run doThings() in handle2

class Class1 {

  constructor() {
   this.things = [];
   this.testValue = "one two three";
  }

  doThings() {

        for(let i = 0; i < 10; i++) {
            this.things[i] = "test "+i;
        }

    console.log("Class 1 doThings(): ", this.things);

  }

  getContent() {
      console.log("getContent Class1: ", this.things);
  }

}

class Class2 extends Class1 {

  constructor(elmnt){
    super();
  }

  getContent() {
      console.log("Class 2 getContent(): ", this.things);
  }

  getValue() {

    console.log("Value: ", this.testValue)

  }

}

let handle1 = new Class1();
let handle2 = new Class2();

handle1.getContent(); // empty because this.things() did not run
handle1.doThings(); // create things...
handle1.getContent(); // this shows the things

handle2.doThings() // This needs to run

handle2.getContent(); // this is empty even is doThings() is called before to produce things...

handle2.getValue();```

Title: JS: using object from parent class

Body:
I am having two classes and want to have an Object with values that are available for both classes. This is my sample code:

class Class1 {

  constructor() {
   this.things = [];
   this.testValue = "one two three";
  }

  doThings() {

        for(let i = 0; i < 10; i++) {
            this.things[i] = "test "+i;
        }

    console.log("Class 1 doThings(): ", this.things);

  }

  getContent() {
      console.log("getContent Class1: ", this.things);
  }

}

class Class2 extends Class1 {

  constructor(elmnt){
    super();
  }

  getContent() {
      console.log("Class 2 getContent(): ", this.things);
  }

  getValue() {

    console.log("Value: ", this.testValue)

  }

}

let handle1 = new Class1();
let handle2 = new Class2();

handle1.getContent(); // empty because this.things() did not run
handle1.doThings(); // create things...
handle1.getContent(); // this shows the things

handle2.getContent(); // this is empty even is doThings() is called before to produce things...

handle2.getValue();

Why is handle2.getContent() not showing the Things-Array? And (more important) what would be right?

i think the super() overrides the this.things... Is that true? how could i prevent this?