问:
URL was not found in the server
I am trying to deploy my ml model in flask. The error appear when i am trying access my height-weight.html page from the home.html page.

code for app.py

```<code>from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

if __name__ == "__main__":
    app.run()

</code>```

This works perfectly fine. It render home.html. No problem here.

Output 1:-

But as soon as I click Check Project button following error occurs.

Output 2:-

Code for height-weight.py

```<code>from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)

model = pickle.load(open('model.pkl', 'rb'))

@app.route('/predict')
def weight_predict():
    return render_template('height-weight.html')

@app.route('/predict',methods=['POST'])
def predict():
    if request.method == 'POST':
        height = float(request.form['height'])
        gender = float(request.form['gender'])

        prediction = model.predict([[gender, height]])

        output = round(prediction[0], 2)

    return render_template('height-weight.html', weights = output)

if __name__ == "__main__":
    app.run()
</code>```

And finally my html code for height-weight.html look like this.

Code:-

```<code><section id='form'>
                <div class="container">
                    <h1>Height Weight Prediction</h1>

                    <form action="{{ url_for('predict')}}" method="get">
                        <div class="card">
                            <div class="card-body">
                                <label>Gender</label>
                                <input type="text" class="form-control" id='gender' placeholder="Input Your Gender" required="required">
                            </div>
                            <div class="card-body">
                                <label>Height</label>
                                <input type="text" class="form-control" id='height' placeholder="Input Your Height" required="required">
                                <small class="form-text text-muted">Please input your height in 'Inch'.</small>
                            </div>
                            <button type="submit">Predict Weight</button>
                        </div>
                    </form>
                    {{ weights }}
                </div>
            </section>

</code>```

My expected output is to show height-weight.html pages from where i can predict the weight. This is my error. Hope you guys understand my error and please help me. Thanks in advance.

答:
You are redirecting the page to 127.0.0.1:5000/height-weight.html which is looking for the HTML file on the backend server. You need to redirect the page to /redirect by providing it in an anchor tag.

Flask renders the HTML page and returns the response it doesn't serve the HTML page directly. That's why you are getting 404 error.

Hope this helps!

Title: URL was not found in the server

Body:
I am trying to deploy my ml model in flask. The error appear when i am trying access my height-weight.html page from the home.html page.

code for app.py

from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

if __name__ == "__main__":
    app.run()

This works perfectly fine. It render home.html. No problem here.

Output 1:-

But as soon as I click Check Project button following error occurs.

Output 2:-

Code for height-weight.py

from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)

model = pickle.load(open('model.pkl', 'rb'))

@app.route('/predict')
def weight_predict():
    return render_template('height-weight.html')

@app.route('/predict',methods=['POST'])
def predict():
    if request.method == 'POST':
        height = float(request.form['height'])
        gender = float(request.form['gender'])

        prediction = model.predict([[gender, height]])

        output = round(prediction[0], 2)

    return render_template('height-weight.html', weights = output)

if __name__ == "__main__":
    app.run()

And finally my html code for height-weight.html look like this.

Code:-

Height Weight Prediction

                    <form action="{{ url_for('predict')}}" method="get">

                                Gender
                                <input type="text" class="form-control" id='gender' placeholder="Input Your Gender" required="required">

                                Height
                                <input type="text" class="form-control" id='height' placeholder="Input Your Height" required="required">
                                Please input your height in 'Inch'.

                            <button type="submit">Predict Weight</button>

                    </form>
                    {{ weights }}

My expected output is to show height-weight.html pages from where i can predict the weight. This is my error. Hope you guys understand my error and please help me. Thanks in advance.


来源: stackexchange

问:
Empty String Validation Exception - DynamoDB
I have scoured the internet on how to fix this with little success...

I am parsing a CSV and putting the data into a table using DynamoDB.
Anytime there is a blank entry, I receive the error:

```<code>One or more parameter values were invalid: An AttributeValue may not contain an empty string
</code>```

For example:

```<code>Header: "Name","Age","Birth date"
Entry:  Brandon,22  <------ THROWS ERROR
</code>```

The problem is, I will never know if there are blanks or not in the CSV. But I still need to parse it even if there is.

I have attempted to re-assign the value of the empty string to something like "N/A" in an effort to subvert this error to no avail. Any suggestions?

EDIT: Code to add context.

```<code>var file = process.argv[2];
console.log("File: " + file);

var csv = require("fast-csv");

csv.fromPath(file, {
        headers: true,
        ignoreEmpty: true
    })
    .on("data", function(data) {
        // Uncomment to see CSV data
        // console.log(data);

        params = {
            TableName: tableName,
            Item: {
                RefID: {
                    S: data["Ref-ID"]
                },
                //lots more items
            }
        };

        //Validation loops to make sure the items are defined
        for (var key in params.Item) {
            for (var items in params.Item[key]) {
                var value = params.Item[key][items];
                if (value === undefined || value === "") {
                    value = "N/A";
            }
        }

        dynamodb.putItem(params, function(err, info) {
            if (err) {
                console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
            }
            else {
                console.log("Added item:", JSON.stringify(data, null, 2));
            }
        });
        // }

    })
    .on("end", function() {
        console.log("done");
    });
</code>```

答:
2020 May 18 Update:

DynamoDB now supports empty string values for non-key attributes: https://aws.amazon.com/about-aws/whats-new/2020/05/amazon-dynamodb-now-supports-empty-values-for-non-key-string-and-binary-attributes-in-dynamodb-tables/

You should no longer see this Exception when writing to DynamoDB.

ContentLicense: CC BY-SA 3.0

Body:
I have scoured the internet on how to fix this with little success...

I am parsing a CSV and putting the data into a table using DynamoDB.
Anytime there is a blank entry, I receive the error:

One or more parameter values were invalid: An AttributeValue may not contain an empty string

For example:

Header: "Name","Age","Birth date"
Entry:  Brandon,22  <------ THROWS ERROR

The problem is, I will never know if there are blanks or not in the CSV. But I still need to parse it even if there is.

I have attempted to re-assign the value of the empty string to something like "N/A" in an effort to subvert this error to no avail. Any suggestions?

EDIT: Code to add context.

var file = process.argv[2];
console.log("File: " + file);

var csv = require("fast-csv");

