问:
AttributeError - 'Div' object has no attribute 'set_index'
I am trying to run this code:

```<code>def parse_data(contents, filename):
    content_type, content_string = contents.split(',')

    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
            # Assume that the user uploaded a CSV or TXT file
            df = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            # Assume that the user uploaded an excel file
            df = pd.read_excel(io.BytesIO(decoded))
        elif 'txt' or 'tsv' in filename:
            # Assume that the user upl, delimiter = r'\s+'oaded an excel file
            df = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')), delimiter = r'\s+')
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])

    return df

def update_graph(contents, filename):
    fig = {
        'layout': go.Layout(
            plot_bgcolor=colors["graphBackground"],
            paper_bgcolor=colors["graphBackground"])
    }

    if contents:
        contents = contents[0]
        filename = filename[0]
        df = parse_data(contents, filename)
        df = df.set_index(df.columns[0])
        fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1)

    return fig
</code>```

And get this error:

```<code>Traceback (most recent call last):
  File "/Users/.../PycharmProjects/pythonProject2/main.py", line 93, in update_graph
    df = df.set_index(df.columns[0])
AttributeError: 'Div' object has no attribute 'set_index'
</code>```

Any ideas what might be wrong? Thanks a lot!

答:
All problem is with your parse_data(). If it can't read file then it runs return html.Div() so running df = parse_data() means df = html.Div() and later you don't check if you really get data in df and df.set_index() means html.Div().set_index().

Maybe better use return None and check this after df = parse_data()

```<code>def parse_data(contents, filename):
    # ... code ...

    try:

       # ... code ...

    except Exception as e:
        print(e)
        return None

    return df
</code>```

and later

```<code>    df = parse_data(contents, filename)

    if df is None:
        html.Div(['There was an error processing this file.'])
    else:
        df = df.set_index(df.columns[0])
        fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1)
</code>```

But this still can have problem with fig['data'] when it can't read file.

I can't test your code but maybe it should do assign Div to fig['data']

```<code>if df is None:
    fig['data'] = html.Div(['There was an error processing this file.'])
else:
    df = df.set_index(df.columns[0])
    fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1)
</code>```

Body:
I am trying to run this code:

def parse_data(contents, filename):
    content_type, content_string = contents.split(',')

    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
            # Assume that the user uploaded a CSV or TXT file
            df = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            # Assume that the user uploaded an excel file
            df = pd.read_excel(io.BytesIO(decoded))
        elif 'txt' or 'tsv' in filename:
            # Assume that the user upl, delimiter = r'\s+'oaded an excel file
            df = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')), delimiter = r'\s+')
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])

    return df

def update_graph(contents, filename):
    fig = {
        'layout': go.Layout(
            plot_bgcolor=colors["graphBackground"],
            paper_bgcolor=colors["graphBackground"])
    }

    if contents:
        contents = contents[0]
        filename = filename[0]
        df = parse_data(contents, filename)
        df = df.set_index(df.columns[0])
        fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1)

    return fig

And get this error:

Traceback (most recent call last):
  File "/Users/.../PycharmProjects/pythonProject2/main.py", line 93, in update_graph
    df = df.set_index(df.columns[0])
AttributeError: 'Div' object has no attribute 'set_index'

Any ideas what might be wrong? Thanks a lot!

Body:
All problem is with your parse_data(). If it can't read file then it runs return html.Div() so running df = parse_data() means df = html.Div() and later you don't check if you really get data in df and df.set_index() means html.Div().set_index().

Maybe better use return None and check this after df = parse_data()

def parse_data(contents, filename):
    # ... code ...

    try:

       # ... code ...

    except Exception as e:
        print(e)
        return None

    return df

and later

    df = parse_data(contents, filename)

    if df is None:
        html.Div(['There was an error processing this file.'])
    else:
        df = df.set_index(df.columns[0])
        fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1)

But this still can have problem with fig['data'] when it can't read file.

I can't test your code but maybe it should do assign Div to fig['data']

if df is None:
    fig['data'] = html.Div(['There was an error processing this file.'])
else:
    df = df.set_index(df.columns[0])
    fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1)


来源: stackexchange

问:
Moving logic from Django views to models
This is my model:

```<code>class Car(models.Model):
    make = models.CharField(max_length=30)
    model = models.CharField(max_length=30)
    rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], default=0, blank=True)
    avg_rating = models.FloatField(default=0, blank=True)
    rates_number = models.IntegerField(default=0, blank=True)

    def __str__(self):
        return self.make + ' ' + self.model
</code>```

What's the best way to move the logic from the following perform_create function (in views.py) to my models?

```<code>class CarRate(generics.CreateAPIView):
    serializer_class = CarRatingSerializer
    queryset = Car.objects.all()

    def perform_create(self, serializer):
        pk = serializer.validated_data['car_id']
        rating = serializer.validated_data['rating']
        queryset = Car.objects.all()
        car_queryset = get_object_or_404(queryset, pk=pk)

        if car_queryset.rates_number == 0:
            car_queryset.avg_rating = rating
        else:
            car_queryset.avg_rating = (car_queryset.avg_rating + rating)/2
            car_queryset.avg_rating = round(car_queryset.avg_rating, 1)

        car_queryset.rates_number = car_queryset.rates_number + 1
        car_queryset.save()
</code>```

答:
It would be much better to create two models. Think about how you are counting average rating. This would be some better idea for now:</p>
```<code>class Car(models.Model):
    make = models.CharField(max_length=30)
    model = models.CharField(max_length=30)

    def rates_number(self):
        return self.rates.all().count()

    def avg_rating(self):
        # count average_rating from relation to Rate objects and return it
        return average_rating

class CarRate(models.Model):
    value = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], default=0, blank=True)
    car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='rates')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is my model:

class Car(models.Model):
    make = models.CharField(max_length=30)
    model = models.CharField(max_length=30)
    rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], default=0, blank=True)
    avg_rating = models.FloatField(default=0, blank=True)
    rates_number = models.IntegerField(default=0, blank=True)

    def __str__(self):
        return self.make + ' ' + self.model

What's the best way to move the logic from the following perform_create function (in views.py) to my models?

class CarRate(generics.CreateAPIView):
    serializer_class = CarRatingSerializer
    queryset = Car.objects.all()

    def perform_create(self, serializer):
        pk = serializer.validated_data['car_id']
        rating = serializer.validated_data['rating']
        queryset = Car.objects.all()
        car_queryset = get_object_or_404(queryset, pk=pk)

        if car_queryset.rates_number == 0:
            car_queryset.avg_rating = rating
        else:
            car_queryset.avg_rating = (car_queryset.avg_rating + rating)/2
            car_queryset.avg_rating = round(car_queryset.avg_rating, 1)

        car_queryset.rates_number = car_queryset.rates_number + 1
        car_queryset.save()

Body:
It would be much better to create two models. Think about how you are counting average rating. This would be some better idea for now:

class Car(models.Model):
    make = models.CharField(max_length=30)
    model = models.CharField(max_length=30)

    def rates_number(self):
        return self.rates.all().count()

    def avg_rating(self):
        # count average_rating from relation to Rate objects and return it
        return average_rating

class CarRate(models.Model):
    value = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], default=0, blank=True)
    car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='rates')


问:
Insert data into sqlite db with Go Fiber / Gorm
Hello I'm using Go Fiber together with gorm sqlite. I was wondering if there is a way to pre load data into the database with a sql script?

I know that in Spring Boot it is possible to create a data.sql file to preload data. Is there a same way to accomplish that for go fiber / gorm sqlite?

答:
You could read the sql file and execute the raw query in Gorm, and you could execute this before booting up the server.</p>
```<code>path := filepath.Join("path", "to", "script.sql")

c, ioErr := ioutil.ReadFile(path)
if ioErr != nil {
     // handle error.
}

sql := string(c)

// gorm *DB
err := db.Exec(sql).Error
if err != nil {
    // handle error
}
</code>```

Body:
You could read the sql file and execute the raw query in Gorm, and you could execute this before booting up the server.

path := filepath.Join("path", "to", "script.sql")

c, ioErr := ioutil.ReadFile(path)
if ioErr != nil {
     // handle error.
}

sql := string(c)

// gorm *DB
err := db.Exec(sql).Error
if err != nil {
    // handle error
}


问:
Query result from array string with numbers to array string text?
I have two SQL Server tables.

First table: Product

Id
Title
Tags

1
P1583
2,5

2
P1234
1,3

3
P1456
1

Second table - Tag:

Id
Title

1
Pants

2
Shorts

3
Shirts

4
Tshirts

5
Skirts

I want this result

ProductId
Title
TagName

1
P1583
Short,Skirts

2
P1234
Pants,Shirts

3
P1456
Pants

How can I write the query?

```<code>SELECT
    P.Id AS ProductId,
    P.Title AS Title,
    ????
FROM
    Product P
LEFT JOIN
    Tag T ON T.Id = P.Tags  --- (this is not working)