csv.fromPath(file, {
        headers: true,
        ignoreEmpty: true
    })
    .on("data", function(data) {
        // Uncomment to see CSV data
        // console.log(data);

        params = {
            TableName: tableName,
            Item: {
                RefID: {
                    S: data["Ref-ID"]
                },
                //lots more items
            }
        };

        //Validation loops to make sure the items are defined
        for (var key in params.Item) {
            for (var items in params.Item[key]) {
                var value = params.Item[key][items];
                if (value === undefined || value === "") {
                    value = "N/A";
            }
        }

        dynamodb.putItem(params, function(err, info) {
            if (err) {
                console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
            }
            else {
                console.log("Added item:", JSON.stringify(data, null, 2));
            }
        });
        // }

    })
    .on("end", function() {
        console.log("done");
    });

ContentLicense: CC BY-SA 4.0


问:
Convert String to HTML Ready text for MAILTO: URL
I am writing a large Java Application in which I would like to include a "Send Email" button.
All it does is open a mailto url with the appropriate headers.

The only difficulty I am having is parsing the input strings so that they are formatted appropriately, for example:
mailto:someone@somewhere.net?subject=This is the subject
needs to become
mailto:someone@somewhere.net?subject=This%20is%20the%20subject

答:
You most likely need to "URLEncode" (translates the space characters (' ') to %20.

See this document: http://download.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html


问:
Python Flask automatically generated Swagger/OpenAPI 3.0
Im trying to generate swagger document for my existing Flask app, I tried with Flask-RESTPlus initially and found out the project is abundant now and checked at the forked project flask-restx  https://github.com/python-restx/flask-restx but still i dont think they support openapi 3.0

Im a bit confused to choose the package for my need. Im looking to solve a problem where we dont want to manually create swagger doc for our API, instead we would like to generate automatically using a packages.

import os
import requests
import json, yaml

from flask import Flask, after_this_request, send_file, safe_join, abort
from flask_restx import Resource, Api, fields
from flask_restx.api import Swagger

app = Flask(__name__)
api = Api(app=app, doc='/docs', version='1.0.0-oas3', title='TEST APP API',
          description='TEST APP API')

response_fields = api.model('Resource', {
    'value': fields.String(required=True, min_length=1, max_length=200, description='Book title')
})

@api.route('/compiler/', endpoint='compiler')
# @api.doc(params={'id': 'An ID'})
@api.doc(responses={403: 'Not Authorized'})
@api.doc(responses={402: 'Not Authorized'})
# @api.doc(responses={200: 'Not Authorized'})
class DemoList(Resource):
    @api.expect(response_fields, validate=True)
    @api.marshal_with(response_fields, code=200)
    def post(self):
        """
        returns a list of conferences
        """
        api.payload["value"] = 'Im the response ur waiting for'
        return api.payload

@api.route('/swagger')
class HelloWorld(Resource):
    def get(self):
        data = json.loads(json.dumps(api.__schema__))
        with open('yamldoc.yml', 'w') as yamlf:
            yaml.dump(data, yamlf, allow_unicode=True, default_flow_style=False)
            file = os.path.abspath(os.getcwd())
            try:
                @after_this_request
                def remove_file(resp):
                    try:
                        os.remove(safe_join(file, 'yamldoc.yml'))
                    except Exception as error:
                        log.error("Error removing or closing downloaded file handle", error)
                    return resp

                return send_file(safe_join(file, 'yamldoc.yml'), as_attachment=True, attachment_filename='yamldoc.yml', mimetype='application/x-yaml')
            except FileExistsError:
                abort(404)

# main driver function
if __name__ == '__main__':
    app.run(port=5003, debug=True)
```

The above code is a combination of my try on different packages, but it can generate swagger 2.0 doc but im trying to generate doc for openapi 3.0

Can some one suggest a good package which is supporting openapi 3.0 way of generating swagger yaml or json.

答:
I found a package to generate openapi 3.0 document

https://apispec.readthedocs.io/en/latest/install.html

This package serves the purpose neatly. Find the below code for detailed usage.

from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.flask import FlaskPlugin
from marshmallow import Schema, fields
from flask import Flask, abort, request, make_response, jsonify
from pprint import pprint
import json

class DemoParameter(Schema):
    gist_id = fields.Int()

class DemoSchema(Schema):
    id = fields.Int()
    content = fields.Str()

spec = APISpec(
    title="Demo API",
    version="1.0.0",
    openapi_version="3.0.2",
    info=dict(
        description="Demo API",
        version="1.0.0-oas3",
        contact=dict(
            email="admin@donofden.com"
            ),
        license=dict(
            name="Apache 2.0",
            url='http://www.apache.org/licenses/LICENSE-2.0.html'
            )
        ),
    servers=[
        dict(
            description="Test server",
            url="https://resources.donofden.com"
            )
        ],
    tags=[
        dict(
            name="Demo",
            description="Endpoints related to Demo"
            )
        ],
    plugins=[FlaskPlugin(), MarshmallowPlugin()],
)

spec.components.schema("Demo", schema=DemoSchema)

# spec.components.schema(
#     "Gist",
#     {
#         "properties": {
#             "id": {"type": "integer", "format": "int64"},
#             "name": {"type": "string"},
#         }
#     },
# )
#
# spec.path(
#     path="/gist/{gist_id}",
#     operations=dict(
#         get=dict(
#             responses={"200": {"content": {"application/json": {"schema": "Gist"}}}}
#         )
#     ),
# )
# Extensions initialization
# =========================
app = Flask(__name__)

@app.route("/demo/<gist_id>", methods=["GET"])
def my_route(gist_id):
    """Gist detail view.
    ---
    get:
      parameters:
      - in: path
        schema: DemoParameter
      responses:
        200:
          content:
            application/json:
              schema: DemoSchema
        201:
          content:
            application/json:
              schema: DemoSchema
    """
    # (...)
    return jsonify('foo')

# Since path inspects the view and its route,
# we need to be in a Flask request context
with app.test_request_context():
    spec.path(view=my_route)
# We're good to go! Save this to a file for now.
with open('swagger.json', 'w') as f:
    json.dump(spec.to_dict(), f)

pprint(spec.to_dict())
print(spec.to_yaml())

```

Hope this helps someone!! :)

Update: More Detailed Documents

Python Flask automatically generated Swagger 3.0/Openapi Document - http://donofden.com/blog/2020/06/14/Python-Flask-automatically-generated-Swagger-3-0-openapi-Document

Python Flask automatically generated Swagger 2.0 Document -
http://donofden.com/blog/2020/05/30/Python-Flask-automatically-generated-Swagger-2-0-Document

Body:
Im trying to generate swagger document for my existing Flask app, I tried with Flask-RESTPlus initially and found out the project is abundant now and checked at the forked project flask-restx  https://github.com/python-restx/flask-restx but still i dont think they support openapi 3.0

Im a bit confused to choose the package for my need. Im looking to solve a problem where we dont want to manually create swagger doc for our API, instead we would like to generate automatically using a packages.

import os
import requests
import json, yaml

from flask import Flask, after_this_request, send_file, safe_join, abort
from flask_restx import Resource, Api, fields
from flask_restx.api import Swagger

app = Flask(__name__)
api = Api(app=app, doc='/docs', version='1.0.0-oas3', title='TEST APP API',
          description='TEST APP API')

response_fields = api.model('Resource', {
    'value': fields.String(required=True, min_length=1, max_length=200, description='Book title')
})

@api.route('/compiler/', endpoint='compiler')
# @api.doc(params={'id': 'An ID'})
@api.doc(responses={403: 'Not Authorized'})
@api.doc(responses={402: 'Not Authorized'})
# @api.doc(responses={200: 'Not Authorized'})
class DemoList(Resource):
    @api.expect(response_fields, validate=True)
    @api.marshal_with(response_fields, code=200)
    def post(self):
        """
        returns a list of conferences
        """
        api.payload["value"] = 'Im the response ur waiting for'
        return api.payload

@api.route('/swagger')
class HelloWorld(Resource):
    def get(self):
        data = json.loads(json.dumps(api.__schema__))
        with open('yamldoc.yml', 'w') as yamlf:
            yaml.dump(data, yamlf, allow_unicode=True, default_flow_style=False)
            file = os.path.abspath(os.getcwd())
            try:
                @after_this_request
                def remove_file(resp):
                    try:
                        os.remove(safe_join(file, 'yamldoc.yml'))
                    except Exception as error:
                        log.error("Error removing or closing downloaded file handle", error)
                    return resp

                return send_file(safe_join(file, 'yamldoc.yml'), as_attachment=True, attachment_filename='yamldoc.yml', mimetype='application/x-yaml')
            except FileExistsError:
                abort(404)

# main driver function
if __name__ == '__main__':
    app.run(port=5003, debug=True)

The above code is a combination of my try on different packages, but it can generate swagger 2.0 doc but im trying to generate doc for openapi 3.0

Can some one suggest a good package which is supporting openapi 3.0 way of generating swagger yaml or json.

Body:
I found a package to generate openapi 3.0 document

https://apispec.readthedocs.io/en/latest/install.html

This package serves the purpose neatly. Find the below code for detailed usage.

from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.flask import FlaskPlugin
from marshmallow import Schema, fields
from flask import Flask, abort, request, make_response, jsonify
from pprint import pprint
import json

class DemoParameter(Schema):
    gist_id = fields.Int()

class DemoSchema(Schema):
    id = fields.Int()
    content = fields.Str()

spec = APISpec(
    title="Demo API",
    version="1.0.0",
    openapi_version="3.0.2",
    info=dict(
        description="Demo API",
        version="1.0.0-oas3",
        contact=dict(
            email="admin@donofden.com"
            ),
        license=dict(
            name="Apache 2.0",
            url='http://www.apache.org/licenses/LICENSE-2.0.html'
            )
        ),
    servers=[
        dict(
            description="Test server",
            url="https://resources.donofden.com"
            )
        ],
    tags=[
        dict(
            name="Demo",
            description="Endpoints related to Demo"
            )
        ],
    plugins=[FlaskPlugin(), MarshmallowPlugin()],
)

spec.components.schema("Demo", schema=DemoSchema)

# spec.components.schema(
#     "Gist",
#     {
#         "properties": {
#             "id": {"type": "integer", "format": "int64"},
#             "name": {"type": "string"},
#         }
#     },
# )
#
# spec.path(
#     path="/gist/{gist_id}",
#     operations=dict(
#         get=dict(
#             responses={"200": {"content": {"application/json": {"schema": "Gist"}}}}
#         )
#     ),
# )
# Extensions initialization
# =========================
app = Flask(__name__)

@app.route("/demo/<gist_id>", methods=["GET"])
def my_route(gist_id):
    """Gist detail view.
    ---
    get:
      parameters:
      - in: path
        schema: DemoParameter
      responses:
        200:
          content:
            application/json:
              schema: DemoSchema
        201:
          content:
            application/json:
              schema: DemoSchema
    """
    # (...)
    return jsonify('foo')

# Since path inspects the view and its route,
# we need to be in a Flask request context
with app.test_request_context():
    spec.path(view=my_route)
# We're good to go! Save this to a file for now.
with open('swagger.json', 'w') as f:
    json.dump(spec.to_dict(), f)

pprint(spec.to_dict())
print(spec.to_yaml())

Hope this helps someone!! :)

Update: More Detailed Documents

Python Flask automatically generated Swagger 3.0/Openapi Document - http://donofden.com/blog/2020/06/14/Python-Flask-automatically-generated-Swagger-3-0-openapi-Document

Python Flask automatically generated Swagger 2.0 Document -
http://donofden.com/blog/2020/05/30/Python-Flask-automatically-generated-Swagger-2-0-Document


问:
Difference between HTML "overflow : auto" and "overflow : scroll"
When I was studying the overflow property's values, I came across these two values: auto and scroll, which adds scrollbar(s) if the content overflows the element.

Could someone please explain me whats the difference between them?

答:
overflow: scroll will show both horizontal and vertical scrollbar even when you don't need one or other. while, overflow: auto will show the scrollbar which your div needs. so basically auto will help you to get rid of both scollbar.
Here is more of that:

https://css-tricks.com/the-css-overflow-property/


问:
Lazy loading function in Javascript
In our code sometimes we need a function to load after some time the page is loaded, for stuff like caching the articles of website which is not needed while the page load is happening.

I was wondering if we can write or use some syntax which can lazy load that particular function.

Example:

lazyload funnction xyz(){
    // put your code here
}
```

If there is any way to do this or something similar approach, It is fine if you point me to any patterns, frameworks etc.

答:
First, you should distinguish between "lazy loading" and "delayed loading".

Lazy loading very specifically means loading when it's necessary. In this case, it means try running some code, if not loaded, then load and run. This would imply that load will be immediately followed by run.

Delayed loading means loading at an arbitrarily-decided time for any reason, without necessarily running the code immediately. In other words, delayed loading is a superset of lazy loading.

I'm not sure whether your need is strictly lazy loading. But their implementation is similar enough. This is how I would do it, assuming you don't want to use modules.

Idea: have the lazily-loaded code in a separate file, and load the file by adding a script tag to your DOM. Then set an arbitrary trigger for this action to achieve delayed loading.

In main.js:

```<code>function loadDelayed() {
  const tag = "<script src='delayed.js'></script>";
  document.querySelector("head").insertAdjacentHTML("beforeend", tag);
}
// E.g. trigger via timeout after 5 seconds
setTimeout(loadDelayed, 5000);
</code>```

In delayed.js:

```<code>function myDelayedFunc() {
  // Your code here
}
</code>```

If you just want lazy loading, create one .js file for each lazily-loaded function:

E.g. func1.js:

```<code>(() => {
  // Your code here
})();
</code>```

And in main.js create a helper function:

```<code>function runLazy(funcName) {
  const tag = `<script src='${funcName}.js'></script>`;
  document.querySelector("head").insertAdjacentHTML("beforeend", tag);
}

runLazy("func1");
</code>```

Note: although the browser will load the file from cache after the first call, this naive approach will always add a new script tag to your DOM every time you call runLazy(). If you intend to call the function many times, you might wish to use loadDelayed() and then call the function normally.

Title: Lazy loading function in Javascript

Body:
In our code sometimes we need a function to load after some time the page is loaded, for stuff like caching the articles of website which is not needed while the page load is happening.

I was wondering if we can write or use some syntax which can lazy load that particular function.

Example:

lazyload funnction xyz(){
    // put your code here
}

If there is any way to do this or something similar approach, It is fine if you point me to any patterns, frameworks etc.

Body:
First, you should distinguish between "lazy loading" and "delayed loading".

Lazy loading very specifically means loading when it's necessary. In this case, it means try running some code, if not loaded, then load and run. This would imply that load will be immediately followed by run.

Delayed loading means loading at an arbitrarily-decided time for any reason, without necessarily running the code immediately. In other words, delayed loading is a superset of lazy loading.

I'm not sure whether your need is strictly lazy loading. But their implementation is similar enough. This is how I would do it, assuming you don't want to use modules.

Idea: have the lazily-loaded code in a separate file, and load the file by adding a script tag to your DOM. Then set an arbitrary trigger for this action to achieve delayed loading.

In main.js:

function loadDelayed() {
  const tag = "<script src='delayed.js'></script>";
  document.querySelector("head").insertAdjacentHTML("beforeend", tag);
}
// E.g. trigger via timeout after 5 seconds
setTimeout(loadDelayed, 5000);

In delayed.js:

function myDelayedFunc() {
  // Your code here
}

If you just want lazy loading, create one .js file for each lazily-loaded function:

E.g. func1.js:

(() => {
  // Your code here
})();

And in main.js create a helper function:

function runLazy(funcName) {
  const tag = `<script src='${funcName}.js'></script>`;
  document.querySelector("head").insertAdjacentHTML("beforeend", tag);
}

runLazy("func1");

Note: although the browser will load the file from cache after the first call, this naive approach will always add a new script tag to your DOM every time you call runLazy(). If you intend to call the function many times, you might wish to use loadDelayed() and then call the function normally.


问:
Which observables do Angular complete automatically?
Which observables produced by Angular are also completed by Angular?

For example:

HttpClient completes any observables as the request finishes

observables from the Router (parammap, queryparammap, etc) automatically complete when the route changes.

What other observables from Angular does Angular complete for you automatically and under what circumstances?

答:
observables from the Router [...] automatically complete when the route changes.

I wouldn't say this is true. When the route changes, that view is destroyed and since each ActivatedRoute is associated with a route(thus with a route component), when the component is destroyed, everything inside it will be destroyed, as well any subscriptions to sources which belong to that component(e.g ActivatedRoute.params). At least this is what I've noticed, but it for sure does not emits a complete notification when a route changes.

The same would apply for @ViewChildren. Since it will query for elements from the current component's view, when the component will be destroyed, that source(@ViewChildren.changes) will be nulled out as well, so there is no need to manually unsubscribe.

Same for valueChanges or statusChanges(assuming that the form control is created in that component).

Memory leaks can occur when you have, for instance, a global service. Because it is global it just keeps references to subscribers, which can come from multiple places. But since the global service's existence does not depend on whether a component is destroyed, it's up to that component to let the service know that it is no longer interested in receiving values.

Some very interesting things happen with guards.

When using a canLoad guard, if you return an observable, you must make sure that your observable completes(e.g by adding take(1)). This is important as Angular does not automatically handle this for you:

sbj = new BehaviorSubject(true)

canLoad (route: Route, segments: UrlSegment[]) {
  // Although it's returning `true`, it never completes
  return this.sbj;
}
```

<p>From its implementation we can see why:</p>

<pre class="lang-js prettyprint-override"><code>
// Observable that will emit each `canLoad` individually
const obs = from(canLoad).pipe(map((injectionToken: any) => {
  const guard = moduleInjector.get(injectionToken);
  let guardVal;
  if (isCanLoad(guard)) {
    guardVal = guard.canLoad(route, segments);
  } /* ... */
  return wrapIntoObservable(guardVal);
}));

return obs.pipe(
  // `concatAll` === `mergeMap(obs => obs, 1)`
  // `concatAll` requires an observable to **complete** in order to subscribe to the next one
  concatAll(),
  /* ... */
  every(result => result === true),
);
</code>```

On the other side, when using canActivate for example, it's another story. This time, Angular will automatically take the first value and then complete, so this should work:

sbj = new BehaviorSubject(true);

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

  return this.sbj;
}
```

<p>As seen in the implementation:</p>

<pre class="lang-js prettyprint-override"><code>const canActivateObservables = canActivate.map((c: any) => {
  return defer(() => {
    const guard = getToken(c, futureARS, moduleInjector);
    let observable;

    if (isCanActivate(guard)) {
      observable = wrapIntoObservable(guard.canActivate(futureARS, futureRSS));
    } /* ... */

    // Only get the first emitted value and then complete
    return observable.pipe(first());
  });
});
return of(canActivateObservables).pipe(prioritizedGuardValue());
</code>```

Body:
observables from the Router [...] automatically complete when the route changes.

I wouldn't say this is true. When the route changes, that view is destroyed and since each ActivatedRoute is associated with a route(thus with a route component), when the component is destroyed, everything inside it will be destroyed, as well any subscriptions to sources which belong to that component(e.g ActivatedRoute.params). At least this is what I've noticed, but it for sure does not emits a complete notification when a route changes.

The same would apply for @ViewChildren. Since it will query for elements from the current component's view, when the component will be destroyed, that source(@ViewChildren.changes) will be nulled out as well, so there is no need to manually unsubscribe.

Same for valueChanges or statusChanges(assuming that the form control is created in that component).

Memory leaks can occur when you have, for instance, a global service. Because it is global it just keeps references to subscribers, which can come from multiple places. But since the global service's existence does not depend on whether a component is destroyed, it's up to that component to let the service know that it is no longer interested in receiving values.

Some very interesting things happen with guards.

When using a canLoad guard, if you return an observable, you must make sure that your observable completes(e.g by adding take(1)). This is important as Angular does not automatically handle this for you:

sbj = new BehaviorSubject(true)

canLoad (route: Route, segments: UrlSegment[]) {
  // Although it's returning `true`, it never completes
  return this.sbj;
}

From its implementation we can see why:

// Observable that will emit each `canLoad` individually
const obs = from(canLoad).pipe(map((injectionToken: any) => {
  const guard = moduleInjector.get(injectionToken);
  let guardVal;
  if (isCanLoad(guard)) {
    guardVal = guard.canLoad(route, segments);
  } /* ... */
  return wrapIntoObservable(guardVal);
}));

return obs.pipe(
  // `concatAll` === `mergeMap(obs => obs, 1)`
  // `concatAll` requires an observable to **complete** in order to subscribe to the next one
  concatAll(),
  /* ... */
  every(result => result === true),
);

On the other side, when using canActivate for example, it's another story. This time, Angular will automatically take the first value and then complete, so this should work:

sbj = new BehaviorSubject(true);

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

  return this.sbj;
}

As seen in the implementation:

const canActivateObservables = canActivate.map((c: any) => {
  return defer(() => {
    const guard = getToken(c, futureARS, moduleInjector);
    let observable;

    if (isCanActivate(guard)) {
      observable = wrapIntoObservable(guard.canActivate(futureARS, futureRSS));
    } /* ... */

    // Only get the first emitted value and then complete
    return observable.pipe(first());
  });
});
return of(canActivateObservables).pipe(prioritizedGuardValue());


问:
Portable and safe way to add byte offset to any pointer
I'm quite new at working with C++ and haven't grasped all the intricacies and subtleties of the language.

What is the most portable, correct and safe way to add an arbitrary byte offset to a pointer of any type in C++11?

```<code>SomeType* ptr;
int offset = 12345 /* bytes */;
ptr = ptr + offset;             // <--
</code>```

I found many answers on Stack Overflow and Google, but they all propose different things. Some variants I have encountered:

Cast to char *:

```<code>ptr = (SomeType*)(((char*)ptr) + offset);
</code>```

Cast to unsigned int:

```<code>ptr = (SomeType*)((unsigned int)ptr) + offset);
</code>```

Cast to size_t:

```<code>ptr = (SomeType*)((size_t)ptr) + offset);
</code>```

"The size of size_t and ptrdiff_t always coincide with the pointer's size. Because of this, it is these types that should be used as indexes for large arrays, for storage of pointers and pointer arithmetic." - About size_t and ptrdiff_t on CodeProject

```<code>ptr = (SomeType*)((size_t)ptr + (ptrdiff_t)offset);
</code>```

Or like the previous, but with intptr_t instead of size_t, which is signed instead of unsigned:

```<code>ptr = (SomeType*)((intptr_t)ptr + (ptrdiff_t)offset);
</code>```

Only cast to intptr_t, since offset is already a signed integer and intptr_t is not size_t:

```<code>ptr = (SomeType*)((intptr_t)ptr) + offset);
</code>```

And in all these cases, is it safe to use old C-style casts, or is it safer or more portable to use static_cast or reinterpret_cast for this?

Should I assume the pointer value itself is unsigned or signed?

答:
Mine isn't as elegant, but I hope is more readable.
    char helper_ptr;
    helper_ptr= (char) ptr;

Then you can traverse byte-by-byte using helper_ptr.

ptr = (SomeType*)(((char*)ptr) + 1) will advance the ptr by sizeof(SomeType) instead of 1 byte.

Body:
I'm quite new at working with C++ and haven't grasped all the intricacies and subtleties of the language.

What is the most portable, correct and safe way to add an arbitrary byte offset to a pointer of any type in C++11?

SomeType* ptr;
int offset = 12345 /* bytes */;
ptr = ptr + offset;             // <--

I found many answers on Stack Overflow and Google, but they all propose different things. Some variants I have encountered:

Cast to char *:

ptr = (SomeType*)(((char*)ptr) + offset);

Cast to unsigned int:

ptr = (SomeType*)((unsigned int)ptr) + offset);

Cast to size_t:

ptr = (SomeType*)((size_t)ptr) + offset);

"The size of size_t and ptrdiff_t always coincide with the pointer's size. Because of this, it is these types that should be used as indexes for large arrays, for storage of pointers and pointer arithmetic." - About size_t and ptrdiff_t on CodeProject

ptr = (SomeType*)((size_t)ptr + (ptrdiff_t)offset);

Or like the previous, but with intptr_t instead of size_t, which is signed instead of unsigned:

ptr = (SomeType*)((intptr_t)ptr + (ptrdiff_t)offset);

Only cast to intptr_t, since offset is already a signed integer and intptr_t is not size_t:

ptr = (SomeType*)((intptr_t)ptr) + offset);

And in all these cases, is it safe to use old C-style casts, or is it safer or more portable to use static_cast or reinterpret_cast for this?

Should I assume the pointer value itself is unsigned or signed?


问:
Problem with style.format() and a decimal column
I am trying to apply a style.format function to a data frame in order to adjust the number of decimal places, since the round() function does not apply. (I don't understand why.)

The data in the df are of the format 123.0, 432.0, and 543.0, but I need them to have two decimal places (e.g., 123.00).

I have verified with the function df.dtypes that the column is of type float.

I tried to apply the following:

import pandas.io.formats.style
import pandas as pd

df['DD'] = df[['Quantity']].style.format("{:.2%}")
df
```