</code>```

答:
An alternative way to do the split and re-aggregate is a modification of @FlexYourData's excellent answer:

SELECT
  p.Id,
  p.Title,
  tags.TagName
FROM Product p
CROSS APPLY (
    SELECT
        TagName = STRING_AGG(t.Title, ',')
    FROM STRING_SPLIT(p.Tags, ',') tags
    INNER JOIN Tag t ON tags.value = t.id
) tags;
```
<hr />
<p>Ideally, you should normalize your schema and create a separate join table:</p>
```CREATE TABLE ProductTag (
    ProductId REFERENCES Product (Id),
    TagId REFERENCES Tag (Id)
);
```
<pre class="lang-sql prettyprint-override"><code>INSERT ProductTag (ProductId, TagId)
SELECT
  p.Id,
  tags.value
FROM Product p
CROSS APPLY STRING_SPLIT(p.Tags, ',') tags;
</code>```

Then your query becomes:

SELECT
  p.Id,
  p.Title,
  tags.TagName
FROM Product p
CROSS APPLY (
    SELECT
        TagName = STRING_AGG(t.Title, ',')
    FROM ProductTags pt
    INNER JOIN Tag t ON pt.TagId = t.id
    WHERE pt.ProductId = p.Id
) tags;
```

Body:
I have two SQL Server tables.

First table: Product

Id
Title
Tags

1
P1583
2,5

2
P1234
1,3

3
P1456
1

Second table - Tag:

Id
Title

1
Pants

2
Shorts

3
Shirts

4
Tshirts

5
Skirts

I want this result

ProductId
Title
TagName

1
P1583
Short,Skirts

2
P1234
Pants,Shirts

3
P1456
Pants

How can I write the query?

SELECT
    P.Id AS ProductId,
    P.Title AS Title,
    ????
FROM
    Product P
LEFT JOIN
    Tag T ON T.Id = P.Tags  --- (this is not working)

Body:
An alternative way to do the split and re-aggregate is a modification of @FlexYourData's excellent answer:

SELECT
  p.Id,
  p.Title,
  tags.TagName
FROM Product p
CROSS APPLY (
    SELECT
        TagName = STRING_AGG(t.Title, ',')
    FROM STRING_SPLIT(p.Tags, ',') tags
    INNER JOIN Tag t ON tags.value = t.id
) tags;

Ideally, you should normalize your schema and create a separate join table:

CREATE TABLE ProductTag (
    ProductId REFERENCES Product (Id),
    TagId REFERENCES Tag (Id)
);

INSERT ProductTag (ProductId, TagId)
SELECT
  p.Id,
  tags.value
FROM Product p
CROSS APPLY STRING_SPLIT(p.Tags, ',') tags;

Then your query becomes:

SELECT
  p.Id,
  p.Title,
  tags.TagName
FROM Product p
CROSS APPLY (
    SELECT
        TagName = STRING_AGG(t.Title, ',')
    FROM ProductTags pt
    INNER JOIN Tag t ON pt.TagId = t.id
    WHERE pt.ProductId = p.Id
) tags;


问:
MySQL query with UUID's really slow
I have the following query example:

```<code>SELECT tableA.*, tableB.*, tableA.uuid as tableAuuid
FROM tableA, tableB
WHERE tableA.userUUID =
      '51ce8ea9533da73640d84324731d67014e077fc8536ssdsdsdsdwqz79603'
  AND tableB.uuid = tableA.tableBUUID
ORDER BY Date ASC, depTime ASC
LIMIT 194, 18
</code>```

Recently I have added uuid's essantially as a 'secondary' key due to allow offline functionality and sync.

Currenty the UUID's are just stored as a random string in a varchar field

The above query is really slow like takes around 10 seconds. But the original query which is

```<code>tableB.id=tableA.tableBId
</code>```

which are auto inc primary keys are really fast.

I am wondering how to make the queries with UUID's faster

答:
When you search by UUID, you are filtering the data and the engine needs to find the rows you want only, not any rows of the table(s).

In this case the query can benefit from the index:

```<code>create index ix1 on tableA (userUUID, tableBUUID);
</code>```

Title: MySQL query with UUID's really slow

Body:
I have the following query example:

SELECT tableA.*, tableB.*, tableA.uuid as tableAuuid
FROM tableA, tableB
WHERE tableA.userUUID =
      '51ce8ea9533da73640d84324731d67014e077fc8536ssdsdsdsdwqz79603'
  AND tableB.uuid = tableA.tableBUUID
ORDER BY Date ASC, depTime ASC
LIMIT 194, 18

Recently I have added uuid's essantially as a 'secondary' key due to allow offline functionality and sync.

Currenty the UUID's are just stored as a random string in a varchar field

The above query is really slow like takes around 10 seconds. But the original query which is

tableB.id=tableA.tableBId

which are auto inc primary keys are really fast.

I am wondering how to make the queries with UUID's faster

Body:
When you search by UUID, you are filtering the data and the engine needs to find the rows you want only, not any rows of the table(s).

In this case the query can benefit from the index:

create index ix1 on tableA (userUUID, tableBUUID);


问:
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>```

答:
I think this is what you are looking for, assuming you are working with .csv files based on the data that you posted.

Basically  you can just parse the files as JSON and then you can manipulate them easily.

```<code>import csv
import json
gender_data = []
full_data = []

with open("stack/new.csv", encoding="utf-8") as csvf:
    csvReader = csv.DictReader(csvf)
    for row in csvReader:
        gender_data.append(row)
with open("stack/info.csv", encoding="utf-8") as csvf:
    csvReader = csv.DictReader(csvf)
    for row in csvReader:
        full_data.append(row)

for x in gender_data:
    for y in full_data:
        if x["SUBJECT_ID"] == y["SUBJECT_ID"]:
            y["SEX"] = x["SEX"]

f = csv.writer(open("stack/test.csv", "w+"))

f.writerow(["SUBJECT_ID", "YEAR_1", "YEAR_2", "YEAR_3", "SEX"])

for x in full_data:
    f.writerow(
        [
            x["SUBJECT_ID"],
            x["YEAR_1"],
            x["YEAR_2"],
            x["YEAR_3"],
            x["SEX"] if "SEX" in x else "",
        ]
    )
</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:
I think this is what you are looking for, assuming you are working with .csv files based on the data that you posted.

Basically  you can just parse the files as JSON and then you can manipulate them easily.

import csv
import json
gender_data = []
full_data = []

with open("stack/new.csv", encoding="utf-8") as csvf:
    csvReader = csv.DictReader(csvf)
    for row in csvReader:
        gender_data.append(row)
with open("stack/info.csv", encoding="utf-8") as csvf:
    csvReader = csv.DictReader(csvf)
    for row in csvReader:
        full_data.append(row)

for x in gender_data:
    for y in full_data:
        if x["SUBJECT_ID"] == y["SUBJECT_ID"]:
            y["SEX"] = x["SEX"]

f = csv.writer(open("stack/test.csv", "w+"))

f.writerow(["SUBJECT_ID", "YEAR_1", "YEAR_2", "YEAR_3", "SEX"])

for x in full_data:
    f.writerow(
        [
            x["SUBJECT_ID"],
            x["YEAR_1"],
            x["YEAR_2"],
            x["YEAR_3"],
            x["SEX"] if "SEX" in x else "",
        ]
    )


问:
"SyntaxError: Unexpected token {": Babel/ Webpack/ES6 import statement not compiling
I've already viewed this link, and I've ready many threads about different configurations for . babelrc, .eslintrc, webpack.config.js, and none of them apply to my situtation so far.

Basically, I have this code:

```<code>// referencing this function
// // @flow
// export const PressurePsiToPa = (value: number): number => {
//     return value * 6894.757;
// };
// should also mention that import * ... raises the same error.
import {pressurePsiToPA} from './helpers/unit-converter.js';

console.log(pressurePsiToPA(70.4));

...

ERROR:

import {pressurePsiToPA} from './helpers/unit-converter.js';
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:721:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
</code>```

I've thought it was some stuff with vscode, since I already had to disable TypeScript and JavaScript Language Features in order for something else to work, but I don't see anything on SO or even an entry for babel or webpack in settings.json. It could be an issue with having things as node_modules and also installed as extensions, but as a safe assumption I've just had both at all times because things got hairy for me and it seems to work the way I want it (at least between eslint and flow).

Please help, I'm at a loss.

Relevant files:

Snippet of package.json

```<code> "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/plugin-proposal-class-properties": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "@babel/preset-flow": "^7.0.0",
    "@babel/register": "^7.5.5",
    "babel-cli": "^6.26.0",
    "babel-eslint": "^10.0.2",
    "babel-loader": "^8.0.6",
    "babel-minify-webpack-plugin": "^0.3.1",
    "babel-preset-flow": "^6.23.0",
    "eslint": "^5.16.0",
    "eslint-config-prettier": "^4.3.0",
    "eslint-loader": "^2.2.1",
    "eslint-plugin-flowtype": "^3.13.0",
    "eslint-plugin-flowtype-errors": "^4.1.0",
    "eslint-plugin-node": "^8.0.1",
    "eslint-plugin-prettier": "^3.1.0",
    "flow-bin": "^0.95.1",
    "webpack": "^4.39.1",
    "webpack-cli": "^3.3.6",
    "webpack-merge": "^4.2.1"
  }
</code>```

.babelrc

```<code>{
  "presets": ["@babel/preset-env", "@babel/preset-flow"],
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

</code>```

.eslintrc