<p>But the following appears in the <code>DD</code> field:</p>

```<pandas.io.formats.style.Styler object at 0x7f...
```

The round() function does not work on the column either.

What can be done?

答:
The .style gives back a Styler object (reference). The Styler object can be formatted in different ways. This has not happened in your DD column; you are only halfway through.

You can format the dataframe with

```<code>df.style.format({'Quantity': "{:.2%}"})
</code>```

as explained in this SO post.

Body:
I am trying to apply a style.format function to a data frame in order to adjust the number of decimal places, since the round() function does not apply. (I don't understand why.)

The data in the df are of the format 123.0, 432.0, and 543.0, but I need them to have two decimal places (e.g., 123.00).

I have verified with the function df.dtypes that the column is of type float.

I tried to apply the following:

import pandas.io.formats.style
import pandas as pd

df['DD'] = df[['Quantity']].style.format("{:.2%}")
df

But the following appears in the DD field:

<pandas.io.formats.style.Styler object at 0x7f...

The round() function does not work on the column either.

What can be done?

Body:
The .style gives back a Styler object (reference). The Styler object can be formatted in different ways. This has not happened in your DD column; you are only halfway through.

You can format the dataframe with

df.style.format({'Quantity': "{:.2%}"})

as explained in this SO post.


问:
I am having problem with 'done' button's click event on my todo app
I want to create a simple todo list from javascript. Everything seems fine but the functionality is not working properly. I used for loop to iterate through every buttons in the list and fired an event listener on click. The problem is, when there are more than to items on the list and if I click 'done' on the first element the required class i.e. 'line' is not triggered. However, the lists at the bottom seems to be functioning properly.

const add = document.getElementById('add');
let list = document.querySelector('#list');
let task = document.getElementById('task');

// function to handle buttons

function handleButtons(){
    let allSpan = document.querySelectorAll('span');
    let allList = document.querySelectorAll('li');
    const doneButton = document.querySelectorAll('.done');
    const deleteButton = document.querySelectorAll('.delete');

    for(let i=0; i < doneButton.length; i++ ){
            doneButton[i].addEventListener('click',function doneTask(){
            let clickedbtn = [...allSpan].indexOf(doneButton[i].parentElement);
            allList[clickedbtn].firstChild.classList.toggle('line');

            })
        }

    for(let i=0; i < deleteButton.length; i++ ){
        deleteButton[i].addEventListener('click',function deleteTask(){
                let clickedbtn = [...allSpan].indexOf(deleteButton[i].parentElement);
                allList[clickedbtn].classList.add('hide');

        })
    }

}
// Add Lists
function addList(){
    if(task.value !== ''){
    let li = document.createElement('li');
    let p =document.createElement('p')
    p.classList.add('default')
    let t = document.createTextNode(task.value);
    p.appendChild(t);
    // create a span for the buttons
    let span = document.createElement('span');
    let doneBtn = document.createElement('button');
    let doneTxt = document.createTextNode('Done');
    let deleteBtn = document.createElement('button');
    let deleteTxt = document.createTextNode('Delete');

    doneBtn.appendChild(doneTxt);
    doneBtn.classList.add('done');
    deleteBtn.appendChild(deleteTxt);
    deleteBtn.classList.add('delete');

    li.appendChild(p);
    span.appendChild(doneBtn);
    span.appendChild(deleteBtn);
    li.appendChild(span);
    list.appendChild(li);
    // console.log(list)
    // reset the input
    task.value = '';
    }
    else{
        alert('Enter a task!')
    }
    handleButtons();
}
// Event Listeners
add.addEventListener('click',addList);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}
ul{list-style: none;}
.main{
    min-height: 100vh;
    padding-top: 100px;
    background-color: rgb(231, 231, 230);
}
.container{
    position: relative;
    text-align: center;
    top: 10%;
    transform: translateY(-10%);
    width: 100%;
    margin: auto;
}
.container h1{
    margin-bottom: 20px;
    font-size: 2.7rem;
    text-transform: uppercase;
    letter-spacing: 5px;
    word-spacing: 5px;
    color: rgb(231, 96, 96);
}
.container input{
    border: none;
    font-size: 1.5rem;
    padding: 4px 8px;
    border-radius: 4px;
    width: 50%;
    outline: none;
}

.container button{
    font-size: 1.5rem;
    border: none;
    cursor: pointer;
    padding: 3px 8px;
    width: 20%;
    background-color: rgb(159, 221, 65);
    transition: .5s;
    outline: none;
}
.container button:hover{
    background-color: rgb(13, 177, 21);
    color: rgb(233, 225, 225);
}
.list{
    margin-top: 20px;
    width: 72%;
    margin: auto;
    padding: 30px 10px;
    font-size: 18px;
    text-align: start;
}
.list li{
    display: flex;
    font-size: 21px;
    margin-bottom: 20px;
    padding: 14px 20px;
    background-color: lightgrey;
    justify-content: space-between;
    align-items: center;

}
#list li span{
    width: 40%;
}
.list .delete{
    background-color: rgb(231, 63, 63);
    width: 40%;
    margin: 10px;
    font-size: 18px;
}
.list .delete:hover{
    background-color: rgb(230, 28, 28);

}
.list .done{
    background-color: rgb(12, 185, 113);
    width: 40%;
    margin: 10px;
    font-size: 18px;
}
.list .done:hover{
    background-color: rgb(5, 168, 59);

}
.default{
    text-decoration:none;
}
p.line{
    text-decoration: line-through;
}
li.hide{
    display: none;
}