```<code>{
  "root": true,
  "extends": ["eslint:recommended", "plugin:flowtype/recommended"],
  "env": {
    "node": true,
    "es6": true,
    "browser": false
  },
  "plugins": ["flowtype-errors", "flowtype"],
  "parser": "babel-eslint",
  "rules": {
    "flowtype-errors/show-errors": "error",
    "flowtype-errors/show-warnings": "warn",
    "no-console": "off"
  },
  "settings": {}
}

</code>```

webpack.common.js

```<code>const path = require("path");

const CleanWebpackPlugin = require("clean-webpack-plugin");
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");

const smp = new SpeedMeasurePlugin();

module.exports = smp.wrap({
  target: "node",
  entry: "./src/index.js",
  output: {
    filename: "xxx.js",
    path: path.join(__dirname, "dist"),
  },
  plugins: [new CleanWebpackPlugin()],
  module: {
    rules: [
      {
        test: /\.(js)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "eslint-loader",
          options: { failOnError: true },
        },
      },
      {
        test: [
          /node_modules[/\\]mqtt[/\\]mqtt.js/,
          /node_modules[/\\]mqtt[/\\]bin[/\\]sub.js/,
          /node_modules[/\\]mqtt[/\\]bin[/\\]pub.js/,
        ],
        loader: "shebang-loader",
      },
    ],
  },
});

</code>```

答: I used to have a similar error. In my case it was enough updating the Node version.</p>

Body:
I've already viewed this link, and I've ready many threads about different configurations for . babelrc, .eslintrc, webpack.config.js, and none of them apply to my situtation so far.

Basically, I have this code:

// referencing this function
// // @flow
// export const PressurePsiToPa = (value: number): number => {
//     return value * 6894.757;
// };
// should also mention that import * ... raises the same error.
import {pressurePsiToPA} from './helpers/unit-converter.js';

console.log(pressurePsiToPA(70.4));

...

ERROR:

import {pressurePsiToPA} from './helpers/unit-converter.js';
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:721:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

I've thought it was some stuff with vscode, since I already had to disable TypeScript and JavaScript Language Features in order for something else to work, but I don't see anything on SO or even an entry for babel or webpack in settings.json. It could be an issue with having things as node_modules and also installed as extensions, but as a safe assumption I've just had both at all times because things got hairy for me and it seems to work the way I want it (at least between eslint and flow).

Please help, I'm at a loss.

Relevant files:

Snippet of package.json

 "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/plugin-proposal-class-properties": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "@babel/preset-flow": "^7.0.0",
    "@babel/register": "^7.5.5",
    "babel-cli": "^6.26.0",
    "babel-eslint": "^10.0.2",
    "babel-loader": "^8.0.6",
    "babel-minify-webpack-plugin": "^0.3.1",
    "babel-preset-flow": "^6.23.0",
    "eslint": "^5.16.0",
    "eslint-config-prettier": "^4.3.0",
    "eslint-loader": "^2.2.1",
    "eslint-plugin-flowtype": "^3.13.0",
    "eslint-plugin-flowtype-errors": "^4.1.0",
    "eslint-plugin-node": "^8.0.1",
    "eslint-plugin-prettier": "^3.1.0",
    "flow-bin": "^0.95.1",
    "webpack": "^4.39.1",
    "webpack-cli": "^3.3.6",
    "webpack-merge": "^4.2.1"
  }

.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-flow"],
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

.eslintrc

{
  "root": true,
  "extends": ["eslint:recommended", "plugin:flowtype/recommended"],
  "env": {
    "node": true,
    "es6": true,
    "browser": false
  },
  "plugins": ["flowtype-errors", "flowtype"],
  "parser": "babel-eslint",
  "rules": {
    "flowtype-errors/show-errors": "error",
    "flowtype-errors/show-warnings": "warn",
    "no-console": "off"
  },
  "settings": {}
}

webpack.common.js

const path = require("path");

const CleanWebpackPlugin = require("clean-webpack-plugin");
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");

const smp = new SpeedMeasurePlugin();

module.exports = smp.wrap({
  target: "node",
  entry: "./src/index.js",
  output: {
    filename: "xxx.js",
    path: path.join(__dirname, "dist"),
  },
  plugins: [new CleanWebpackPlugin()],
  module: {
    rules: [
      {
        test: /\.(js)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "eslint-loader",
          options: { failOnError: true },
        },
      },
      {
        test: [
          /node_modules[/\\]mqtt[/\\]mqtt.js/,
          /node_modules[/\\]mqtt[/\\]bin[/\\]sub.js/,
          /node_modules[/\\]mqtt[/\\]bin[/\\]pub.js/,
        ],
        loader: "shebang-loader",
      },
    ],
  },
});


问:
How do you stop processing when there's an error on the GRPC input stream?
Say I have a method

rpc saveFormData(stream SavedFormChunk) returns (stream SavedFormChunk) {}
```
<p>in the server implementation</p>
<pre class="lang-java prettyprint-override"><code>public StreamObserver<SavedFormChunk> saveFormData(StreamObserver<SavedFormChunk> responseObserver) {
  return new StreamObserver<>() {
    public void onNext(SavedFormChunk chunk) {
      // say chunk was in error what do I do to stop the processing?
    }
    ...
  }
}
</code>```

答:
It might be more clear to have types that indicate the direction in your service definition.

```<code>rpc saveFormData(stream SavedFormChunkRequest) returns (stream SavedFormChunkResponse) {}
</code>```

On your request StreamObserver where you are getting request data. Add this so that if the client sends you an error you will acknowledge with an observed onComplete.

```<code>@Override
public void onError(Throwable t) {
    responseObserver.onCompleted();
    log.error("During form processing, requestObserver called onError", t);
}
</code>```

To send an error back to the client. Do something like this.

```<code>responseObserver.onError(Status.INVALID_ARGUMENT.withDescription("The number being sent was out of range.")
                .augmentDescription("The number sent was:" + number).asRuntimeException());
</code>```

Body:
Say I have a method

rpc saveFormData(stream SavedFormChunk) returns (stream SavedFormChunk) {}

in the server implementation

public StreamObserver<SavedFormChunk> saveFormData(StreamObserver<SavedFormChunk> responseObserver) {
  return new StreamObserver<>() {
    public void onNext(SavedFormChunk chunk) {
      // say chunk was in error what do I do to stop the processing?
    }
    ...
  }
}

Body:
It might be more clear to have types that indicate the direction in your service definition.

rpc saveFormData(stream SavedFormChunkRequest) returns (stream SavedFormChunkResponse) {}

On your request StreamObserver where you are getting request data. Add this so that if the client sends you an error you will acknowledge with an observed onComplete.

@Override
public void onError(Throwable t) {
    responseObserver.onCompleted();
    log.error("During form processing, requestObserver called onError", t);
}

To send an error back to the client. Do something like this.

responseObserver.onError(Status.INVALID_ARGUMENT.withDescription("The number being sent was out of range.")
                .augmentDescription("The number sent was:" + number).asRuntimeException());


问:
How set default API definition url in openapi?
I want set default scheme by url /v3/api-docs/, but there are empty url and error "No API definition provided.".
Which settings properties I should use?

Current code in project:

application.properties

```<code>springdoc.swagger-ui.disable-swagger-default-url=true
springdoc.swagger-ui.use-root-path=true
</code>```

SwaggerConfig.java

```<code>@Configuration
public class SwaggerConfig {

@Bean
public GroupedOpenApi applicationApi() {
    String packagesToScan[] = {"ru.vetrf.ecert.web.application"};
    return GroupedOpenApi.builder()
            .group("application")
            .pathsToMatch("/rest-api/application/**")
            .packagesToScan(packagesToScan)
            .build();
}

@Bean
public OpenAPI eCertOpenAPI() {
    return new OpenAPI()
            .info(new Info().title("ECert API")
                    .description("ECert API")
                    .version("v1.0.0"))
            ;
}
</code>```

}

pom.xml

```<code>        <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.5.9</version>
        </dependency>
</code>```

答:
I had the same problem, and it worked for me this way

```<code>springdoc:
  swagger-ui:
    query-config-enabled: true
  api-docs:
    path: /my-service/v3/api-docs
</code>```

testing some properties, I found that this parameter does the magic :)

```<code>query-config-enabled: true
</code>```

Body:
I want set default scheme by url /v3/api-docs/, but there are empty url and error "No API definition provided.".
Which settings properties I should use?

Current code in project:

application.properties

springdoc.swagger-ui.disable-swagger-default-url=true
springdoc.swagger-ui.use-root-path=true

SwaggerConfig.java

@Configuration
public class SwaggerConfig {

@Bean
public GroupedOpenApi applicationApi() {
    String packagesToScan[] = {"ru.vetrf.ecert.web.application"};
    return GroupedOpenApi.builder()
            .group("application")
            .pathsToMatch("/rest-api/application/**")
            .packagesToScan(packagesToScan)
            .build();
}

@Bean
public OpenAPI eCertOpenAPI() {
    return new OpenAPI()
            .info(new Info().title("ECert API")
                    .description("ECert API")
                    .version("v1.0.0"))
            ;
}

}

pom.xml

        <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.5.9</version>
        </dependency>

Body:
I had the same problem, and it worked for me this way

springdoc:
  swagger-ui:
    query-config-enabled: true
  api-docs:
    path: /my-service/v3/api-docs

testing some properties, I found that this parameter does the magic :)

query-config-enabled: true


问:
Python/NumPy first occurrence of subarray
In Python or NumPy, what is the best way to find out the first occurrence of a subarray?

For example, I have

```<code>a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]
</code>```

What is the fastest way (run-time-wise) to find out where b occurs in a? I understand for strings this is extremely easy, but what about for a list or numpy ndarray?

Thanks a lot!

[EDITED] I prefer the numpy solution, since from my experience numpy vectorization is much faster than Python list comprehension. Meanwhile, the big array is huge, so I don't want to convert it into a string; that will be (too) long.

答:
you can call tostring() method to convert an array to string, and then you can use fast string search. this method maybe faster when you have many subarray to check.</p>

```<code>import numpy as np

a = np.array([1,2,3,4,5,6])
b = np.array([2,3,4])
print a.tostring().index(b.tostring())//a.itemsize
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In Python or NumPy, what is the best way to find out the first occurrence of a subarray?

For example, I have

a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]

What is the fastest way (run-time-wise) to find out where b occurs in a? I understand for strings this is extremely easy, but what about for a list or numpy ndarray?

Thanks a lot!

[EDITED] I prefer the numpy solution, since from my experience numpy vectorization is much faster than Python list comprehension. Meanwhile, the big array is huge, so I don't want to convert it into a string; that will be (too) long.

Body:
you can call tostring() method to convert an array to string, and then you can use fast string search. this method maybe faster when you have many subarray to check.

import numpy as np

a = np.array([1,2,3,4,5,6])
b = np.array([2,3,4])
print a.tostring().index(b.tostring())//a.itemsize


问:
Repeat a sequence of dates (sheet attached)? Would like to convert to colums (GOOGLE SHEETS)
Cell E2: Transposed sequence, 366 days of data points starting from 1/31/22.

I have a model with 366 days of sales forecasts for 200 SKUs.

I would like this sequence to repeat in a column "X" number of times per the value in cell B3, so in this case, 200 times. How do I accomplish this?

Link to document is below:
Transpose Sequence

答:
try:

```<code>=ARRAYFORMULA(SPLIT(FLATTEN(SEQUENCE(Sheet1!B3)&"×"&
 SEQUENCE(1, Sheet1!B7, Sheet1!B8, Sheet1!B9)), "×"))
</code>```

demo sheet

Body:
try:

=ARRAYFORMULA(SPLIT(FLATTEN(SEQUENCE(Sheet1!B3)&"×"&
 SEQUENCE(1, Sheet1!B7, Sheet1!B8, Sheet1!B9)), "×"))

demo sheet


问:
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?

答:
For version control, I have been using Git for quite some time, and using Git with Github is very good for managing your code. Github also supports private repositories if you need that functionality. I've also used CVS and bazaar which work well for version control.

For time management I assume you mean for planning, calendars, etc. For a free solution, Google's Calendar has plenty of features for working with a team and making sure you stay on time.

As for a knowledge base, you could use a local mediawiki set up, relatively simple to set up and free.

I reccomend all of these from personal experience and from working in teams. Of course, there may be better paid alternatives but these have worked well together for me.

Cheers


问:
How to decode a QR-code image in (preferably pure) Python?

TL;DR: I need a way to decode a QR-code from an image file using (preferable pure) Python.

I've got a jpg file with a QR-code which I want to decode using Python. I've found a couple libraries which claim to do this:

PyQRCode (website here) which supposedly can decode qr codes from images by simply providing a path like this:

```<code>import sys, qrcode
d = qrcode.Decoder()
if d.decode('out.png'):
    print 'result: ' + d.result
else:
    print 'error: ' + d.error
</code>```

So I simply installed it using sudo pip install pyqrcode. The thing I find strange about the example code above however, is that it only imports qrcode (and not pyqrcode though) Since I think qrcode refers to this library which can only generate qr-code images it kind of confused me. So I tried the code above with both pyqrcode and qrcode, but both fail at the second line saying AttributeError: 'module' object has no attribute 'Decoder'. Furthermore, the website refers to Ubuntu 8.10 (which came out more than 6 years ago) and I can't find a public (git or other) repository of it to check the latest commit. So I moved on to the next library:

ZBar (website here) claims to be "an open source software suite for reading bar codes from various sources, such as image files." So I tried installing it on Mac OSX running sudo pip install zbar. This fails with error: command 'cc' failed with exit status 1. I tried to suggestions in the answers to this SO question, but I can't seem to solve it. So I decided to move on again:

QRTools, which according to this blogpost can decode images easily by using the following code:

```<code>from qrtools import QR
myCode = QR(filename=u"/home/psutton/Documents/Python/qrcodes/qrcode.png")
if myCode.decode():
  print myCode.data
  print myCode.data_type
  print myCode.data_to_string()
</code>```

So I tried installing it using sudo pip install qrtools, which can't find anything. I also tried it with python-qrtools, qr-tools, python-qrtools and a couple more combinations, but unfortunately to no avail. I suppose it refers to this repo which says it is based on ZBar (see above). Although I want to run my code on Heroku (and thus prefer a pure Python solution) I successfully installed it on a Linux box (with sudo apt-get install python-qrtools) and tried running it:

```<code>from qrtools import QR
c = QR(filename='/home/kramer65/qrcode.jpg')
c.data  # prints u'NULL'
c.data_type  # prints u'text'
c.data_to_string()  # prints '\xef\xbb\xbfNULL' where I expect an int (being `1234567890`)
</code>```

Although this seems to decode it, It doesn't seem to do it correctly. It furthermore needs ZBar and is thus not pure Python. So I decided to find yet another library.

PyXing (website here) is supposedly a Python port of the popular Java ZXing library, but the initial and only commit is 6 years old and the project has no readme or documentation whatsoever.

For the rest I found a couple qr-encoders (not decoders) and some API endpoints which can decode for you. Since I don't like this service to be dependent on other API endpoints I would want to keep the decoding local though.

So to conclude; would anybody know how I can decode QR-codes from images in (preferable pure) Python? All tips are welcome!

答:
PyBoof is a wrapper around BoofCV and has an easy to use QR Code reader. It also give you access to a ton of information about the QR, e.g. number of bit errors, precise location, raw message, ...</p>
```<code>image = pb.load_single_band(data_path, np.uint8)

detector = pb.FactoryFiducial(np.uint8).qrcode()
detector.detect(image)

for qr in detector.detections:
    print("Message: " + qr.message)
    print("     at: " + str(qr.bounds))
</code>```

Body:
TL;DR: I need a way to decode a QR-code from an image file using (preferable pure) Python.

I've got a jpg file with a QR-code which I want to decode using Python. I've found a couple libraries which claim to do this:

PyQRCode (website here) which supposedly can decode qr codes from images by simply providing a path like this:

import sys, qrcode
d = qrcode.Decoder()
if d.decode('out.png'):
    print 'result: ' + d.result
else:
    print 'error: ' + d.error

So I simply installed it using sudo pip install pyqrcode. The thing I find strange about the example code above however, is that it only imports qrcode (and not pyqrcode though) Since I think qrcode refers to this library which can only generate qr-code images it kind of confused me. So I tried the code above with both pyqrcode and qrcode, but both fail at the second line saying AttributeError: 'module' object has no attribute 'Decoder'. Furthermore, the website refers to Ubuntu 8.10 (which came out more than 6 years ago) and I can't find a public (git or other) repository of it to check the latest commit. So I moved on to the next library:

ZBar (website here) claims to be "an open source software suite for reading bar codes from various sources, such as image files." So I tried installing it on Mac OSX running sudo pip install zbar. This fails with error: command 'cc' failed with exit status 1. I tried to suggestions in the answers to this SO question, but I can't seem to solve it. So I decided to move on again:

QRTools, which according to this blogpost can decode images easily by using the following code:

from qrtools import QR
myCode = QR(filename=u"/home/psutton/Documents/Python/qrcodes/qrcode.png")
if myCode.decode():
  print myCode.data
  print myCode.data_type
  print myCode.data_to_string()

So I tried installing it using sudo pip install qrtools, which can't find anything. I also tried it with python-qrtools, qr-tools, python-qrtools and a couple more combinations, but unfortunately to no avail. I suppose it refers to this repo which says it is based on ZBar (see above). Although I want to run my code on Heroku (and thus prefer a pure Python solution) I successfully installed it on a Linux box (with sudo apt-get install python-qrtools) and tried running it:

from qrtools import QR
c = QR(filename='/home/kramer65/qrcode.jpg')
c.data  # prints u'NULL'
c.data_type  # prints u'text'
c.data_to_string()  # prints '\xef\xbb\xbfNULL' where I expect an int (being `1234567890`)

Although this seems to decode it, It doesn't seem to do it correctly. It furthermore needs ZBar and is thus not pure Python. So I decided to find yet another library.

PyXing (website here) is supposedly a Python port of the popular Java ZXing library, but the initial and only commit is 6 years old and the project has no readme or documentation whatsoever.

For the rest I found a couple qr-encoders (not decoders) and some API endpoints which can decode for you. Since I don't like this service to be dependent on other API endpoints I would want to keep the decoding local though.

So to conclude; would anybody know how I can decode QR-codes from images in (preferable pure) Python? All tips are welcome!

Body:
PyBoof is a wrapper around BoofCV and has an easy to use QR Code reader. It also give you access to a ton of information about the QR, e.g. number of bit errors, precise location, raw message, ...

image = pb.load_single_band(data_path, np.uint8)

detector = pb.FactoryFiducial(np.uint8).qrcode()
detector.detect(image)

for qr in detector.detections:
    print("Message: " + qr.message)
    print("     at: " + str(qr.bounds))


问:
How can I filter or query for cells in a table that fail its validation rule
I have a large table that contains a few data validation errors.
How can I filter or define a query to locate these errors?
I have thought of setting a conditional formatting rule but cannot figure out how to write the formula.
Does the red mark signifying the error have a method of describing it?
Cells in error may have a null entry or #N/A.</p>

答:
you can use ISERROR() function

```<code>=FILTER(B:B, ISERROR(A:A))
</code>```

update:

```<code>=INDEX(IF(A2:A12="",, REGEXMATCH(A2:A12&"", TEXTJOIN("|", 1, A15:A25))))
</code>```

Body:
you can use ISERROR() function

=FILTER(B:B, ISERROR(A:A))

update:

=INDEX(IF(A2:A12="",, REGEXMATCH(A2:A12&"", TEXTJOIN("|", 1, A15:A25))))


问:
Im getting TypeError using req, res
I'm getting TypeError: Cannot read properties of undefined (reading 'content-type')

This is my code:

```<code>const express = require("express");
const res = require("express/lib/response");
const app = express()