@media(max-width:790px){
    #task{
        font-size: 14px;
        width: 67%;
    }
    #add{
        font-size: 14px;
    }
    .list span{
        width: 50%;
        display: flex;
        justify-content: space-around;
    }
    .list{
        width: 95%;
    }
    .list li{
        font-size: 10px;
    }
    .list .done{
        width: 78%;
        font-size: 10px;
    }
    .list .delete{

        width: 78%;
        font-size: 10px;
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <link href="style.css" rel="stylesheet">
    <title>TODO</title>

TODO List

            <input type="text" name="task" id="task" autocomplete="off" placeholder="Enter The Task">
            <button id="add">ADD</button>

```

so

答:
@Prashanth,

Please see the quick answer to this problem. I have modified the app.js below. I removed handlebutton function.

```<code>const add = document.getElementById('add');
let list = document.querySelector('#list');
let task = document.getElementById('task');

// Add Lists
function addList(){
if(task.value !== ''){
let li = document.createElement('li');
let p =document.createElement('p')
p.classList.add('default')
let t = document.createTextNode(task.value);
p.appendChild(t);
// create a span for the buttons
let span = document.createElement('span');
let doneBtn = document.createElement('button');
let doneTxt = document.createTextNode('Done');
let deleteBtn = document.createElement('button');
let deleteTxt = document.createTextNode('Delete');

doneBtn.addEventListener('click',function(){
    p.classList.toggle('line');
});

deleteBtn.addEventListener('click',function(){
    li.classList.add('hide');
});
doneBtn.appendChild(doneTxt);
doneBtn.classList.add('done');
deleteBtn.appendChild(deleteTxt);
deleteBtn.classList.add('delete');

li.appendChild(p);
span.appendChild(doneBtn);
span.appendChild(deleteBtn);
li.appendChild(span);
list.appendChild(li);
// console.log(list)
// reset the input
task.value = '';
}
else{
    alert('Enter a task!')
}
}
// Event Listeners
add.addEventListener('click',addList);
</code>```

Issue is the on click event was triggering for all buttons for a single click.
For assigning onclick for new items, you are iterating complete elements, which is not a good practice.

Body:
I want to create a simple todo list from javascript. Everything seems fine but the functionality is not working properly. I used for loop to iterate through every buttons in the list and fired an event listener on click. The problem is, when there are more than to items on the list and if I click 'done' on the first element the required class i.e. 'line' is not triggered. However, the lists at the bottom seems to be functioning properly.

const add = document.getElementById('add');
let list = document.querySelector('#list');
let task = document.getElementById('task');

// function to handle buttons

function handleButtons(){
    let allSpan = document.querySelectorAll('span');
    let allList = document.querySelectorAll('li');
    const doneButton = document.querySelectorAll('.done');
    const deleteButton = document.querySelectorAll('.delete');

    for(let i=0; i < doneButton.length; i++ ){
            doneButton[i].addEventListener('click',function doneTask(){
            let clickedbtn = [...allSpan].indexOf(doneButton[i].parentElement);
            allList[clickedbtn].firstChild.classList.toggle('line');

            })
        }

    for(let i=0; i < deleteButton.length; i++ ){
        deleteButton[i].addEventListener('click',function deleteTask(){
                let clickedbtn = [...allSpan].indexOf(deleteButton[i].parentElement);
                allList[clickedbtn].classList.add('hide');

        })
    }

}
// Add Lists
function addList(){
    if(task.value !== ''){
    let li = document.createElement('li');
    let p =document.createElement('p')
    p.classList.add('default')
    let t = document.createTextNode(task.value);
    p.appendChild(t);
    // create a span for the buttons
    let span = document.createElement('span');
    let doneBtn = document.createElement('button');
    let doneTxt = document.createTextNode('Done');
    let deleteBtn = document.createElement('button');
    let deleteTxt = document.createTextNode('Delete');

    doneBtn.appendChild(doneTxt);
    doneBtn.classList.add('done');
    deleteBtn.appendChild(deleteTxt);
    deleteBtn.classList.add('delete');

    li.appendChild(p);
    span.appendChild(doneBtn);
    span.appendChild(deleteBtn);
    li.appendChild(span);
    list.appendChild(li);
    // console.log(list)
    // reset the input
    task.value = '';
    }
    else{
        alert('Enter a task!')
    }
    handleButtons();
}
// Event Listeners
add.addEventListener('click',addList);

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}
ul{list-style: none;}
.main{
    min-height: 100vh;
    padding-top: 100px;
    background-color: rgb(231, 231, 230);
}
.container{
    position: relative;
    text-align: center;
    top: 10%;
    transform: translateY(-10%);
    width: 100%;
    margin: auto;
}
.container h1{
    margin-bottom: 20px;
    font-size: 2.7rem;
    text-transform: uppercase;
    letter-spacing: 5px;
    word-spacing: 5px;
    color: rgb(231, 96, 96);
}
.container input{
    border: none;
    font-size: 1.5rem;
    padding: 4px 8px;
    border-radius: 4px;
    width: 50%;
    outline: none;
}

.container button{
    font-size: 1.5rem;
    border: none;
    cursor: pointer;
    padding: 3px 8px;
    width: 20%;
    background-color: rgb(159, 221, 65);
    transition: .5s;
    outline: none;
}
.container button:hover{
    background-color: rgb(13, 177, 21);
    color: rgb(233, 225, 225);
}
.list{
    margin-top: 20px;
    width: 72%;
    margin: auto;
    padding: 30px 10px;
    font-size: 18px;
    text-align: start;
}
.list li{
    display: flex;
    font-size: 21px;
    margin-bottom: 20px;
    padding: 14px 20px;
    background-color: lightgrey;
    justify-content: space-between;
    align-items: center;

}
#list li span{
    width: 40%;
}
.list .delete{
    background-color: rgb(231, 63, 63);
    width: 40%;
    margin: 10px;
    font-size: 18px;
}
.list .delete:hover{
    background-color: rgb(230, 28, 28);

}
.list .done{
    background-color: rgb(12, 185, 113);
    width: 40%;
    margin: 10px;
    font-size: 18px;
}
.list .done:hover{
    background-color: rgb(5, 168, 59);

}
.default{
    text-decoration:none;
}
p.line{
    text-decoration: line-through;
}
li.hide{
    display: none;
}

@media(max-width:790px){
    #task{
        font-size: 14px;
        width: 67%;
    }
    #add{
        font-size: 14px;
    }
    .list span{
        width: 50%;
        display: flex;
        justify-content: space-around;
    }
    .list{
        width: 95%;
    }
    .list li{
        font-size: 10px;
    }
    .list .done{
        width: 78%;
        font-size: 10px;
    }
    .list .delete{

        width: 78%;
        font-size: 10px;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <link href="style.css" rel="stylesheet">
    <title>TODO</title>

TODO List

            <input type="text" name="task" id="task" autocomplete="off" placeholder="Enter The Task">
            <button id="add">ADD</button>

so

Body:
@Prashanth,

Please see the quick answer to this problem. I have modified the app.js below. I removed handlebutton function.

const add = document.getElementById('add');
let list = document.querySelector('#list');
let task = document.getElementById('task');

// Add Lists
function addList(){
if(task.value !== ''){
let li = document.createElement('li');
let p =document.createElement('p')
p.classList.add('default')
let t = document.createTextNode(task.value);
p.appendChild(t);
// create a span for the buttons
let span = document.createElement('span');
let doneBtn = document.createElement('button');
let doneTxt = document.createTextNode('Done');
let deleteBtn = document.createElement('button');
let deleteTxt = document.createTextNode('Delete');

doneBtn.addEventListener('click',function(){
    p.classList.toggle('line');
});

deleteBtn.addEventListener('click',function(){
    li.classList.add('hide');
});
doneBtn.appendChild(doneTxt);
doneBtn.classList.add('done');
deleteBtn.appendChild(deleteTxt);
deleteBtn.classList.add('delete');

li.appendChild(p);
span.appendChild(doneBtn);
span.appendChild(deleteBtn);
li.appendChild(span);
list.appendChild(li);
// console.log(list)
// reset the input
task.value = '';
}
else{
    alert('Enter a task!')
}
}
// Event Listeners
add.addEventListener('click',addList);

Issue is the on click event was triggering for all buttons for a single click.
For assigning onclick for new items, you are iterating complete elements, which is not a good practice.


问:
AWS S3 -> Elastic Beanstalk - Mixed content error
I have a frontend deployed on S3 using https.
When frontend request backend API (load balancer -> elastic beanstalk) then I got an error: Mixed content.
I know that it is because I am calling API via HTTP, not https.

My question is:
Should I create a brand new SSL certificate for my LoadBalancer?
And how to do this if my load balancer DNS address looks like this:
awseb-address.region.elb.amazonaws.com (A Record)

I tried to use this address in Certificate Manager but it is not accepting it.

答:
Should I create a brand new SSL certificate for my LoadBalancer? [...] I tried to use this address in Certificate Manager but it is not accepting it.

You can't register a certificate direclty for awseb-address.region.elb.amazonaws.com.

This is AWS owned domain. To register a SSL certificate, you need to have your own domain that you control. You can acquire one from AWS or on any other domain seller.

However, if already have a domain for your fronted, as you mentioned, then maybe you can use that, and create a subdomain for your ELB. You can have one certificate for multiple domains.


问:
PyQt5 closeEvent method
I'm currently learning how to build an application with pyqt5 and encountered some problem with closeEvent method, overriden so user gets asked for confirmation by QMessageBox object. It seems working well with X button - event gets 'accepted' when action is confirmed and 'canceled' when cancel button is clicked. However, when I use my Quit button from dropdown File menu, no matter which button I click, program gets closed with exit code 1. Seems strange, because I use same closeEvent method in both cases.

```<code>import sys

from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow, QAction

class window(QMainWindow):
    def __init__(self):

        super().__init__()

    def createUI(self):

        self.setGeometry(500, 300, 700, 700)

        self.setWindowTitle("window")

        quit = QAction("Quit", self)
        quit.triggered.connect(self.closeEvent)

        menubar = self.menuBar()
        fmenu = menubar.addMenu("File")
        fmenu.addAction(quit)

    def closeEvent(self, event):
        close = QMessageBox()
        close.setText("You sure?")
        close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
        close = close.exec()

        if close == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

main = QApplication(sys.argv)
window = window()
window.createUI()
window.show()
sys.exit(main.exec_())
</code>```

Thanks for suggestions!

答:
I had the same problem and fixed with a type-check-hack. It might be an ugly hack, but it works (tested on macOS 10.15 with python 3.8.0 and PyQt 5.14.2).</p>

```<code>class Gui(QtWidgets.QMainWindow):
    def __init__(self):
        super(Gui, self).__init__()
        uic.loadUi("gui.ui", self)

        # ...

        self.actionExit = self.findChild(QtWidgets.QAction, "actionExit")
        self.actionExit.triggered.connect(self.closeEvent)

        # ...

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Quit?',
                                     'Are you sure you want to quit?',
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            if not type(event) == bool:
                event.accept()
            else:
                sys.exit()
        else:
            if not type(event) == bool:
                event.ignore()
</code>```

Title: PyQt5 closeEvent method

Body:
I'm currently learning how to build an application with pyqt5 and encountered some problem with closeEvent method, overriden so user gets asked for confirmation by QMessageBox object. It seems working well with X button - event gets 'accepted' when action is confirmed and 'canceled' when cancel button is clicked. However, when I use my Quit button from dropdown File menu, no matter which button I click, program gets closed with exit code 1. Seems strange, because I use same closeEvent method in both cases.

import sys

from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow, QAction

class window(QMainWindow):
    def __init__(self):

        super().__init__()

    def createUI(self):

        self.setGeometry(500, 300, 700, 700)

        self.setWindowTitle("window")

        quit = QAction("Quit", self)
        quit.triggered.connect(self.closeEvent)

        menubar = self.menuBar()
        fmenu = menubar.addMenu("File")
        fmenu.addAction(quit)

    def closeEvent(self, event):
        close = QMessageBox()
        close.setText("You sure?")
        close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
        close = close.exec()

        if close == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

main = QApplication(sys.argv)
window = window()
window.createUI()
window.show()
sys.exit(main.exec_())

Thanks for suggestions!

Body:
I had the same problem and fixed with a type-check-hack. It might be an ugly hack, but it works (tested on macOS 10.15 with python 3.8.0 and PyQt 5.14.2).

class Gui(QtWidgets.QMainWindow):
    def __init__(self):
        super(Gui, self).__init__()
        uic.loadUi("gui.ui", self)

        # ...

        self.actionExit = self.findChild(QtWidgets.QAction, "actionExit")
        self.actionExit.triggered.connect(self.closeEvent)

        # ...

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Quit?',
                                     'Are you sure you want to quit?',
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            if not type(event) == bool:
                event.accept()
            else:
                sys.exit()
        else:
            if not type(event) == bool:
                event.ignore()


问:
Is it the correct way to create XML schema? Please suggest
1:

```<code>  <xs:element name="abcd" minOccurs="1" maxOccurs="1"/>
    <xs:simpleType>
     <xs:restriction base="xs:string">
      <xs:length value="4"/>
    </xs:restriction>
   </xs:simpleType>
  </xs:element>
</code>```

2:

```<code><xs:element name="abcd" type="xs:string" length value = "4" minOccurs="1" maxOccurs="1"/>
</code>```

Can I add maxOccurs and minOccurs as I have done in number 1. Is number 2 also correct way to define schema?

答:
Your first code example has a small syntax error. The <xs:element> start tag has a slash / in the end which makes it a self-closing element and your XML would be malformed. Removing the slash fixes that error.

```<code><xs:element name="abcd" minOccurs="1" maxOccurs="1"/>
  <xs:simpl...
</xs:element>
</code>```

Yes, you can generally add minOccurs and maxOccurs as you have done, but this is not allowed for global element definitions (which means that <xs:element> is a (direct) child of the <xs:schema> element). The default values both for minOccurs and maxOccurs is 1, so in your example code the meaning would stay the same even if they were left out.

Your second example contains an error.

```<code><xs:element name="abcd" type="xs:string" length value = "4" minOccurs="1" maxOccurs="1"/>
</code>```

length is not a valid attribute for element <xs:element> Also the XML recommendation does not allow spaces before or after the equals character = but not all parsers complain about this. Otherwise it seems correct.

Body:
1:

  <xs:element name="abcd" minOccurs="1" maxOccurs="1"/>
    <xs:simpleType>
     <xs:restriction base="xs:string">
      <xs:length value="4"/>
    </xs:restriction>
   </xs:simpleType>
  </xs:element>

2:

<xs:element name="abcd" type="xs:string" length value = "4" minOccurs="1" maxOccurs="1"/>

Can I add maxOccurs and minOccurs as I have done in number 1. Is number 2 also correct way to define schema?

Body:
Your first code example has a small syntax error. The <xs:element> start tag has a slash / in the end which makes it a self-closing element and your XML would be malformed. Removing the slash fixes that error.

<xs:element name="abcd" minOccurs="1" maxOccurs="1"/>
  <xs:simpl...
</xs:element>

Yes, you can generally add minOccurs and maxOccurs as you have done, but this is not allowed for global element definitions (which means that <xs:element> is a (direct) child of the <xs:schema> element). The default values both for minOccurs and maxOccurs is 1, so in your example code the meaning would stay the same even if they were left out.

Your second example contains an error.

<xs:element name="abcd" type="xs:string" length value = "4" minOccurs="1" maxOccurs="1"/>

length is not a valid attribute for element <xs:element> Also the XML recommendation does not allow spaces before or after the equals character = but not all parsers complain about this. Otherwise it seems correct.


答:
maybe you mean:

```<code>SELECT
T1.*
,_T2.TotalAmount
FROM T1
INNER JOIN
(
SELECT WBS_Parent , sum(amount) TotalAmount
FROM T2
GROUP BY WBS_Parent
) _T2 ON _T2.WBS_Parent = T1.Projectex
</code>```

else, it's better to put a sample data output for the result you expect

Title: SQL - JOIN QUERY - SUMMING ISSUE

Body:
I am joining 2 tables using the query below.  Its many to many relationship.

The join works fine but creates multiple rows for each item which is expected but the value is also duplicated. How to avoid this? Thanks
As you can see the Current output the value (50000 appears 3 times instead of 1 and 27000 appears 3 times instead of 1)

SELECT * FROM T1
INNER JOIN T2 ON
T1.Projectex = T2.WBS_Parent

Table 1:

+-----------+------------+-----------+----------+--------+----------+-------+
| Projectex | CAPEX_OPEX | costelmnt | sap_vers | Period | FISCYEAR | VALUE |
+-----------+------------+-----------+----------+--------+----------+-------+
| 0-01081   | CAPEX      |      3416 |       61 |      3 |     2020 | 50000 |
| 0-01081   | OPEX       |      7077 |       30 |      5 |     2020 | 27000 |
+-----------+------------+-----------+----------+--------+----------+-------+

Table2:

+------------+-----------------+---------+---------+
| WBS_PARENT | FINANCILAL_YEAR | MEASURE | AMOUNT  |
+------------+-----------------+---------+---------+
| 0-01081    |            2020 | CPX     | 2000000 |
| 0-01081    |            2020 | OPX     |   50000 |
| 0-01081    |            2020 | OPX     | 1000000 |
+------------+-----------------+---------+---------+

CURRENT OUTPUT:

Projectex| CAPEX_OPEX|  costelmnt|  sap_vers|  Period|  FISCYEAR|  VALUE|
0   0-01081|      CAPEX|       3416|       61|      3|      2020|  50000|
1   0-01081|      CAPEX|       3416|       61|      3|      2020|  50000|
2   0-01081|      CAPEX|       3416|       61|      3|      2020|  50000|
3   0-01081|       OPEX|       7077|       30|      5|      2020|  27000|
4   0-01081|       OPEX|       7077|       30|      5|      2020|  27000|
5   0-01081|       OPEX|       7077|       30|      5|      2020|  27000|

  WBS_PARENT  FINANCILAL_YEAR MEASURE   AMOUNT
0    0-01081|            2020|     CPX|  2000000
1    0-01081|            2020|     OPX|    50000
2    0-01081|            2020|     OPX|  1000000
3    0-01081|            2020|     CPX|  2000000
4    0-01081|            2020|     OPX|    50000
5    0-01081|            2020|     OPX|  1000000

Expected Output:

Projectex| CAPEX_OPEX|  costelmnt|  sap_vers|  Period|  FISCYEAR|  VALUE|

0   0-01081|      CAPEX|       3416|       61|      3|      2020|  50000|

1   0-01081|      CAPEX|       3416|       61|      3|      2020|

2   0-01081|      CAPEX|       3416|       61|      3|      2020|

3   0-01081|       OPEX|       7077|       30|      5|      2020|  27000|

4   0-01081|       OPEX|       7077|       30|      5|      2020|

5   0-01081|       OPEX|       7077|       30|      5|      2020|

WBS_PARENT  FINANCILAL_YEAR MEASURE   AMOUNT

0    0-01081|            2020|     CPX|  2000000

1    0-01081|            2020|     OPX|    50000

2    0-01081|            2020|     OPX|  1000000

3    0-01081|            2020|     CPX|

4    0-01081|            2020|     OPX|

5    0-01081|            2020|     OPX|

Body:
maybe you mean:

SELECT
T1.*
,_T2.TotalAmount
FROM T1
INNER JOIN
(
SELECT WBS_Parent , sum(amount) TotalAmount
FROM T2
GROUP BY WBS_Parent
) _T2 ON _T2.WBS_Parent = T1.Projectex

else, it's better to put a sample data output for the result you expect


问:
splitting a string using strtok()
I have a string I would like to split into two different strings, the delimiter is $$$.
For instance: milk $$$ 45
On the left side is the product name and on the right is its quantity.
I've used strtok to split the string but I can't extract the number unfortunately.

```<code>int num;
char *token = strtok(str, DELIMITER);
printf("%s\n", token);
strcpy(component->name, token);
char *number = strtok(NULL, "       ");
num = atoi(number);
printf("%s\n", number);
</code>```

The printf calls are for debugging.

答:
I didnt debug your code but using strtok_r() its better and more intuitive. C provides two functions strtok() and strtok_r() for splitting a string by some delimiter.

strtok_r()

Just like strtok() function in C, strtok_r() does the same task of parsing a string into a sequence of tokens. strtok_r() is a reentrant version of strtok()

function Signature

char *strtok_r(char *str, const char *delim, char **saveptr);

The third argument saveptr is a pointer to a char *
variable that is used internally by strtok_r() in
order to maintain context between successive calls
that parse the same string.

```<code>#include <stdio.h>
#include <string.h> /*for the strtok function*/
#include <ctype.h> /*for the isalpha function*/
int main()
{
    /*assume your string is a raw string just like the one bellow. and if its not.
    please modify the code.
    */
    char str[80] = "milk $$$ 45 meat $$$ 89 water $$$ 12";
    const char* delim = " $$$ ";
    char* token = NULL;
    char* rest = str;
    int num;

    while ((token = strtok_r(rest, " $$$ ", &rest)))
    {
        /*if its a number we will convert it to integer number*/
        if (!isalpha(token[0]))
        {
            num = atoi(token);
            printf("The price is: %d\n",num);
        }
        /*else it is a string*/
        printf("The prodact name is: %s\n", token);

    }

    return 0;
}
</code>```

Title: splitting a string using strtok()

Body:
I have a string I would like to split into two different strings, the delimiter is $$$.
For instance: milk $$$ 45
On the left side is the product name and on the right is its quantity.
I've used strtok to split the string but I can't extract the number unfortunately.

int num;
char *token = strtok(str, DELIMITER);
printf("%s\n", token);
strcpy(component->name, token);
char *number = strtok(NULL, "       ");
num = atoi(number);
printf("%s\n", number);

The printf calls are for debugging.

Body:
I didnt debug your code but using strtok_r() its better and more intuitive. C provides two functions strtok() and strtok_r() for splitting a string by some delimiter.

strtok_r()

Just like strtok() function in C, strtok_r() does the same task of parsing a string into a sequence of tokens. strtok_r() is a reentrant version of strtok()

function Signature

char *strtok_r(char *str, const char *delim, char **saveptr);

The third argument saveptr is a pointer to a char *
variable that is used internally by strtok_r() in
order to maintain context between successive calls
that parse the same string.

#include <stdio.h>
#include <string.h> /*for the strtok function*/
#include <ctype.h> /*for the isalpha function*/
int main()
{
    /*assume your string is a raw string just like the one bellow. and if its not.
    please modify the code.
    */
    char str[80] = "milk $$$ 45 meat $$$ 89 water $$$ 12";
    const char* delim = " $$$ ";
    char* token = NULL;
    char* rest = str;
    int num;

    while ((token = strtok_r(rest, " $$$ ", &rest)))
    {
        /*if its a number we will convert it to integer number*/
        if (!isalpha(token[0]))
        {
            num = atoi(token);
            printf("The price is: %d\n",num);
        }
        /*else it is a string*/
        printf("The prodact name is: %s\n", token);

    }

    return 0;
}


问:
Magento 2. Add ui-form elements dynamically (at Admin area)
We have a ui-form at Admin area, which should implement the following behavior: "on product category select, show filterable product attributes with possible values (as multi-selects)".

Product categories are displayed as drop-down list.
There is a controller, which retrieves attributes with values for a provided category id.

How to join these together so on "Category select" the form gets several multi-selects added below?

General problem. To create a ui-form in admin, xml form fields are defined. However, in this case, these field names are not known in advance - we do not know what are the filters available for a particular category, neither we know the multi-select values.
As an attempt for solution, we added a javascript to the form, which ajax-called a controller on category drop-down change and it returned the required data, but how to add new form fields to an already created form, then?

答:
First, find out the layout of this page. Then, overwrite this on your module by adding custom js to it. There you can handle this case by adding js functions.
If I am not correct, please add the screenshot of your dropdown & multi-select.</p>


问:
How to detect swipe in flutter
I've tried using the swipe detector plugin for flutter to achieve navigating to a new screen on swipe right but it's not working, no errors are thrown and the breakpoint is never hit when I debug it. I looked into the GestureDector but I wasn't sure it would work for a swipe right scenario, we want it to navigate to a screen when anywhere on the screen is swiped right.

Here's my code using the plugin

```<code> @override
 Widget build(BuildContext context){
return new Scaffold(
 appBar : LBAppBar().getAppBar(),
  //drawer: new LBDrawer().getDrawer(),
 body:  Container(
decoration: BoxDecoration(
    gradient: new LinearGradient(
        colors: [Color.fromRGBO(1,89,99, 1.0), Colors.grey],
        begin: Alignment.bottomLeft,
        end: Alignment.topRight
    )
),
 child:
 SwipeDetector(
     onSwipeRight: () {
       Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new WidgetsPage())
        ); },
  child: Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children:[
    Row(
            children: [
          Container(
            margin: EdgeInsets.only(left: 20.0,top: 10.0, bottom: 10.0, right:30.0),
            child: Column(
  children: <Widget>[

            Text("Hi ${user.firstName}, Today is " + formatDate(), style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.bold, fontSize: 19.0
 )),

        ],

         ),
                 ),
                  ]
            ),

      Row(
        //ROW 1
        children: [
          Container(
            margin: EdgeInsets.only(left: 30.0,top: 60.0, bottom: 30.0, right:30.0),
            child: Column(
      children: <Widget>[
           GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.checkSquare,
                 size: 50.0,
                 color: Colors.white70,
         ),
              onTap: () {
                        Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CheckIn()));
                      }),
                Text("Check In", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
 ),
              ),
              Container(
           margin: EdgeInsets.only(left: 50.0,top: 60.0, bottom: 30.0, right:30.0),
                child: Column(
      children: <Widget>[
           GestureDetector(

                 child: Icon(
                 FontAwesomeIcons.list,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new DayAtAGlance()));
                      }),
            Text("My Day", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
],
 ),
               ),
            Container(
           margin: EdgeInsets.only(left: 30.0,top: 60.0, bottom: 30.0, right:30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.phone,
                 size: 45.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CommunicationLinks()));
                      }),
              Text("Communication", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
 ),
             ),
             ]
              ),
         Row(//ROW 2
          children: [
        Container(
           margin: EdgeInsets.only(left: 32.0,top: 50.0, bottom: 30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.dollarSign,
                 size: 50.0,
                  color: Colors.white70,
           ),
              onTap: () {
                   Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new Budget()));
                      }),
            Text("Budget", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
],
 ),

              ),
        Container(
           margin: EdgeInsets.only(left: 75.0, top: 50.0, bottom: 30.0, right: 30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.trophy,
                 size: 50.0,
                  color:  Colors.white70,
         ),
              onTap: () {
                    print("Pressed");
                      }),
            Text("Goals", style: new TextStyle( color:  Colors.white70, fontWeight: FontWeight.normal ))
],
),

            ),
         Container(
           margin: EdgeInsets.only(left: 50.0, top: 50.0, bottom: 30.0, right: 20.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.calendar,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {

                   Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CalendarsPage()));
                      }),
            Text("Calendar", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
),
            )
         ]),
      Row(// ROW 3
          children: [
        Container(
           margin: EdgeInsets.only(left: 30.0, top: 50.0, bottom: 30.0, right: 30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.comments,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    print("Pressed");
                      }),
            Text("Community", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
),

            ),
        Container(
           margin: EdgeInsets.only(left: 20.0, top: 50.0, bottom: 30.0, right: 20.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.shoppingCart,
                 size: 50.0,
                 color: Colors.white70,
         ),
              onTap: () {
                     Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new ShoppingList()));
                      }),
            Text("Shopping", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
),

              ),
          Container(
           margin: EdgeInsets.only(left: 50.0, top: 50.0, bottom: 30.0, right: 40.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.solidCheckSquare,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CheckOut()));
                      }),
            Text("Check Out", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.bold ))
],
),

            ),
      ]),
    ],
      ),
   )

 )

   );