app.get('/cats', (req, res) => {
res.send('meow!')
})

app.listen(8080, () => {
res.send('MEOW!!')
})
</code>```

答:
You can make your code run with two changes.  Remove this line const res = require("express/lib/response"); and change the second res.send('MEOW!!') to console.log('MEOW!!').

Change this:

```<code>const express = require("express");
const res = require("express/lib/response");
const app = express()

app.get('/cats', (req, res) => {
    res.send('meow!')
})

app.listen(8080, () => {
    res.send('MEOW!!')
})
</code>```

to this:

```<code>const express = require("express");
const app = express();

app.get('/cats', (req, res) => {
    res.send('meow!');
});

app.listen(8080, () => {
   console.log('MEOW!!');
});
</code>```

Title: Im getting TypeError using req, res

Body:
I'm getting TypeError: Cannot read properties of undefined (reading 'content-type')

This is my code:

const express = require("express");
const res = require("express/lib/response");
const app = express()

app.get('/cats', (req, res) => {
res.send('meow!')
})

app.listen(8080, () => {
res.send('MEOW!!')
})

Body:
You can make your code run with two changes.  Remove this line const res = require("express/lib/response"); and change the second res.send('MEOW!!') to console.log('MEOW!!').

Change this:

const express = require("express");
const res = require("express/lib/response");
const app = express()

app.get('/cats', (req, res) => {
    res.send('meow!')
})

app.listen(8080, () => {
    res.send('MEOW!!')
})

to this:

const express = require("express");
const app = express();

app.get('/cats', (req, res) => {
    res.send('meow!');
});

app.listen(8080, () => {
   console.log('MEOW!!');
});


问:
How to ensure that a Struct that is made up of channels and map gets passed by reference?
I have the following struct that contains channels and a map for storage of data. I want to be able to pass that struct into functions in order to make use of those channels so that once they are triggered/have incoming messages, to use them in order to update the map that is associated with it.

I understand that maps by default are passed by reference when sent to various functions. Would this be the same case even when they are contained within a custom struct? How do i make sure that my entire struct is passed around to functions by reference in order to update Storage and also make use of its channels?

```<code>type CustomStrct struct {
Storage      map[string]string
RetrieveChannel    chan string
InsertChannel      chan string
}
</code>```

This is a constructor I have created for initialising a new instance of the struct:

```<code>func InitializeNewStore() CustomStrct {
    newCustomStruct := CustomStrct {
        Storage:      make(map[string]string),
        RetrieveChannel:    make(chan Request),
        InsertChannel:    make(chan Request),
       }

return newCustomStruct
}
</code>```

答:
Slices, maps and channels are pointer-like values in Go: copying a struct containing a channel copies a reference to the channel, not the channel itself:

a := CustomStrct{
    RetrieveChannel: make(chan Request),
}
b := a
log.Println(a.RetrieveChannel == b.RetrieveChannel)    // logs true
```
<p>So it's quite fine to pass your struct either by value or by reference.</p>
<p>If you need to ensure that <code>go vet</code> will flag attempts to pass your struct by value, the simplest solution is to embed a <code>sync.Mutex</code> inside the struct:</p>
```type CustomStrct struct {
    mu sync.Mutex
    ...
}
```

You don't need to actually use the mutex: just having it embedded in the struct will cause go vet to complain whenever you attempt to pass it by value.

Body:
I have the following struct that contains channels and a map for storage of data. I want to be able to pass that struct into functions in order to make use of those channels so that once they are triggered/have incoming messages, to use them in order to update the map that is associated with it.

I understand that maps by default are passed by reference when sent to various functions. Would this be the same case even when they are contained within a custom struct? How do i make sure that my entire struct is passed around to functions by reference in order to update Storage and also make use of its channels?

type CustomStrct struct {
Storage      map[string]string
RetrieveChannel    chan string
InsertChannel      chan string
}

This is a constructor I have created for initialising a new instance of the struct:

func InitializeNewStore() CustomStrct {
    newCustomStruct := CustomStrct {
        Storage:      make(map[string]string),
        RetrieveChannel:    make(chan Request),
        InsertChannel:    make(chan Request),
       }

return newCustomStruct
}

Body:
Slices, maps and channels are pointer-like values in Go: copying a struct containing a channel copies a reference to the channel, not the channel itself:

a := CustomStrct{
    RetrieveChannel: make(chan Request),
}
b := a
log.Println(a.RetrieveChannel == b.RetrieveChannel)    // logs true

So it's quite fine to pass your struct either by value or by reference.

If you need to ensure that go vet will flag attempts to pass your struct by value, the simplest solution is to embed a sync.Mutex inside the struct:

type CustomStrct struct {
    mu sync.Mutex
    ...
}

You don't need to actually use the mutex: just having it embedded in the struct will cause go vet to complain whenever you attempt to pass it by value.


问:
Nginx is redirecting proxy_pass to root path automatically
I have two nextjs apps running on port 3000 and 3001 and my Nginx config is as follows

```<code>events {
    worker_connections  1024;
}

http {
    server {
        listen       8080;
        server_name  http://localhost:8080;
        proxy_buffering off;
        proxy_http_version 1.1;

        location / {
            proxy_pass    http://localhost:3000/;
            proxy_redirect off;
        }
        location ^~ /app {
            proxy_pass    http://localhost:3001/;
            proxy_redirect off;
        }
    }
}
</code>```

NextJS app on port 3000 works fine.

When I visit localhost:8080 - it loads the app from port 3000 as expected.

But it is impossible to access the second app on Port 3001 through nginx URL

When I visit localhost:8080/app - it loads the app from port 3000.

When I visit localhost:8080/app/ - it changes the URL to localhost:8080 and loads the app from port 3000.

When I visit localhost:8080/app/login - It changes the URL to localhost:8080/login and loads a 404 since app on port 3000 does not have a login route.

Is there something that I am missing in this configuration?

答:
put ^~ /app block  before / block . The higher block takes priority and / block is like... for everything.

```<code>   location ^~ /app {
        proxy_pass    http://localhost:3001/;
        proxy_redirect off;
    }

   location / {
        proxy_pass    http://localhost:3000/;
        proxy_redirect off;
    }

</code>```

Anything but /app will go to the second block.

Body:
I have two nextjs apps running on port 3000 and 3001 and my Nginx config is as follows

events {
    worker_connections  1024;
}

http {
    server {
        listen       8080;
        server_name  http://localhost:8080;
        proxy_buffering off;
        proxy_http_version 1.1;

        location / {
            proxy_pass    http://localhost:3000/;
            proxy_redirect off;
        }
        location ^~ /app {
            proxy_pass    http://localhost:3001/;
            proxy_redirect off;
        }
    }
}

NextJS app on port 3000 works fine.

When I visit localhost:8080 - it loads the app from port 3000 as expected.

But it is impossible to access the second app on Port 3001 through nginx URL

When I visit localhost:8080/app - it loads the app from port 3000.

When I visit localhost:8080/app/ - it changes the URL to localhost:8080 and loads the app from port 3000.

When I visit localhost:8080/app/login - It changes the URL to localhost:8080/login and loads a 404 since app on port 3000 does not have a login route.

Is there something that I am missing in this configuration?

Body:
put ^~ /app block  before / block . The higher block takes priority and / block is like... for everything.

   location ^~ /app {
        proxy_pass    http://localhost:3001/;
        proxy_redirect off;
    }

   location / {
        proxy_pass    http://localhost:3000/;
        proxy_redirect off;
    }

Anything but /app will go to the second block.


问:
Will destructor delete built-in types and pointer objects?
I'm a c++ beginner and now reading the C++ Primer. I have some problem about the destrucor:

in chapter 13.1.3: "In a destructor, there is nothing akin to the constructor initializer list to control how members are destroyed; the destruction part is implicit. What happens when a member is destroyed depends on the type of the member. Members of class type are destroyed by running the member’s own destructor. The built-in types do not have destructors, so nothing is done to destroy members of built-in type."

So if I have such a class:

```<code>class Foo {
  ~Foo() { delete pi; }
  int *pi;
  int i;
};
</code>```

When an instance of Foo is going to  be destroyed, according to the above text, the built in type variable int i will not be destroyed? Then how it will exist since the object to which it belongs has been destroyed.

In chapter 13.1.4: "The HasPtr class that we have used in the exercises is a good example (§ 13.1.1,p.499). That class allocates dynamic memory in its constructor. The synthesized destructor will not delete a data member that is a pointer. Therefore, this class needs to define a destructor to free the memory allocated by its constructor."

I understand that the synthesized destructor does not de-allocate the memory that has been allocated by new and is pointed to by plain pointers, but here in the text, it indicates that the pointer object itself is also not deleted by the synthesized pointer. Still the example of class Foo, does that mean that after an object of Foo class is destroyed, the pointer pi will not be destroyed ( so becomes an invalid pointer )?

答:
pi stores in stack memory, and it points to an address in heap memory!
you need to call

```<code>delete pi;
</code>```

to deallocate that part of memory in heap
pi itself doesn't need to be deallocated
it will be deallocated after it's scope.

Body:
I'm a c++ beginner and now reading the C++ Primer. I have some problem about the destrucor:

in chapter 13.1.3: "In a destructor, there is nothing akin to the constructor initializer list to control how members are destroyed; the destruction part is implicit. What happens when a member is destroyed depends on the type of the member. Members of class type are destroyed by running the member’s own destructor. The built-in types do not have destructors, so nothing is done to destroy members of built-in type."

So if I have such a class:

class Foo {
  ~Foo() { delete pi; }
  int *pi;
  int i;
};

When an instance of Foo is going to  be destroyed, according to the above text, the built in type variable int i will not be destroyed? Then how it will exist since the object to which it belongs has been destroyed.

In chapter 13.1.4: "The HasPtr class that we have used in the exercises is a good example (§ 13.1.1,p.499). That class allocates dynamic memory in its constructor. The synthesized destructor will not delete a data member that is a pointer. Therefore, this class needs to define a destructor to free the memory allocated by its constructor."

I understand that the synthesized destructor does not de-allocate the memory that has been allocated by new and is pointed to by plain pointers, but here in the text, it indicates that the pointer object itself is also not deleted by the synthesized pointer. Still the example of class Foo, does that mean that after an object of Foo class is destroyed, the pointer pi will not be destroyed ( so becomes an invalid pointer )?

Body:
pi stores in stack memory, and it points to an address in heap memory!
you need to call

delete pi;

to deallocate that part of memory in heap
pi itself doesn't need to be deallocated
it will be deallocated after it's scope.


问:
Draw PNG without whitespace in pyglet
I wrote a program to render maps I make in a program named tiled. The maps have multiple layers and the program can output to .json so I wrote a program to interpret the .json file and display the map. However after I got the program to work I realized that when I draw bushes on second layer it deletes everything in the layer behind it because of the white space on the png. Is there any way to draw PNGs in pyglet without the whitespace?

With whitespaces:
https://imgur.com/VlnXUP2

In tiled (intended look without dotted lines):
https://imgur.com/xbw1K4K

```<code>import pyglet
import pyglet.gl as gl
import json

# read json file and specifically get the "data","height","width"
f = open("TILED-FILES/16x16 map2.json","r")
map = json.load(f)
layers = map['layers']

screen = pyglet.window.Window(resizable=True)

background = pyglet.image.load('/Users/naghs/srcHome/game/images/grass.png')
background.anchor_x = background.width // 2
background.anchor_y = background.height // 2

def center_image(img):
    img.anchor_x = img.width // 2
    img.anchor_y = img.height // 2

def formatMap(alist,width,height):
    matrix = []
    j1 = []
    for j in range(height):
        j1 = []
        for i in range(width):
            j1.append(alist[i*j])
            pass
        matrix.append(j1)
    return matrix

def drawTile(x,y,i=int,scale = 2):
    if i == 0:
        return
    tile = pyglet.image.load(f'tiny 16 basic tilesets/basictiles/basictiles{i}.png')
    width = 16 * scale
    height = 16 * scale
    texture = tile.get_texture()
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
    texture.width = width # resize from 8x8 to 16x16
    texture.height = height
    texture.blit(x,y)
    center_image(tile)
    texture.blit(x,y)
    pass

def draw_layer(layer,scale=2):
    map = layer["data"]
    height = layer['height']
    width = layer['width']
    tile = 16 * scale
    map = formatMap(map,width,height)
    print(map)
    y = 0
    for y1 in range(0,height*tile,tile):
        x = 0
        for x1 in range(0,width*tile,tile):
            print(map[y][x])
            drawTile(x1,y1,i=map[y][x],scale=scale)
            x += 1
        y += 1

# Old
def draw_background():
    tile = background.width
    for x in range(0,screen.width+tile,tile):
        for y in range(0,screen.height+tile,tile):
            background.blit(x,y)

@screen.event
def on_draw():
    screen.clear()
    draw_layer(layers[0])
    draw_layer(layers[1])

pyglet.app.run()
</code>```

答:
Make sure that your .PNGs are actually transparent. You haven't provided the files you are loading so I cannot verify that.

If they aren't, the easiest is to remove the background in a program like Gimp and load the files with transparent background.

BTW: from my testing pyglet.resource.image() is faster than pyglet.image.load() and make sure you close your json file with f.close() or use

```<code>with open("TILED-FILES/16x16 map2.json", "r") as file:
    map = json.load(file)
</code>```

that closes it for you once you exit with

Title: Draw PNG without whitespace in pyglet

Body:
I wrote a program to render maps I make in a program named tiled. The maps have multiple layers and the program can output to .json so I wrote a program to interpret the .json file and display the map. However after I got the program to work I realized that when I draw bushes on second layer it deletes everything in the layer behind it because of the white space on the png. Is there any way to draw PNGs in pyglet without the whitespace?

With whitespaces:
https://imgur.com/VlnXUP2

In tiled (intended look without dotted lines):
https://imgur.com/xbw1K4K

import pyglet
import pyglet.gl as gl
import json

# read json file and specifically get the "data","height","width"
f = open("TILED-FILES/16x16 map2.json","r")
map = json.load(f)
layers = map['layers']

screen = pyglet.window.Window(resizable=True)

background = pyglet.image.load('/Users/naghs/srcHome/game/images/grass.png')
background.anchor_x = background.width // 2
background.anchor_y = background.height // 2

def center_image(img):
    img.anchor_x = img.width // 2
    img.anchor_y = img.height // 2

def formatMap(alist,width,height):
    matrix = []
    j1 = []
    for j in range(height):
        j1 = []
        for i in range(width):
            j1.append(alist[i*j])
            pass
        matrix.append(j1)
    return matrix

def drawTile(x,y,i=int,scale = 2):
    if i == 0:
        return
    tile = pyglet.image.load(f'tiny 16 basic tilesets/basictiles/basictiles{i}.png')
    width = 16 * scale
    height = 16 * scale
    texture = tile.get_texture()
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
    texture.width = width # resize from 8x8 to 16x16
    texture.height = height
    texture.blit(x,y)
    center_image(tile)
    texture.blit(x,y)
    pass

def draw_layer(layer,scale=2):
    map = layer["data"]
    height = layer['height']
    width = layer['width']
    tile = 16 * scale
    map = formatMap(map,width,height)
    print(map)
    y = 0
    for y1 in range(0,height*tile,tile):
        x = 0
        for x1 in range(0,width*tile,tile):
            print(map[y][x])
            drawTile(x1,y1,i=map[y][x],scale=scale)
            x += 1
        y += 1

# Old
def draw_background():
    tile = background.width
    for x in range(0,screen.width+tile,tile):
        for y in range(0,screen.height+tile,tile):
            background.blit(x,y)

@screen.event
def on_draw():
    screen.clear()
    draw_layer(layers[0])
    draw_layer(layers[1])

pyglet.app.run()

Body:
Make sure that your .PNGs are actually transparent. You haven't provided the files you are loading so I cannot verify that.

If they aren't, the easiest is to remove the background in a program like Gimp and load the files with transparent background.

BTW: from my testing pyglet.resource.image() is faster than pyglet.image.load() and make sure you close your json file with f.close() or use

with open("TILED-FILES/16x16 map2.json", "r") as file:
    map = json.load(file)

that closes it for you once you exit with


问:
Composite Foreign Key Question
I am trying to figure out if it is possible to create a foreign key in this way.

First there are two parent tables in this scenario.

Table 1 has a PK int and another int column. When combined the two are unique.

Table 2 has a PK int and another int column. When combined the two are unique.

The paired value between the two ints is how we currently select the child records for either table.

Table 3 has a value for the PK and other int column from one of the first two tables. It is reliably selectable because the two fields when both used in a search are unique to one of the above tables.

So I am looking to create a FK or possibly two FK for this scenario. I would like to be able to do cascading deletes from either of the first tables into the third table, and would also like to use this for the entity relationships in Entity Framework.

Please let me know if this is not making sense. I have read it several times, and it is about as clear as I can get it.

Thanks

答: I don't know which dbms you are using but I don't know any that accept multi-parents. What you can do is to define an index on table3 (just to be faster) and implement the cascading delete in your application.</p>