</code>```

答:
Try using PageView. You can give it a set of Pages which you can then navigate through by swiping right.

https://api.flutter.dev/flutter/widgets/PageView-class.html

Title: How to detect swipe in flutter

Body:
I've tried using the swipe detector plugin for flutter to achieve navigating to a new screen on swipe right but it's not working, no errors are thrown and the breakpoint is never hit when I debug it. I looked into the GestureDector but I wasn't sure it would work for a swipe right scenario, we want it to navigate to a screen when anywhere on the screen is swiped right.

Here's my code using the plugin

 @override
 Widget build(BuildContext context){
return new Scaffold(
 appBar : LBAppBar().getAppBar(),
  //drawer: new LBDrawer().getDrawer(),
 body:  Container(
decoration: BoxDecoration(
    gradient: new LinearGradient(
        colors: [Color.fromRGBO(1,89,99, 1.0), Colors.grey],
        begin: Alignment.bottomLeft,
        end: Alignment.topRight
    )
),
 child:
 SwipeDetector(
     onSwipeRight: () {
       Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new WidgetsPage())
        ); },
  child: Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children:[
    Row(
            children: [
          Container(
            margin: EdgeInsets.only(left: 20.0,top: 10.0, bottom: 10.0, right:30.0),
            child: Column(
  children: <Widget>[

            Text("Hi ${user.firstName}, Today is " + formatDate(), style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.bold, fontSize: 19.0
 )),

        ],

         ),
                 ),
                  ]
            ),

      Row(
        //ROW 1
        children: [
          Container(
            margin: EdgeInsets.only(left: 30.0,top: 60.0, bottom: 30.0, right:30.0),
            child: Column(
      children: <Widget>[
           GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.checkSquare,
                 size: 50.0,
                 color: Colors.white70,
         ),
              onTap: () {
                        Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CheckIn()));
                      }),
                Text("Check In", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
 ),
              ),
              Container(
           margin: EdgeInsets.only(left: 50.0,top: 60.0, bottom: 30.0, right:30.0),
                child: Column(
      children: <Widget>[
           GestureDetector(

                 child: Icon(
                 FontAwesomeIcons.list,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new DayAtAGlance()));
                      }),
            Text("My Day", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
],
 ),
               ),
            Container(
           margin: EdgeInsets.only(left: 30.0,top: 60.0, bottom: 30.0, right:30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.phone,
                 size: 45.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CommunicationLinks()));
                      }),
              Text("Communication", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
 ),
             ),
             ]
              ),
         Row(//ROW 2
          children: [
        Container(
           margin: EdgeInsets.only(left: 32.0,top: 50.0, bottom: 30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.dollarSign,
                 size: 50.0,
                  color: Colors.white70,
           ),
              onTap: () {
                   Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new Budget()));
                      }),
            Text("Budget", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
],
 ),

              ),
        Container(
           margin: EdgeInsets.only(left: 75.0, top: 50.0, bottom: 30.0, right: 30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.trophy,
                 size: 50.0,
                  color:  Colors.white70,
         ),
              onTap: () {
                    print("Pressed");
                      }),
            Text("Goals", style: new TextStyle( color:  Colors.white70, fontWeight: FontWeight.normal ))
],
),

            ),
         Container(
           margin: EdgeInsets.only(left: 50.0, top: 50.0, bottom: 30.0, right: 20.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.calendar,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {

                   Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CalendarsPage()));
                      }),
            Text("Calendar", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
),
            )
         ]),
      Row(// ROW 3
          children: [
        Container(
           margin: EdgeInsets.only(left: 30.0, top: 50.0, bottom: 30.0, right: 30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.comments,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    print("Pressed");
                      }),
            Text("Community", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
),

            ),
        Container(
           margin: EdgeInsets.only(left: 20.0, top: 50.0, bottom: 30.0, right: 20.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.shoppingCart,
                 size: 50.0,
                 color: Colors.white70,
         ),
              onTap: () {
                     Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new ShoppingList()));
                      }),
            Text("Shopping", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
),

              ),
          Container(
           margin: EdgeInsets.only(left: 50.0, top: 50.0, bottom: 30.0, right: 40.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.solidCheckSquare,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CheckOut()));
                      }),
            Text("Check Out", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.bold ))
],
),

            ),
      ]),
    ],
      ),
   )

 )

   );


问:
How can we add Samsung galaxy skin into android emulator?
I am new to android development, I want to know how can we add Samsung galaxy devices/skin into my emulator?
I can able to add skins of Samsung galaxy but can't see in AVD manager.
I need help to understand this.</p>

答:
Steps to add new skin into your Android Emulator:

Need to download the skin of your desired device, Recommended URL https://developer.samsung.com/galaxy-emulator-skin/galaxy_note_series.html to download

Then unzip this downloaded file, Now copy and paste this to /Users/YourUserName/Library/Android/sdk/platforms/android-29/skins

Launch android studio and open AVD manager

Now we need to add a device definition for that recently added skin

In AVD manager click to this create virtual device option

Now you will see the an option for New Hardware Profile option at the bottom left of this popup.

Click to this New Hardware Profile, you will get a popup for Configure Hardware Profile. Add device and device type then scroll down and you will find an option for Default skin dropdown, Choose your newly added skin

Afterwards press this finish button at the right bottom and you are done with device definition configuration.

Now you can create your own virtual device with this newly added device definition.


问:
Is there a way to collect the following through REST on XtremIO
Is there a way to collect the following through REST on XtremIO?

SNMP

SYSLOG

I can't find that here:

```<code>https://support.emc.com/docu56460_XtremIO-3.0.1,-3.0.2,-3.0.3-and-3.0.5-Storage-Array-RESTful-API-Guide.pdf?language=en_US
</code>```

Is there a newer REST version?

Thanks!

答:
I've found a updated version with all the data I needed:
https://www.dellemc.com/pt-pt/collaterals/unauth/quick-reference-guides/products/storage/docu88753.pdf</p>

Body:
Is there a way to collect the following through REST on XtremIO?

SNMP

SYSLOG

I can't find that here:

https://support.emc.com/docu56460_XtremIO-3.0.1,-3.0.2,-3.0.3-and-3.0.5-Storage-Array-RESTful-API-Guide.pdf?language=en_US

Is there a newer REST version?

Thanks!


问:
Find top parent in hierarchy
I have a SQL table with different project codes. A project can consist of multiple levels (sub-projects). I want to find the top level (top parent) for each of the project codes using SQL coding.

My table looks like this:

```<code>CREATE TABLE #Temp
(
    Child nvarchar(100),
    Parent nvarchar(100)

)