ContentLicense: CC BY-SA 2.5

Title: Composite Foreign Key Question

OwnerDisplayName: Gambrinus


问:
TabBar disappears when starting new intent in android app
I have an Android application with four tabs. When I'm in one of the tabs, click a button which starts a new intent and go to the next view, the tabbar disappears. Any suggestions to how I can prevent that from happening? I want to have the tabbar visible no matter where the user is in the application.</p>

答:
You will need to include the tabs (is it a TabHost?) in the layout for each of your Activities. Perhaps what you really want to be doing is switching tabs within the TabHost rather than launching a new Activity...

You can do this by using TabHost.setCurrentTab

You might also be interested in doing something like the button bar at the top of the Twitter app.  Some details on implementing that can be found here: button bar similar to twitter app for android


问:
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>```

答:
As I can see in your Quantity.js component, your syntax is not good. It should be

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

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

the props should be wrapped in { } (destructed). I think that is the problem you are providing.

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

Body:
As I can see in your Quantity.js component, your syntax is not good. It should be

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

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

the props should be wrapped in { } (destructed). I think that is the problem you are providing.


问:
Docker get-started tutorial, port 3000 does not run the app
I am new to Docker and I am following their official tutorial - https://docs.docker.com/get-started/.

I am trying to start my container with this command -  docker run -dp 3000:3000 getting-started.

However, when I am trying to open my browser to http://localhost:3000 I get

I already did try to run it on different port - docker run -dp 3000:80 getting-started, however it redirects me to docker tutrial page and thats not what I want.

I have created a file app/Dockerfile with this content:

```<code># syntax=docker/dockerfile:1
FROM node:12-alpine
RUN apk add --no-cache python3 g++ make
WORKDIR /app
COPY . .
RUN yarn install --production
CMD ["node", "src/index.js"]
</code>```

I can't find the problem and I will be grateful for help.

答:
Not sure if you ever solved this but I had a similar issue as I missed this all important line located in this section:

"If you haven't already done so, open a terminal and go to the app directory with the Dockerfile"

Body:
I am new to Docker and I am following their official tutorial - https://docs.docker.com/get-started/.

I am trying to start my container with this command -  docker run -dp 3000:3000 getting-started.

However, when I am trying to open my browser to http://localhost:3000 I get

I already did try to run it on different port - docker run -dp 3000:80 getting-started, however it redirects me to docker tutrial page and thats not what I want.

I have created a file app/Dockerfile with this content:

# syntax=docker/dockerfile:1
FROM node:12-alpine
RUN apk add --no-cache python3 g++ make
WORKDIR /app
COPY . .
RUN yarn install --production
CMD ["node", "src/index.js"]

I can't find the problem and I will be grateful for help.


问:
White to Transparent Layer in matplotlib figure (SVG)
I would like to add a layer with a gradient (from white to transparent) on top of my matplotlib image and be able to save the result as an SVG eventually (I have some more shapes on my actual image than sketched below).

It is unclear to me, if this is possible with matplotlib + svg. Does anybody know or has a solution for this?

Here is some example code:

```<code>plt.figure(figsize=[6, 6])
x = np.arange(0, 100, 0.00001)
y = np.sin(0.1* np.pi * x)
plt.plot(y)
plt.axis('off')
plt.gca().set_position([0, 0, 1, 1])
# TODO: Add white -> transparent layer
plt.savefig("temp.svg", bbox_inches=0)
</code>```

The result should look like this:

Before:

After:

答:
You can adapt your code, to use as the example shown in the matplotlib documentation

More especifically, you can modify the gradient_bar function (which also uses the gradient_image function) as here explained:

```<code>def gradient_bar(ax, x, y, width=0.5, bottom=0):
    for left, top in zip(x, y):
        right = left + width
        gradient_image(
            ax,
            #here you are forcing it to be from top to bottom
            extent=(left, right, top, bottom),
            #here you are forcing it to be vertical
            direction=0,
            cmap=plt.cm.Blues,
            cmap_range=(0, 1.0))
</code>```

Body:
I would like to add a layer with a gradient (from white to transparent) on top of my matplotlib image and be able to save the result as an SVG eventually (I have some more shapes on my actual image than sketched below).

It is unclear to me, if this is possible with matplotlib + svg. Does anybody know or has a solution for this?

Here is some example code:

plt.figure(figsize=[6, 6])
x = np.arange(0, 100, 0.00001)
y = np.sin(0.1* np.pi * x)
plt.plot(y)
plt.axis('off')
plt.gca().set_position([0, 0, 1, 1])
# TODO: Add white -> transparent layer
plt.savefig("temp.svg", bbox_inches=0)

The result should look like this:

Before:

After:

Body:
You can adapt your code, to use as the example shown in the matplotlib documentation

More especifically, you can modify the gradient_bar function (which also uses the gradient_image function) as here explained:

def gradient_bar(ax, x, y, width=0.5, bottom=0):
    for left, top in zip(x, y):
        right = left + width
        gradient_image(
            ax,
            #here you are forcing it to be from top to bottom
            extent=(left, right, top, bottom),
            #here you are forcing it to be vertical
            direction=0,
            cmap=plt.cm.Blues,
            cmap_range=(0, 1.0))


问:
Flutter mobx mobx_codegen generates null safety code for computed getters
Using mobx and mobx_codegen for Flutter.

My code is NOT null safe (sdk: ">=2.7.0 <3.0.0").

When mobx_codegen generates code for @computed getters, it uses null safety, which won't compile...

Sample class counter (look at @computed):

```<code>import 'package:mobx/mobx.dart';

// Include generated file
part 'counter.g.dart';

// This is the class used by rest of your codebase
class Counter = _Counter with _$Counter;

// The store-class
abstract class _Counter with Store {
  @observable
  int value = 0;

  @computed
  int get test => 0;

  @action
  void increment() {
    value++;
  }
}
</code>```

Relevant generated code (counter.g.dart):

```<code>Computed<int>? _$testComputed;
</code>```

Shows this error:
This requires the 'non-nullable' language feature to be enabled.
Try updating your pubspec.yaml to set the minimum SDK constraint to 2.12.0 or higher, and running 'pub get'.

I'm new to mobx, am I doing something wrong?

答:
How´s it going?

I am with the same issue in my project. I installed the new flutter version and after that my project stopped to compile. I changed my dependences of mobx, flutter_mobx, mobx_codegen and build_runner and them worked.

My first dependences:

```<code>  mobx: ^1.2.1+4
  flutter_mobx: ^1.1.0+2
  build_runner: ^1.11.5
  mobx_codegen: ^1.1.2
</code>```

My last dependences:

```<code>  mobx: ^2.0.6+1
  flutter_mobx: ^2.0.4
  build_runner: ^2.1.7
  mobx_codegen: ^2.0.5+2
</code>```

From there, It has started my issue of "@computed" while I run the build_runner.

I changed the Dart SDK of my project and It stopped to show error of "@computed". But broke all source code because I developed my code with "non- null-safety".

So, looking for replies. I figured out the root cause is the specifically the mobx_codegen newer  dependency that uses null safety and doesn´t have a tratament to valid our Dart SDK.

In my opnion, It should´ve validated while running of build_runner.

So, Someone knows how could I resolve that issue?

I have a commercial solution of app, and I´ve planned to release until 3 months.

my pubspec.yaml is so:

```<code>name: XPTO
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  mobx: ^2.0.6+1
  flutter_mobx: ^2.0.4
  get_it: ^7.2.0
  flutter_search_bar: ^3.0.0-dev.1
  carousel_slider: ^4.0.0
  intl: ^0.17.0
  image_picker: ^0.8.4+5
  image_cropper: ^1.4.1
  parse_server_sdk_flutter: ^3.1.0
  cpf_cnpj_validator: ^2.0.0
  brasil_fields: ^1.3.0
  mask_text_input_formatter: ^2.1.0
  badges: ^2.0.2
  flutter_rating_bar: ^4.0.0
  expandable: ^5.0.1
  flutter_easyloading: ^3.0.3
  internet_connection_checker: ^0.0.1+3
  cached_network_image: ^3.2.0
  flutter_keyboard_visibility: ^5.1.1
  json_annotation: ^4.4.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  build_runner: ^2.1.7
  mobx_codegen: ^2.0.5+2
  graphs: ^2.1.0
  json_serializable: ^6.1.4

dependency_overrides:
  plugin_platform_interface: ^2.0.0
  build_resolvers: ^2.0.6
  web_socket_channel: ^2.0.0
  analyzer: ^3.2.0

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^1.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  assets:
    - images/logo.jpeg
    - images/empty.jpg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages
</code>```

Body:
Using mobx and mobx_codegen for Flutter.

My code is NOT null safe (sdk: ">=2.7.0 <3.0.0").

When mobx_codegen generates code for @computed getters, it uses null safety, which won't compile...

Sample class counter (look at @computed):

import 'package:mobx/mobx.dart';

// Include generated file
part 'counter.g.dart';

// This is the class used by rest of your codebase
class Counter = _Counter with _$Counter;

// The store-class
abstract class _Counter with Store {
  @observable
  int value = 0;

  @computed
  int get test => 0;

  @action
  void increment() {
    value++;
  }
}

Relevant generated code (counter.g.dart):

Computed<int>? _$testComputed;

Shows this error:
This requires the 'non-nullable' language feature to be enabled.
Try updating your pubspec.yaml to set the minimum SDK constraint to 2.12.0 or higher, and running 'pub get'.

I'm new to mobx, am I doing something wrong?

Body:
How´s it going?

I am with the same issue in my project. I installed the new flutter version and after that my project stopped to compile. I changed my dependences of mobx, flutter_mobx, mobx_codegen and build_runner and them worked.

My first dependences:

  mobx: ^1.2.1+4
  flutter_mobx: ^1.1.0+2
  build_runner: ^1.11.5
  mobx_codegen: ^1.1.2

My last dependences:

  mobx: ^2.0.6+1
  flutter_mobx: ^2.0.4
  build_runner: ^2.1.7
  mobx_codegen: ^2.0.5+2

From there, It has started my issue of "@computed" while I run the build_runner.

I changed the Dart SDK of my project and It stopped to show error of "@computed". But broke all source code because I developed my code with "non- null-safety".

So, looking for replies. I figured out the root cause is the specifically the mobx_codegen newer  dependency that uses null safety and doesn´t have a tratament to valid our Dart SDK.

In my opnion, It should´ve validated while running of build_runner.

So, Someone knows how could I resolve that issue?

I have a commercial solution of app, and I´ve planned to release until 3 months.

my pubspec.yaml is so:

name: XPTO
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  mobx: ^2.0.6+1
  flutter_mobx: ^2.0.4
  get_it: ^7.2.0
  flutter_search_bar: ^3.0.0-dev.1
  carousel_slider: ^4.0.0
  intl: ^0.17.0
  image_picker: ^0.8.4+5
  image_cropper: ^1.4.1
  parse_server_sdk_flutter: ^3.1.0
  cpf_cnpj_validator: ^2.0.0
  brasil_fields: ^1.3.0
  mask_text_input_formatter: ^2.1.0
  badges: ^2.0.2
  flutter_rating_bar: ^4.0.0
  expandable: ^5.0.1
  flutter_easyloading: ^3.0.3
  internet_connection_checker: ^0.0.1+3
  cached_network_image: ^3.2.0
  flutter_keyboard_visibility: ^5.1.1
  json_annotation: ^4.4.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  build_runner: ^2.1.7
  mobx_codegen: ^2.0.5+2
  graphs: ^2.1.0
  json_serializable: ^6.1.4

dependency_overrides:
  plugin_platform_interface: ^2.0.0
  build_resolvers: ^2.0.6
  web_socket_channel: ^2.0.0
  analyzer: ^3.2.0

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^1.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  assets:
    - images/logo.jpeg
    - images/empty.jpg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages


问:
Extending classes that extend Zend_Db_Table_Row_Abstract
We are building an online payment system using Zend Framework and we try to design it to make it easier to add new payment systems. Currently we have an implementation for PayPal, but maybe we want to add other providers later too.

We have a Payment object that extends Zend_Db_Table_Row_Abstract and a Payments object extending Zend_Db_Table_Abstract. The Payment object now has PayPal specific data in its row which we want to move to a different, PayPal specific, table. This enables us to have general data for payments in the payments table and payment provider specific data in another.

Now we tried to make a class PayPalPayment extending Payment and a class PayPalPayments extending Zend_Db_Table_Abstract. The PayPalPayments refers to our new database table and the new object PayPalPayment. What we want to do now is:

```<code>$ppp = new PayPalPayments();
$p = $ppp->createRow();
//set a paypal specific property. setToken is defined in PayPalPayment
$p->setToken('lol');
//set a Payment general property. setStatus is defined in Payment
$p->setStatus('paid');
//write to database
$p->save();
</code>```

However, we cannot get this to work since the createRow will only return a row with the columns in the PayPalPayment table. So this would give the error:

```<code>Specified column "pay_status" is not in the row
</code>```

Found some things about relations in the Zend framework documentation, but that's not really how we want to do it. Anyone tried this before?

Regards,
Lars

答: Did you declare in class PayPalPayments that the default $_rowClass = 'PayPalPayment'?

Body:
We are building an online payment system using Zend Framework and we try to design it to make it easier to add new payment systems. Currently we have an implementation for PayPal, but maybe we want to add other providers later too.

We have a Payment object that extends Zend_Db_Table_Row_Abstract and a Payments object extending Zend_Db_Table_Abstract. The Payment object now has PayPal specific data in its row which we want to move to a different, PayPal specific, table. This enables us to have general data for payments in the payments table and payment provider specific data in another.

Now we tried to make a class PayPalPayment extending Payment and a class PayPalPayments extending Zend_Db_Table_Abstract. The PayPalPayments refers to our new database table and the new object PayPalPayment. What we want to do now is:

$ppp = new PayPalPayments();
$p = $ppp->createRow();
//set a paypal specific property. setToken is defined in PayPalPayment
$p->setToken('lol');
//set a Payment general property. setStatus is defined in Payment
$p->setStatus('paid');
//write to database
$p->save();

However, we cannot get this to work since the createRow will only return a row with the columns in the PayPalPayment table. So this would give the error:

Specified column "pay_status" is not in the row

Found some things about relations in the Zend framework documentation, but that's not really how we want to do it. Anyone tried this before?

Regards,
Lars


问:
Repeat changing value in single column in a dataframe n times using dplyr
I am using dplyr to manipulate and tidy up a data frame and need to repeat a specific value in one of the columns 3 more times (4 in total). It is just a single column of the dataframe that needs to edited and I am not sure how to do this with the mutate function.

```<code>current_column = c(69886, 1, 1, 1, 38866, 1, 1, 1)
desired_column = c(69886, 69886, 69886, 69886, 38866, 38866, 38866, 38866)
</code>```

答:
There are a variety of ways to replicate values in R. Without more context it is difficult to be sure exactly which approach will be better.

Depending on your setup, you may be able to use the rep function. For example:

df = data.frame(desired_column = c(rep(69886, 4), rep(38866, 4)))
```
<p>If there are other columns in your data frame these could be used to group the data together. For example:</p>
<pre class="lang-r prettyprint-override"><code>df = data.frame(groups = c(1,1,1,1,2,2,2,2),
                current_column = c(69886, 1, 1, 1, 38866, 1, 1, 1))

df = df %>%
  group_by(groups) %>%
  mutate(desired_column = max(current_column))
</code>```

But if neither of these are an option, then the best I can propose is looping through the table. Note that this approach is dependent on order of the rows in the data frame, if the order of the rows changes, then this method will fail.

current_value = NA

# loop through all rows
for(ii in 1:nrow(df)){
  # if value in this row is not 1, record this value
  if(df$current_column[ii] != 1){
    current_value = df$current_column[ii]
  # if value in this row is 1, overwrite this value
  } else {
    df$current_column[ii] = current_value
  }
}
```
<p>If you really want a dplyr solution, the following is less efficient but does something similar to the immediately above:</p>
<pre class="lang-r prettyprint-override"><code>df = data.frame(current_column = c(69886, 1, 1, 1, 38866, 1, 1, 1))

df = df %>% mutate(new_col = current_column)

for(ii in 1:10){ # this will replace up to 10 following 1's, increase this number if there are more 1's
  df = df %>%
    mutate(lag_col = lag(new_col)) %>%
    mutate(new_col = ifelse(new_col == 1, lag_col, new_col)) %>%
    select(current_column, new_col, desired_column)
}
</code>```

Body:
I am using dplyr to manipulate and tidy up a data frame and need to repeat a specific value in one of the columns 3 more times (4 in total). It is just a single column of the dataframe that needs to edited and I am not sure how to do this with the mutate function.

current_column = c(69886, 1, 1, 1, 38866, 1, 1, 1)
desired_column = c(69886, 69886, 69886, 69886, 38866, 38866, 38866, 38866)

Body:
There are a variety of ways to replicate values in R. Without more context it is difficult to be sure exactly which approach will be better.

Depending on your setup, you may be able to use the rep function. For example:

df = data.frame(desired_column = c(rep(69886, 4), rep(38866, 4)))

If there are other columns in your data frame these could be used to group the data together. For example:

df = data.frame(groups = c(1,1,1,1,2,2,2,2),
                current_column = c(69886, 1, 1, 1, 38866, 1, 1, 1))

df = df %>%
  group_by(groups) %>%
  mutate(desired_column = max(current_column))

But if neither of these are an option, then the best I can propose is looping through the table. Note that this approach is dependent on order of the rows in the data frame, if the order of the rows changes, then this method will fail.

current_value = NA

# loop through all rows
for(ii in 1:nrow(df)){
  # if value in this row is not 1, record this value
  if(df$current_column[ii] != 1){
    current_value = df$current_column[ii]
  # if value in this row is 1, overwrite this value
  } else {
    df$current_column[ii] = current_value
  }
}

If you really want a dplyr solution, the following is less efficient but does something similar to the immediately above:

df = data.frame(current_column = c(69886, 1, 1, 1, 38866, 1, 1, 1))

df = df %>% mutate(new_col = current_column)

for(ii in 1:10){ # this will replace up to 10 following 1's, increase this number if there are more 1's
  df = df %>%
    mutate(lag_col = lag(new_col)) %>%
    mutate(new_col = ifelse(new_col == 1, lag_col, new_col)) %>%
    select(current_column, new_col, desired_column)
}