insert into #Temp (Child,Parent)
values
('17210',Null),
('17210-100','17210'),
('17210-100-100','17210-100'),
('1310',Null),
('1310-100','1310'),
('1310-100-100','1310-100')
;

select * from #Temp

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End
</code>```

This is the result I want:

```<code>Child           Parent      TopParent
17210           NULL        17210
17210-100       17210       17210
17210-100-100   17210-100   17210
1310            NULL        1310
1310-100        1310        1310
1310-100-100    1310-100    1310
</code>```

How do I find the top parent for each project number (child)? I have an idea that using recursive CTE's might be the solution, but I am not sure if this is the right approach.

Any help is much appreciated.

答:
I'm not really sure how it's different from any other recursive cte question, but since you've done such a great job posting sample data as DDL+DML I've decided to answer the question anyway (though it could have been just as easily closed as a duplicate).

As you wrote, using a recursive cte is the solution here:

```<code>WITH cte AS
(
    SELECT Child, Parent, Child As TopParent
    FROM #Temp
    WHERE Parent IS NULL
    UNION ALL
    SELECT T.Child, T.Parent, cte.TopParent
    FROM #Temp As T
    JOIN cte
        ON T.Parent = cte.Child
)

SELECT *
FROM cte
ORDER BY TopParent DESC, Parent;
</code>```

Title: Find top parent in hierarchy

Body:
I have a SQL table with different project codes. A project can consist of multiple levels (sub-projects). I want to find the top level (top parent) for each of the project codes using SQL coding.

My table looks like this:

CREATE TABLE #Temp
(
    Child nvarchar(100),
    Parent nvarchar(100)

)

insert into #Temp (Child,Parent)
values
('17210',Null),
('17210-100','17210'),
('17210-100-100','17210-100'),
('1310',Null),
('1310-100','1310'),
('1310-100-100','1310-100')
;

select * from #Temp

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End

This is the result I want:

Child           Parent      TopParent
17210           NULL        17210
17210-100       17210       17210
17210-100-100   17210-100   17210
1310            NULL        1310
1310-100        1310        1310
1310-100-100    1310-100    1310

How do I find the top parent for each project number (child)? I have an idea that using recursive CTE's might be the solution, but I am not sure if this is the right approach.

Any help is much appreciated.

Body:
I'm not really sure how it's different from any other recursive cte question, but since you've done such a great job posting sample data as DDL+DML I've decided to answer the question anyway (though it could have been just as easily closed as a duplicate).

As you wrote, using a recursive cte is the solution here:

WITH cte AS
(
    SELECT Child, Parent, Child As TopParent
    FROM #Temp
    WHERE Parent IS NULL
    UNION ALL
    SELECT T.Child, T.Parent, cte.TopParent
    FROM #Temp As T
    JOIN cte
        ON T.Parent = cte.Child
)

SELECT *
FROM cte
ORDER BY TopParent DESC, Parent;


问:
Configure C++ Google Style in CLion IDE
This is a rather easy matter in IntelliJ (and setting up PEP8 in PyCharm), but I have been googling and I couldn't find a configuration file (I presume in XML or whatever CLion uses) that I could use to configure it to adhere to the Google style guide.

Is this a "future feature" or am I missing something fundamental?

Of course, I can configure it manually, but it's a tedious and time-consuming operation; if someone has already done that, awesome and thanks for sharing!

答: Go to Setting/Preferences | Editor | Code Style | C/C++ then click the button "Set from..." in the top right and select "Google."</p>

Title: Configure C++ Google Style in CLion IDE


问:
Close Command WPF
I have just started learning WPF.  I currently have the MenuItem File -> EXIT on my main window.

I want to know how i should add functionality to the Exit MenuItem.  As i see it there are 3 main choices

1) Add an Event handler to the Click event of the Exit menuitem. Then code the event handler in the window code behind

2) Add a Close command to to Exit menuitem and add a binding in the main window that handles the command.  Again this involves adding code to the window code behind.

3) Add a command to the Exit menuItem that calls a method in the ViewModel.  This removes code from the views code behind, but means the ViewModel needs to hold a reference to the View.

Which approach would best suit this situation?

I don't want to get to hung up on not putting any code at all into the Views code-behind.  However, since this is action only reaaly involves the view, maybe method 1 or 2 would be best.  Any thoughts?

答:
Well I came across the exact same scenario and this is what I did:

Since I'm using MVVMLight Toolkit hence all the ViewModels are created in a centralised location i.e. the ViewModelLocator. This class also contain static properties through which you can access these viewmodels.

Hence I declared an event in the viewmodel as follows:

```<code>public event EventHandler RequestClose;
</code>```

Next I provided an implementation to it in the code-behind file from which I am opening the viewmodel's associated view as follows:

```<code>var view = new NewView();
view.Owner = this;
ViewModelLocator.NewViewViewModelStatic.RequestClose += (s, e) => { view.Close(); };
</code>```

Now whenever I needed to close the view from the viewmodel, I would just call:

```<code>RequestClose(this, new EventArgs());
</code>```

Hope it helps. Kindly let me know, if you have any confusion.

Title: Close Command WPF

Body:
Well I came across the exact same scenario and this is what I did:

Since I'm using MVVMLight Toolkit hence all the ViewModels are created in a centralised location i.e. the ViewModelLocator. This class also contain static properties through which you can access these viewmodels.

Hence I declared an event in the viewmodel as follows:

public event EventHandler RequestClose;

Next I provided an implementation to it in the code-behind file from which I am opening the viewmodel's associated view as follows:

var view = new NewView();
view.Owner = this;
ViewModelLocator.NewViewViewModelStatic.RequestClose += (s, e) => { view.Close(); };

Now whenever I needed to close the view from the viewmodel, I would just call:

RequestClose(this, new EventArgs());

Hope it helps. Kindly let me know, if you have any confusion.


问:
How to fix disable validation in Dynamo-db against null / empty string?
I am trying to push the data to Dynamodb from node JS code.

I am getting the issue like

DynamoDB.DocumentClient should support empty string properties

does anyone knows how to disable validation in DynamoDB ?

答:
2020 May 18 Update:

DynamoDB now supports empty string values for non-key attributes: https://aws.amazon.com/about-aws/whats-new/2020/05/amazon-dynamodb-now-supports-empty-values-for-non-key-string-and-binary-attributes-in-dynamodb-tables/

In order to have consistent behavior, make sure that the client does not have { convertEmptyValues: true }, or else these attributes will be saved as NULL as opposed to an empty string.