问:
net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.EcmaError: ReferenceError: "java" is not defined. (internal#105)
When trying to invoke a JNLP application with Open Web start , I get this stack trace of errors.

net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.EcmaError: ReferenceError: "java" is not defined. (internal#105)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3557)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3535)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:3620)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.name(ScriptRuntime.java:1652)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:3413)
at script.dnsResolve(internal:105)
at script.getResolvedIp(http://uhic.ca.edu/toodeepregression3.pac:569)
at script.FindProxyForURL(http://uhic.ca.edu/toodeepregression3.pac:62)

The script at line 569 is..
internalResolvedIp = dnsResolve(host)

```<code>    if (
            host
            ) {
        // If the user has typed an IP address in the address bar, take it
        // as it is.
        var isIpV4Address = /^(\d+.){3}\d+$/;
        var isIpV6Address = /^\[(.*)\]$/;

        if (
                isIpV4Address.test(host)
                ) {
            internalResolvedIp = host;
        } else {
            var matches = host.match(isIpV6Address);

            if (
                    matches && matches.length === 2
                    ) {
                // Get the address between the square brackets
                internalResolvedIp = matches[1];
            } else if (
                    isDnsResolvingAllowed
                    ) {
                ****internalResolvedIp = dnsResolve(host);****
            }
        }
    }
</code>```

I am not sure what this error is . I have looked at the Open web start logs as well . I have searched far and wide in the itnernet world but I barely get any hits for this error.

答:
You have clearly hit the Bug, I am trying to resolve in OWS for my Team as well. We have been stuck with this issue for 9 months ever since OWS rolled out.
I can explain you what I discovered so far. Infact I sent my sanitized pac-proy to OWS team to identify the issue but they sent it back to me  .
So here is the issue.
OWS has a javascript file in its source code. When you call dnsResolve in your pac-proxy, it invokes the provider of dnsResolve and that implementation is in OWS source code.
Now the dnsResolve call java.net.* package classes internally. This requires Rhino and Java interface to have been stabilized at run time.
OWS is not able to create that interface connection so when javascript tries to call java through the Rhino interface , it can not find java classes since it can not recognize that interface and so comes back to say java not found.
I  and my Team are still analyzing the wireshark logs of error to figure out how we could put a fix into OWS or understand how OWS ,Java and Rhino can be successfully talk to each other in the security sandbox container inside which OWS runs.
I could not give u a solution but a better understanding as to where you would like to put your efforts to make it work for u.</p>

Body:
When trying to invoke a JNLP application with Open Web start , I get this stack trace of errors.

net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.EcmaError: ReferenceError: "java" is not defined. (internal#105)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3557)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3535)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:3620)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.name(ScriptRuntime.java:1652)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:3413)
at script.dnsResolve(internal:105)
at script.getResolvedIp(http://uhic.ca.edu/toodeepregression3.pac:569)
at script.FindProxyForURL(http://uhic.ca.edu/toodeepregression3.pac:62)

The script at line 569 is..
internalResolvedIp = dnsResolve(host)

    if (
            host
            ) {
        // If the user has typed an IP address in the address bar, take it
        // as it is.
        var isIpV4Address = /^(\d+.){3}\d+$/;
        var isIpV6Address = /^\[(.*)\]$/;

        if (
                isIpV4Address.test(host)
                ) {
            internalResolvedIp = host;
        } else {
            var matches = host.match(isIpV6Address);

            if (
                    matches && matches.length === 2
                    ) {
                // Get the address between the square brackets
                internalResolvedIp = matches[1];
            } else if (
                    isDnsResolvingAllowed
                    ) {
                ****internalResolvedIp = dnsResolve(host);****
            }
        }
    }

I am not sure what this error is . I have looked at the Open web start logs as well . I have searched far and wide in the itnernet world but I barely get any hits for this error.


来源: stackexchange

问:
Why does passing $null to a parameter with AllowNull() result in an error?
Consider the following code:

```<code>function Test
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory=$true)]
        [AllowNull()]
        [String]
        $ComputerName
    )
    process{}
}

Test -ComputerName $null
</code>```

Based on the official documentation for AllowNull I was expecting that $ComputerName could either be [string] or $null.  However, running the above code results in the following error:

[14,24: Test] Cannot bind argument to parameter 'ComputerName' because it is an empty
  string.

Why doesn't passing $null for $ComputerName work in this case?

答: As noted, when cast to a [string], $null becomes an empty string (""). To avoid this, one option is to type the param as an object - then in the body test first for $null, then check that $MyParam.GetType().Name is "String".</p>

ContentLicense: CC BY-SA 3.0

Body:
Consider the following code:

function Test
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory=$true)]
        [AllowNull()]
        [String]
        $ComputerName
    )
    process{}
}

Test -ComputerName $null

Based on the official documentation for AllowNull I was expecting that $ComputerName could either be [string] or $null.  However, running the above code results in the following error:

[14,24: Test] Cannot bind argument to parameter 'ComputerName' because it is an empty
  string.

Why doesn't passing $null for $ComputerName work in this case?

ContentLicense: CC BY-SA 4.0


问:
Remove even numbers from a vector in c++
can somebody help me with this function: suppose that I need to remove all even numbers from a vector using reference: can I do that? Is the push_back correct or should I use something else?

void evenRemoe(vector<int>& arr) {
    for(int i = 0; i < arr.size(); i++) {
        if(arr[i] % 2 != 0) {
            push_back(arr[i]);
        }
    }
}
```

答:
Using push_back adds elements so that's not going to work.

You can use std::erase_if with a functor, like a lambda or other function acting as a unary predicate, to decide what elements that should be removed.

void evenRemoe(std::vector<int>& arr) {
    std::erase_if(arr, [](int i) { return i % 2 == 0; });
}
```
<p>Prior to C++20 you could implement the erase–remove idiom</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>
void evenRemoe(std::vector<int>& arr) {
    arr.erase(std::remove_if(arr.begin(), arr.end(),
                             [](int i) { return i % 2 == 0; }),
              arr.end());
}
</code>```

Body:
Using push_back adds elements so that's not going to work.

You can use std::erase_if with a functor, like a lambda or other function acting as a unary predicate, to decide what elements that should be removed.

void evenRemoe(std::vector<int>& arr) {
    std::erase_if(arr, [](int i) { return i % 2 == 0; });
}

Prior to C++20 you could implement the erase–remove idiom

#include <algorithm>
void evenRemoe(std::vector<int>& arr) {
    arr.erase(std::remove_if(arr.begin(), arr.end(),
                             [](int i) { return i % 2 == 0; }),
              arr.end());
}


问:
Learning how to structure websites and how to code them
I am in the process of creating a (hopefully large) social media website that will kind of be similar in nature to sites like youtube, facebook, twitter. This will be my first endeavor into web development.

I have investigated the tools that highly trafficked sites have used to engineer their sites, and I would like to use the same tools. From my investigation, I believe Python, Apache, and MySQL will be best suited for our website. Web2Py seems like a good opensource python framework that I could possibly use. I hear its similar ruby on rails but for python, which is a good thing.

My question is, are there any up-to-date videos, books, articles, source code, etc that I should look at to learn about the software architecture of websites, and see how larger and highly trafficked sites  structure and code their software?

I do not want to use any opensource CMS's(like drupal) or restricting web frameworks because I don't want my software to restricted in any way in the far future.

I appreciate any feedback.

Edit
ps.Keep in mind I am not looking for basic programming books, I already know how to pick up languages like ruby, python, etc on the fly.
I am more interested in how I should be setting up Architecture of the site(eg. Classes, databases, software) UML graphs would greatly help me as well

答:
Unlike the previous poster, especially if you are new to web development and do not have extensive programming background, I would recommend that you try WEB2PY.

It is very well documented and is very, very easy to install and run out of the box with sufficient examples included to put you ahead of the pack.

Yes, you will have to learn Python and yes, that is probably a good thing.

Bear in mind that I am writing this about 9 months after the previous poster gave his answer and I am not sure what was the state of web2py at that time.

Anyway, give it a try.  You will get web2py working faster than either Django or RoR without a shadow of a doubt.

ContentLicense: CC BY-SA 2.5


答:
No, push_back() is not the correct thing to use.  That is meant for adding values, not removing them.

Also, your code is actually looking for odd values, not even values.

You can use std::vector::erase() to remove individual values, eg:

void evenRemoe(vector<int>& arr){
    for(size_t i = 0; i < arr.size();){
        if (arr[i] % 2 == 0){
            arr.erase(arr.begin()+i);
        }else{
            ++i;
        }
    }
}
```
<p>Alternatively, consider using the Erase-Remove idiom via <code>std::remove_if()</code> and <code>std::vector::erase()</code>, eg:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>

void evenRemoe(vector<int>& arr){
    arr.erase(
        std::remove_if(arr.begin(), arr.end(),
            [](int value){ return (value % 2) == 0; }
        ),
        arr.end()
    );
}
</code>```

Or, in C++20, via std::erase_if(), eg:

void evenRemoe(vector<int>& arr){
    std::erase_if(arr,
        [](int value){ return (value % 2) == 0; }
    );
}
```

Title: Remove even numbers from a vector in c++

Body:
can somebody help me with this function: suppose that I need to remove all even numbers from a vector using reference: can I do that? Is the push_back correct or should I use something else?

void evenRemoe(vector<int>& arr) {
    for(int i = 0; i < arr.size(); i++) {
        if(arr[i] % 2 != 0) {
            push_back(arr[i]);
        }
    }
}

Body:
No, push_back() is not the correct thing to use.  That is meant for adding values, not removing them.

Also, your code is actually looking for odd values, not even values.

You can use std::vector::erase() to remove individual values, eg:

void evenRemoe(vector<int>& arr){
    for(size_t i = 0; i < arr.size();){
        if (arr[i] % 2 == 0){
            arr.erase(arr.begin()+i);
        }else{
            ++i;
        }
    }
}

Alternatively, consider using the Erase-Remove idiom via std::remove_if() and std::vector::erase(), eg:

#include <algorithm>

void evenRemoe(vector<int>& arr){
    arr.erase(
        std::remove_if(arr.begin(), arr.end(),
            [](int value){ return (value % 2) == 0; }
        ),
        arr.end()
    );
}

Or, in C++20, via std::erase_if(), eg:

void evenRemoe(vector<int>& arr){
    std::erase_if(arr,
        [](int value){ return (value % 2) == 0; }
    );
}


问:
Celery beat sends the same task twice to the worker on every interval
I have the following scheduled task in example_app -> tasks.py:

```<code>@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):

    sender.add_periodic_task(
        crontab(minute='*/1'),
        test.s(),
    )

@app.task
def test():
    print('test')
</code>```

However this scheduled task is executed twice every minute:

```<code>celery_1       | [2022-02-08 16:53:00,044: INFO/MainProcess] Task example_app.tasks.test[a608d307-0ef8-4230-9586-830d0d900e67] received
celery_1       | [2022-02-08 16:53:00,046: INFO/MainProcess] Task example_app.tasks.test[5d5141cc-dcb5-4608-b115-295293c619a9] received
celery_1       | [2022-02-08 16:53:00,046: WARNING/ForkPoolWorker-6] test
celery_1       | [2022-02-08 16:53:00,047: WARNING/ForkPoolWorker-7] test
celery_1       | [2022-02-08 16:53:00,048: INFO/ForkPoolWorker-6] Task example_app.tasks.test[a608d307-0ef8-4230-9586-830d0d900e67] succeeded in 0.0014668999938294291s: None
celery_1       | [2022-02-08 16:53:00,048: INFO/ForkPoolWorker-7] Task example_app.tasks.test[5d5141cc-dcb5-4608-b115-295293c619a9] succeeded in 0.001373599996441044s: None
</code>```

I read that this can be caused when you change django timezone from UTC, which I have done on this project.  I tried this solution from another question but it doesn't stop the duplication:

```<code>from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.base')

class MyCeleryApp(Celery):
    def now(self):
        """Return the current time and date as a datetime."""
        from datetime import datetime
        return datetime.now(self.timezone)

app = MyCeleryApp('tasks')

app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
</code>```

settings:

```<code>CELERY_BROKER_URL = "redis://redis:6379/0"
CELERY_RESULT_BACKEND = "redis://redis:6379/0"
</code>```

running in docker:

```<code>
    celery:
        restart: always
        build:
          context: .
        command: celery --app=config.celery worker -l info
        depends_on:
          - db
          - redis
          - django

    celery-beat:
        restart: always
        build:
          context: .
        command: celery --app=config.celery beat -l info
        depends_on:
          - db
          - redis
          - django
</code>```

have also tried docker like this:

```<code>    celery:
        restart: always
        build:
          context: .
        command: celery --app=config.celery worker -B -l info
        depends_on:
          - db
          - redis
          - django
</code>```

with same result.

Not sure what is causing this.

答:
In case it helps anyone else, I solved the problem by removing the periodic task from tasks.py and defining it in settings.  So the files look like this:
tasks.py

```<code>@app.task
def test():
    print('test')
</code>```

settings.py

```<code>CELERY_BEAT_SCHEDULE = {
    "test-task": {
        "task": "example_app.tasks.test",
        "args": (),
        "schedule": crontab(),
    }
}
</code>```

Not sure what was wrong with my previous setup as I thought it was inline with the docs.

Body:
I have the following scheduled task in example_app -> tasks.py:

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):

    sender.add_periodic_task(
        crontab(minute='*/1'),
        test.s(),
    )

@app.task
def test():
    print('test')

However this scheduled task is executed twice every minute:

celery_1       | [2022-02-08 16:53:00,044: INFO/MainProcess] Task example_app.tasks.test[a608d307-0ef8-4230-9586-830d0d900e67] received
celery_1       | [2022-02-08 16:53:00,046: INFO/MainProcess] Task example_app.tasks.test[5d5141cc-dcb5-4608-b115-295293c619a9] received
celery_1       | [2022-02-08 16:53:00,046: WARNING/ForkPoolWorker-6] test
celery_1       | [2022-02-08 16:53:00,047: WARNING/ForkPoolWorker-7] test
celery_1       | [2022-02-08 16:53:00,048: INFO/ForkPoolWorker-6] Task example_app.tasks.test[a608d307-0ef8-4230-9586-830d0d900e67] succeeded in 0.0014668999938294291s: None
celery_1       | [2022-02-08 16:53:00,048: INFO/ForkPoolWorker-7] Task example_app.tasks.test[5d5141cc-dcb5-4608-b115-295293c619a9] succeeded in 0.001373599996441044s: None

I read that this can be caused when you change django timezone from UTC, which I have done on this project.  I tried this solution from another question but it doesn't stop the duplication:

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.base')

class MyCeleryApp(Celery):
    def now(self):
        """Return the current time and date as a datetime."""
        from datetime import datetime
        return datetime.now(self.timezone)

app = MyCeleryApp('tasks')

app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

settings:

CELERY_BROKER_URL = "redis://redis:6379/0"
CELERY_RESULT_BACKEND = "redis://redis:6379/0"

running in docker:

    celery:
        restart: always
        build:
          context: .
        command: celery --app=config.celery worker -l info
        depends_on:
          - db
          - redis
          - django

    celery-beat:
        restart: always
        build:
          context: .
        command: celery --app=config.celery beat -l info
        depends_on:
          - db
          - redis
          - django

have also tried docker like this:

    celery:
        restart: always
        build:
          context: .
        command: celery --app=config.celery worker -B -l info
        depends_on:
          - db
          - redis
          - django

with same result.

Not sure what is causing this.

Body:
In case it helps anyone else, I solved the problem by removing the periodic task from tasks.py and defining it in settings.  So the files look like this:
tasks.py

@app.task
def test():
    print('test')

settings.py

CELERY_BEAT_SCHEDULE = {
    "test-task": {
        "task": "example_app.tasks.test",
        "args": (),
        "schedule": crontab(),
    }
}

Not sure what was wrong with my previous setup as I thought it was inline with the docs.


问:
with flask admin tab create user, use the security.database.create_user method to update or create
Im trying to se flask-admin and flask-security-too

and use the Views from flask-admin to administrate the users and its roles

the problem is that, the view from flask-admin is trying to update or create users with a standar db.commit() when the flask-security-too uses the method create_user() or in security.datastore()

so, i havent find a way to override this little error that avoids me to create or edit the erros

by the moment

i have tried

```<code>def form_action(self, form, model, ids):
</code>```

and gives a error that form, model and ids arent posible to use

then i tried

```<code>def update_model(self, form, model, ids):
        try:
            user = security.datastore.find_user(id=ids)
            if user != None:
                username = model.username
                name = model.name
                email = model.email
                password = model.password
                user.username = username
                user.email = email
                user.name = name
                user.password = password
                security.datastore.update_user(user)
                security.datastore.commit()
                flash(f'usuario {user.name} fue editado con exito', 'success')
            else:
                username = model.username
                name = model.name
                email = model.email
                password = model.password
                user.username = username
                user.email = email
                user.name = name
                user.password = password
                security.datastore(user)
                security.datastore.commit()
                flash(f'usuario {user.name} fue editado con exito', 'success')
        except Exception as e:
            print(e)
            flash('ups algo salio mal', 'danger')
</code>```

and it still tries to update the database in the sqlalchemy ay without using the security methods. so it gives a problem in the fs_uniquifier (1048, "Column 'fs_uniquifier' cannot be null")

so any insigth is well apreciated

models.py

```<code>    class RolesUsers(db.Model):
    __tablename__ = 'roles_users'
    __table_args__ = {'extend_existing': True}
    id = db.Column(db.Integer(), primary_key=True)
    user_id = db.Column('user_id', db.Integer(), db.ForeignKey('user.id'))
    role_id = db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))

class Role(db.Model, RoleMixin):
    __tablename__ = 'role'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

    # __str__ is required by Flask-Admin, so we can have human-readable
    # values for the Role when editing a User.
    def __str__(self):
        return self.name

    # __hash__ is required to avoid the exception
    # TypeError: unhashable type: 'Role' when saving a User
    def __hash__(self):
        return hash(self.name)

class User(db.Model, UserMixin):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    username = db.Column(db.String(255), unique=True, nullable=True)
    name = db.Column(db.String(255), nullable=True)
    password = db.Column(db.String(255), nullable=False)
    last_login_at = db.Column(db.DateTime())
    current_login_at = db.Column(db.DateTime())
    last_login_ip = db.Column(db.String(100))
    current_login_ip = db.Column(db.String(100))
    login_count = db.Column(db.Integer)
    active = db.Column(db.Boolean())
    fs_uniquifier = db.Column(db.String(255), unique=True, nullable=False)
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary='roles_users',
                         backref=db.backref('users', lazy='dynamic'))

    def __repr__(self):
        return '<Usuario {}>'.format(self.username)
</code>```

the views.py

```<code>class UserModelView(sqla.ModelView):
    def is_accessible(self):
            return (current_user.is_active and
                    current_user.is_authenticated and
                    current_user.has_role('superuser')
            )
    column_exclude_list = ('password', 'fs_uniquifier', 'email')
    column_default_sort = 'name'
    can_delete = False

    #
    # exclude fileds that im not interested in render
    #
    form_excluded_columns = ('roles', 'last_login_at', 'current_login_at', 'last_login_ip', 'current_login_ip', 'login_count', 'fs_uniquifier', 'confirmed_at', 'password')

    #override the basic form to show fields that i want

    def scaffold_form(self):

        # Start with the standard form as provided by Flask-Admin. We've already told Flask-Admin to exclude the
        # password field from this form.
        form_class = super(UserModelView, self).scaffold_form()

        # Add a password field, naming it "password2" and labeling it "New Password".
        form_class.password2 = PasswordField('Nuevo Password',  [validators.InputRequired(), validators.EqualTo('password3', message='los passwords tienen que coincidir'), validators.Length(min=8, message='el password tiene que tener 8 digitos')])
        form_class.password3 = PasswordField('confirmar password')
        return form_class

    def on_model_change(self, form, model, is_created):

        # If the password field isn't blank...
        if model.password3 == model.password2:
            # ... then encrypt the new password prior to storing it in the database. If the password field is blank,
            # the existing password in the database will be retained.
            model.password = hash_password(model.password2)
        else:
            flash('ups, hay algo mal en el password')

    # add methods to use with flask security too and use the UserMixin of security
    #
    def update_model(self, form, model, ids):
        try:
            user = security.datastore.find_user(id=ids)
            if user != None:
                username = model.username
                name = model.name
                email = model.email
                password = model.password
                user.username = username
                user.email = email
                user.name = name
                user.password = password
                security.datastore.update_user(user)
                security.datastore.commit()
                flash(f'usuario {user.name} fue creado con exito', 'success')
            else:
                username = model.username
                name = model.name
                email = model.email
                password = model.password
                user.username = username
                user.email = email
                user.name = name
                user.password = password
                security.datastore(user)
                security.datastore.commit()
                flash(f'usuario {user.name} fue editado con exito', 'success')
        except Exception as e:
            print(e)
            flash('ups algo salio mal', 'danger')

    @action('activar', 'activar usuarios', 'Seguro que quiere activar este usuario?')
    def activar(self, ids):
        try:
            user = security.datastore.find_user(id=ids)
            security.datastore.activate_user(user)
            security.datastore.commit()
            flash(f'usuario {user.name} fue activado', 'success')
        except Exception as e:
            print(e)
            flash('ups algo salio mal', 'danger')

    @action('desactivar', 'desactivar usuarios', 'Seguro que quiere desactivar este usuario?')
    def desactivar(self, ids):
        try:
            user = security.datastore.find_user(id=ids)
            security.datastore.deactivate_user(user)
            security.datastore.commit()
            flash(f'usuario {user.name} fue desactivado', 'success')
        except Exception as e:
            print(e)
            flash('ups algo salio mal', 'danger')
    @action('cerrar sesion', 'cerrar sesiones', 'Seguro que quieres cerrar todas sus sesiones?')
    def cerrar_sesion(self, ids):
        try:
            user = security.datastore.find_user(id=ids)
            security.datastore.set_uniquifier(user)
            security.datastore.commit()
            flash(f'usuario {user.name} fueron cerradas todas sus sesiones', 'success')
        except Exception as e:
            print(e)
            flash('ups algo salio mal', 'danger')

    def _handle_view(self, name, **kwargs):
        # Override builtin _handle_view in order to redirect users when a view is not accessible.
        if not self.is_accessible():
            if current_user.is_authenticated:
            # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))
</code>```

答:
Your problem is that there is no fs_uniquifier field in your form, and thus it is not set in your user model. It is however required in your SQL table.

There are two different methods you can hook into to add the fs_uniquifier to your user model automatically.

Method 1: When data is passed from the form to the model

This is the method used in flask-react-spa, slightly adjusted.

In views.py:

import uuid

# Import the Baseform from flask_admin...
from flask_admin.form import BaseForm

# extend it ...
class BaseUserForm(BaseForm):

    def populate_obj(self, user):
        super().populate_obj(user)
        if user.fs_uniquifier is None:
            user.fs_uniquifier = uuid.uuid4().hex

# and use the extended BaseForm for your view
class UserModelView(sqla.ModelView):
    form_base_class = BaseUserForm
    ...
```
<p>This will then add a <code>fs_uniquifier</code> to your model if it is missing when you are populating your <code>user</code> object with data from a form.</p>
<p><strong>Method 2: Via the on_model_change event</strong></p>
<p>The second method hooks into the <code>on_model_change</code> event of your view, like you already did for the passwords.</p>
<p>In <code>views.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>import uuid

class UserModelView(sqla.ModelView):

    def on_model_change(self, form, model, is_created):
        if model.fs_uniquifier is None:
            model.fs_uniquifier = uuid.uuid4().hex
        ...
</code>```

This will then add a fs_uniquifier to your model if it is missing when you are changing or creating a new user via the view.

Body:
Im trying to se flask-admin and flask-security-too

and use the Views from flask-admin to administrate the users and its roles

the problem is that, the view from flask-admin is trying to update or create users with a standar db.commit() when the flask-security-too uses the method create_user() or in security.datastore()

so, i havent find a way to override this little error that avoids me to create or edit the erros

by the moment

i have tried

def form_action(self, form, model, ids):

and gives a error that form, model and ids arent posible to use

then i tried

def update_model(self, form, model, ids):
        try:
            user = security.datastore.find_user(id=ids)
            if user != None:
                username = model.username
                name = model.name
                email = model.email
                password = model.password
                user.username = username
                user.email = email
                user.name = name
                user.password = password
                security.datastore.update_user(user)
                security.datastore.commit()
                flash(f'usuario {user.name} fue editado con exito', 'success')
            else:
                username = model.username
                name = model.name
                email = model.email
                password = model.password
                user.username = username
                user.email = email
                user.name = name
                user.password = password
                security.datastore(user)
                security.datastore.commit()
                flash(f'usuario {user.name} fue editado con exito', 'success')
        except Exception as e:
            print(e)
            flash('ups algo salio mal', 'danger')

and it still tries to update the database in the sqlalchemy ay without using the security methods. so it gives a problem in the fs_uniquifier (1048, "Column 'fs_uniquifier' cannot be null")

so any insigth is well apreciated

models.py

    class RolesUsers(db.Model):
    __tablename__ = 'roles_users'
    __table_args__ = {'extend_existing': True}
    id = db.Column(db.Integer(), primary_key=True)
    user_id = db.Column('user_id', db.Integer(), db.ForeignKey('user.id'))
    role_id = db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))

class Role(db.Model, RoleMixin):
    __tablename__ = 'role'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

    # __str__ is required by Flask-Admin, so we can have human-readable
    # values for the Role when editing a User.
    def __str__(self):
        return self.name

    # __hash__ is required to avoid the exception
    # TypeError: unhashable type: 'Role' when saving a User
    def __hash__(self):
        return hash(self.name)

class User(db.Model, UserMixin):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    username = db.Column(db.String(255), unique=True, nullable=True)
    name = db.Column(db.String(255), nullable=True)
    password = db.Column(db.String(255), nullable=False)
    last_login_at = db.Column(db.DateTime())
    current_login_at = db.Column(db.DateTime())
    last_login_ip = db.Column(db.String(100))
    current_login_ip = db.Column(db.String(100))
    login_count = db.Column(db.Integer)
    active = db.Column(db.Boolean())
    fs_uniquifier = db.Column(db.String(255), unique=True, nullable=False)
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary='roles_users',
                         backref=db.backref('users', lazy='dynamic'))

    def __repr__(self):
        return '<Usuario {}>'.format(self.username)

the views.py

class UserModelView(sqla.ModelView):
    def is_accessible(self):
            return (current_user.is_active and
                    current_user.is_authenticated and
                    current_user.has_role('superuser')
            )
    column_exclude_list = ('password', 'fs_uniquifier', 'email')
    column_default_sort = 'name'
    can_delete = False

    #
    # exclude fileds that im not interested in render
    #
    form_excluded_columns = ('roles', 'last_login_at', 'current_login_at', 'last_login_ip', 'current_login_ip', 'login_count', 'fs_uniquifier', 'confirmed_at', 'password')

    #override the basic form to show fields that i want

    def scaffold_form(self):

        # Start with the standard form as provided by Flask-Admin. We've already told Flask-Admin to exclude the
        # password field from this form.
        form_class = super(UserModelView, self).scaffold_form()

        # Add a password field, naming it "password2" and labeling it "New Password".
        form_class.password2 = PasswordField('Nuevo Password',  [validators.InputRequired(), validators.EqualTo('password3', message='los passwords tienen que coincidir'), validators.Length(min=8, message='el password tiene que tener 8 digitos')])
        form_class.password3 = PasswordField('confirmar password')
        return form_class

    def on_model_change(self, form, model, is_created):

        # If the password field isn't blank...
        if model.password3 == model.password2:
            # ... then encrypt the new password prior to storing it in the database. If the password field is blank,
            # the existing password in the database will be retained.
            model.password = hash_password(model.password2)
        else:
            flash('ups, hay algo mal en el password')

    # add methods to use with flask security too and use the UserMixin of security
    #
    def update_model(self, form, model, ids):
        try:
            user = security.datastore.find_user(id=ids)
            if user != None:
                username = model.username
                name = model.name
                email = model.email
                password = model.password
                user.username = username
                user.email = email
                user.name = name
                user.password = password
                security.datastore.update_user(user)
                security.datastore.commit()
                flash(f'usuario {user.name} fue creado con exito', 'success')
            else:
                username = model.username
                name = model.name
                email = model.email
                password = model.password
                user.username = username
                user.email = email
                user.name = name
                user.password = password
                security.datastore(user)
                security.datastore.commit()
                flash(f'usuario {user.name} fue editado con exito', 'success')
        except Exception as e:
            print(e)
            flash('ups algo salio mal', 'danger')

    @action('activar', 'activar usuarios', 'Seguro que quiere activar este usuario?')
    def activar(self, ids):
        try:
            user = security.datastore.find_user(id=ids)
            security.datastore.activate_user(user)
            security.datastore.commit()
            flash(f'usuario {user.name} fue activado', 'success')
        except Exception as e:
            print(e)
            flash('ups algo salio mal', 'danger')

    @action('desactivar', 'desactivar usuarios', 'Seguro que quiere desactivar este usuario?')
    def desactivar(self, ids):
        try:
            user = security.datastore.find_user(id=ids)
            security.datastore.deactivate_user(user)
            security.datastore.commit()
            flash(f'usuario {user.name} fue desactivado', 'success')
        except Exception as e:
            print(e)
            flash('ups algo salio mal', 'danger')
    @action('cerrar sesion', 'cerrar sesiones', 'Seguro que quieres cerrar todas sus sesiones?')
    def cerrar_sesion(self, ids):
        try:
            user = security.datastore.find_user(id=ids)
            security.datastore.set_uniquifier(user)
            security.datastore.commit()
            flash(f'usuario {user.name} fueron cerradas todas sus sesiones', 'success')
        except Exception as e:
            print(e)
            flash('ups algo salio mal', 'danger')

    def _handle_view(self, name, **kwargs):
        # Override builtin _handle_view in order to redirect users when a view is not accessible.
        if not self.is_accessible():
            if current_user.is_authenticated:
            # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))

Body:
Your problem is that there is no fs_uniquifier field in your form, and thus it is not set in your user model. It is however required in your SQL table.

There are two different methods you can hook into to add the fs_uniquifier to your user model automatically.

Method 1: When data is passed from the form to the model

This is the method used in flask-react-spa, slightly adjusted.

In views.py:

import uuid

# Import the Baseform from flask_admin...
from flask_admin.form import BaseForm

# extend it ...
class BaseUserForm(BaseForm):

    def populate_obj(self, user):
        super().populate_obj(user)
        if user.fs_uniquifier is None:
            user.fs_uniquifier = uuid.uuid4().hex

# and use the extended BaseForm for your view
class UserModelView(sqla.ModelView):
    form_base_class = BaseUserForm
    ...

This will then add a fs_uniquifier to your model if it is missing when you are populating your user object with data from a form.

Method 2: Via the on_model_change event

The second method hooks into the on_model_change event of your view, like you already did for the passwords.

In views.py:

import uuid

class UserModelView(sqla.ModelView):

    def on_model_change(self, form, model, is_created):
        if model.fs_uniquifier is None:
            model.fs_uniquifier = uuid.uuid4().hex
        ...

This will then add a fs_uniquifier to your model if it is missing when you are changing or creating a new user via the view.


问:
Groupby year and month for a column without having indexes in the output
I have a dataset with dates and avarage tempratures
I want to groupby year and month on AVG_TEMP column.

data:

```<code>           DATE      AVG_TEMP
912     1957-07-01     22.2
913     1957-07-02     26.1
914     1957-07-03     25.6
            .
            .
            .

23249   2020-12-30     16.7
23250   2020-12-31     15.6
</code>```

When I do

```<code>pd.DataFrame(data.groupby([data['DATE'].dt.year, data['DATE'].dt.month])['AVG_TEMP'])
</code>```

The output contain the index among with the AVG_TEMP.

```<code>           0                          1

0      (1957, 7)         912 22.2 913 26.1 914 25.6 915 26....
1      (1957, 8)         943 28.3 944 28.9 945 28.9 946 27....
                    .
                    .
                    .
698   (2020, 11)         23190 17.2 23191 16.7 23192 17.8 2319...
699   (2020, 12)         23220 12.2 23221 13.3 23222 13.9 2322...
</code>```

As you can see exept from the AVG_TEMP it returns the index of the row as well.(below I cold the indexes to make it clear).

912 22.2 913 26.1 914 25.6 915 26....

943 28.3 944 28.9 945 28.9 946 27....

23190 17.2 23191 16.7 23192 17.8 2319...

I used as_index=False but the output is worse.

```<code>pd.DataFrame(new_data.groupby([new_data.DATE.dt.year, new_data.DATE.dt.month], as_index=False))
</code>```

The outeput:

```<code>           0                              1

0      (1957, 7)        DATE TAVG 912 22.2 913 26.1 914 25.6 915 26....
1      (1957, 8)        DATE TAVG 943 1957-08-01 28.3 944 ...
                   .
                   .
                   .
</code>```

I try to explain it as much as I can because I can't make my code more reproducible.
What can I do to solve this problem?

答:
I take it you're looking for an answer that doesn't also group all the data into one column.

I think you could simply do this

```<code>data.groupby([data['DATE'].dt.year, data['DATE'].dt.month])['AVG_TEMP']
</code>```

Or if you want to view the output of the operation

```<code>group = data.groupby([data['DATE'].dt.year, data['DATE'].dt.month])['AVG_TEMP']
group.apply(print)
</code>```

Does this solve the problem?

Body:
I have a dataset with dates and avarage tempratures
I want to groupby year and month on AVG_TEMP column.

data:

           DATE      AVG_TEMP
912     1957-07-01     22.2
913     1957-07-02     26.1
914     1957-07-03     25.6
            .
            .
            .

23249   2020-12-30     16.7
23250   2020-12-31     15.6

When I do

pd.DataFrame(data.groupby([data['DATE'].dt.year, data['DATE'].dt.month])['AVG_TEMP'])

The output contain the index among with the AVG_TEMP.

           0                          1

0      (1957, 7)         912 22.2 913 26.1 914 25.6 915 26....
1      (1957, 8)         943 28.3 944 28.9 945 28.9 946 27....
                    .
                    .
                    .
698   (2020, 11)         23190 17.2 23191 16.7 23192 17.8 2319...
699   (2020, 12)         23220 12.2 23221 13.3 23222 13.9 2322...

As you can see exept from the AVG_TEMP it returns the index of the row as well.(below I cold the indexes to make it clear).

912 22.2 913 26.1 914 25.6 915 26....

943 28.3 944 28.9 945 28.9 946 27....

23190 17.2 23191 16.7 23192 17.8 2319...

I used as_index=False but the output is worse.

pd.DataFrame(new_data.groupby([new_data.DATE.dt.year, new_data.DATE.dt.month], as_index=False))

The outeput:

           0                              1

0      (1957, 7)        DATE TAVG 912 22.2 913 26.1 914 25.6 915 26....
1      (1957, 8)        DATE TAVG 943 1957-08-01 28.3 944 ...
                   .
                   .
                   .

I try to explain it as much as I can because I can't make my code more reproducible.
What can I do to solve this problem?

Body:
I take it you're looking for an answer that doesn't also group all the data into one column.

I think you could simply do this

data.groupby([data['DATE'].dt.year, data['DATE'].dt.month])['AVG_TEMP']

Or if you want to view the output of the operation

group = data.groupby([data['DATE'].dt.year, data['DATE'].dt.month])['AVG_TEMP']
group.apply(print)

Does this solve the problem?


问:
Format code to display numbers in millions with trend arrow up or down based on value in Excel
I want to show a variance between two years in millions and cannot figure out the correct format code to show like this:

any help would be great, thanks!

答:
CUSTOM FORMATTING WITH SYMBOLS IN EXCEL

```<code>[Color10] ▲ #,##0.0,,;[Red] ▼ (#,##0.0,,)
</code>```

• STEP 1: Select the column’s variance numbers and press CTRL + 1 to bring up the Format Cells dialogue box

• STEP 2: Select the Custom category and select a number format type – #,##0.0,,;[Red] (#,##0.0,,)

The first section of this code #,##0.0,, is for a positive number, and second code [Red] (#,##0.0,,) is for a negative number.

• STEP 3: Under the Type: area you will need to enter the text [Color10] at the start of the positive value string

• STEP 4: Now select a blank cell and go to Insert --> Symbol --> Font: Arial --> Subset: Geometric Shapes and then Insert the Up-Pointing Triangle ▲ and Insert the Down-Pointing Triangle ▼ and press Cancel

• STEP 5: You will need to copy the triangles, select the variance numbers, press CTRL + 1 and paste the triangles before each positive and negative value string, then press OK

You now have your custom number formats with an upwards triangle for any positive number(s) and a downwards triangle for any negative number(s)

Body:
CUSTOM FORMATTING WITH SYMBOLS IN EXCEL

[Color10] ▲ #,##0.0,,;[Red] ▼ (#,##0.0,,)

• STEP 1: Select the column’s variance numbers and press CTRL + 1 to bring up the Format Cells dialogue box

• STEP 2: Select the Custom category and select a number format type – #,##0.0,,;[Red] (#,##0.0,,)

The first section of this code #,##0.0,, is for a positive number, and second code [Red] (#,##0.0,,) is for a negative number.

• STEP 3: Under the Type: area you will need to enter the text [Color10] at the start of the positive value string

• STEP 4: Now select a blank cell and go to Insert --> Symbol --> Font: Arial --> Subset: Geometric Shapes and then Insert the Up-Pointing Triangle ▲ and Insert the Down-Pointing Triangle ▼ and press Cancel

• STEP 5: You will need to copy the triangles, select the variance numbers, press CTRL + 1 and paste the triangles before each positive and negative value string, then press OK

You now have your custom number formats with an upwards triangle for any positive number(s) and a downwards triangle for any negative number(s)


问:
3D plot of Excel data
I'm trying to recreate this plot using some of my own excel data but I've hit a wall. So far I have:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_excel(r'/path/to/data.xlsx')

yr = df['Year']
jd = df['Jday']
dc = df['Discharge']

x = np.asarray(yr)
y = np.asarray(jd)
z = np.asarray(dc)

X,Y,Z = np.meshgrid(x,y,z)

ax = plt.figure().add_subplot(projection='3d')

ax.plot_surface(X,Y,Z, cmap='autumn')

ax.set_xlabel("Year")
ax.set_ylabel("Jday")
ax.set_zlabel("Discharge")

plt.show()
</code>```

But when I run this I get:

```<code>Traceback (most recent call last):
  File "/Users/Desktop/main.py", line 19, in <module>
    ax.plot_surface(X,Y,Z, cmap='autumn')
  File "/Users/venv/lib/python3.10/site-packages/matplotlib/_api/deprecation.py", line 412, in wrapper
    return func(*inner_args, **inner_kwargs)
  File "/Users/venv/lib/python3.10/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1581, in plot_surface
    raise ValueError("Argument Z must be 2-dimensional.")
ValueError: Argument Z must be 2-dimensional.
</code>```

Any help would be appreciated.

EDIT:

I changed my code to:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_excel(r'/path/to/data.xlsx')

yr = df['Year']
jd = df['Jday']
dc = df['Discharge']

X = np.asarray(yr).reshape(-1,2)
Y = np.asarray(jd).reshape(-1,2)
Z = np.asarray(dc).reshape(-1,2)

fig = plt.figure(figsize=(14,8))
ax = plt.axes(projection='3d')

my_cmap = plt.get_cmap('seismic')

surf = ax.plot_surface(X,Y,Z,
                       cmap = my_cmap,
                       edgecolor = 'none')
fig.colorbar(surf, ax=ax,
             shrink = 0.5, aspect = 5)

plt.show()
</code>```

When I run this it produces the following plot:

Which obviously doesn't match the other plot. It seems to be plotting the data from each year in a single line instead of creating filled in polygons which is what I think it's supposed to do. I have a feeling this issue has to do with the .reshape function but I'm not entirely sure.

答:
Note: original answer completely rewritten!

The problem is, as your data stated, that the Z-argument must be two-dimensional. In your problem, you don't need np.meshgrid at all. This is typically used to make a 'grid' of all possible combinations of X/Y, after which you can use these combinations to calculate your response matrix Z. However, since all your data is read in, it is merely a reshaping of all 1d-arrays to 2d-arrays:

target_shape = (np.sqrt(X.shape[0]),-1)
X = np.reshape(X, target_shape)
Y = np.reshape(Y, target_shape)
Z = np.reshape(Z, target_shape)
```

Have a look at the documentation of np.reshape for some more information.

Title: 3D plot of Excel data

Body:
I'm trying to recreate this plot using some of my own excel data but I've hit a wall. So far I have:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_excel(r'/path/to/data.xlsx')

yr = df['Year']
jd = df['Jday']
dc = df['Discharge']

x = np.asarray(yr)
y = np.asarray(jd)
z = np.asarray(dc)

X,Y,Z = np.meshgrid(x,y,z)

ax = plt.figure().add_subplot(projection='3d')

ax.plot_surface(X,Y,Z, cmap='autumn')

ax.set_xlabel("Year")
ax.set_ylabel("Jday")
ax.set_zlabel("Discharge")

plt.show()

But when I run this I get:

Traceback (most recent call last):
  File "/Users/Desktop/main.py", line 19, in <module>
    ax.plot_surface(X,Y,Z, cmap='autumn')
  File "/Users/venv/lib/python3.10/site-packages/matplotlib/_api/deprecation.py", line 412, in wrapper
    return func(*inner_args, **inner_kwargs)
  File "/Users/venv/lib/python3.10/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1581, in plot_surface
    raise ValueError("Argument Z must be 2-dimensional.")
ValueError: Argument Z must be 2-dimensional.

Any help would be appreciated.

EDIT:

I changed my code to:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_excel(r'/path/to/data.xlsx')

yr = df['Year']
jd = df['Jday']
dc = df['Discharge']

X = np.asarray(yr).reshape(-1,2)
Y = np.asarray(jd).reshape(-1,2)
Z = np.asarray(dc).reshape(-1,2)

fig = plt.figure(figsize=(14,8))
ax = plt.axes(projection='3d')

my_cmap = plt.get_cmap('seismic')

surf = ax.plot_surface(X,Y,Z,
                       cmap = my_cmap,
                       edgecolor = 'none')
fig.colorbar(surf, ax=ax,
             shrink = 0.5, aspect = 5)

plt.show()

When I run this it produces the following plot:

Which obviously doesn't match the other plot. It seems to be plotting the data from each year in a single line instead of creating filled in polygons which is what I think it's supposed to do. I have a feeling this issue has to do with the .reshape function but I'm not entirely sure.

Body:
Note: original answer completely rewritten!

The problem is, as your data stated, that the Z-argument must be two-dimensional. In your problem, you don't need np.meshgrid at all. This is typically used to make a 'grid' of all possible combinations of X/Y, after which you can use these combinations to calculate your response matrix Z. However, since all your data is read in, it is merely a reshaping of all 1d-arrays to 2d-arrays:

target_shape = (np.sqrt(X.shape[0]),-1)
X = np.reshape(X, target_shape)
Y = np.reshape(Y, target_shape)
Z = np.reshape(Z, target_shape)

Have a look at the documentation of np.reshape for some more information.


问:
iPhone UIDocumentInteractionController presentOpenInMenuFromRect cancel button does not respond
I am observing a different behavior when "presentOpenInMenuFromRect" is executed in iPhone4 and iPad2 (both running in iOS 4.3.5). In iPad2 it is shown a drop down list, with all the applications that can open a specific file, and it works fine; however, in iPhone4 it is also shown a drop down list (and also works fine), but at the end of the drop  down list there is the button "Cancel", which seems to be inactive.

In iPad2 this problem does not happen because the button "Cancel" does not appears, only appears the drop down list, and when I tap onto another area different from the drop down list, this list is closed; which is the desired behavior.

What I mean saying that the button "Cancel", in iPhone/iPhone4, seems to be inactive is: When I touch it, then nothing happens! Well, to be more specific, if I touch it several times in a short period or time, then, later than sooner, the button "Cancel" seems to respond (it changes its color from gray to blue) and then the drop down list is really closed; which is the desired behavior.

I am using the "presentOpenInMenuFromRect" in the following way: I have implemented a "Save" button, which by default is hidden; however, in the method "-(void)webViewDidFinishLoad:(UIWebView *)webView" I detect the "path extension" of the URL, and if it has the ".pdf" extension, then I show the "Save" button; that is:

```<code>-  (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if ([[[myWebViewOL.request.URL.absoluteString pathExtension] lowercaseString] isEqualToString:@"pdf"])
    {
        saveFile0L.hidden = NO;
    }
}
</code>```

And the "action" related to the "save" button (saveFile0L) is the following method "saveFile":

```<code>[saveFile0L addTarget:self action:@selector(saveFile) forControlEvents:UIControlEventTouchUpInside];
</code>```

where "saveFile" has the following code:

```<code>- (void) saveFile
{
    //Do not worry about "FileManager" is only a singleton class
    //which I have defined in order to implement some common methods
    //and one of them is "saveFile:(UIWebView*) withUIView:(UIView*)
    [[FileManager sharedInstance] saveFile:myWebView withUIView:self.view];
}
</code>```

And "saveFile:(UIWebView*)myWebView withUIView:(UIView*)self.view" has the following code:

```<code>- (void) saveFile:(UIWebView*)webView withUIView:(UIView*)view
{
    NSString* fileName  = [[NSFileManager defaultManager] displayNameAtPath:webView.request.URL.absoluteString];
    NSURL* fileurl = [NSURL URLWithString:webView.request.URL.absoluteString];
    NSData* data = [NSData dataWithContentsOfURL:fileurl];
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* docsDirectory = [paths objectAtIndex:0];
    NSString* filePath = [docsDirectory stringByAppendingPathComponent:fileName];
    [data writeToFile:filePath atomically:YES];
    NSURL* url = [NSURL fileURLWithPath:filePath];
    //UIDocInteractionController API gets the list of devices that support the file type
    docController = [UIDocumentInteractionController interactionControllerWithURL:url];
    [docController retain];
    //Note:[docController presentOpenInMenuFromRect:CGRectZero inView:view animated:YES]
    //presents a drop down list of the apps that support the file type,
    //clicking on an item in the list will open that app while passing in the file.
    //Note: [[UIApplication sharedApplication] canOpenURL:fileurl]
    //will return YES if there is an app that can handle the specific file
    BOOL isValid = ([[UIApplication sharedApplication] canOpenURL:fileurl] &&
                    [docController presentOpenInMenuFromRect:CGRectZero inView:view animated:YES]);
    if (!isValid)
    {
        [self showAlertSaveFileError:fileName];
    }
}
</code>```

At present, I do not know how to make work properly the "Cancel" button which only appears in iPhone (not in the iPad) at the end of the drop down list.

Thanks in advance,

答:
It was my fault; finally I could solve the problem.

The mistake was to use "self.view" and passe it as a parameter for the function "presentOpenInMenuFromRect"

[docController presentOpenInMenuFromRect:CGRectZero inView:view animated:YES]

However, this"view" (self.view) was not be the suitable one to handle the touch events; this mistake could be noticed thanks to the following warning, which was shown in the Xcode console:

```<code>2011-08-17 18:12:56.389 MyApplication[287:707] Presenting action sheet clipped by its superview. Some controls might not respond to touches. On iPhone try -[UIActionSheet showFromTabBar:] or -[UIActionSheet showFromToolbar:] instead of -[UIActionSheet showInView:].
</code>```

This message has given to me the clue and I have modified the code in the following way:

The new and right code is:

```<code>- (void) saveFile:(UIWebView*)webView
{
    NSString* fileName  = [[NSFileManager defaultManager]  displayNameAtPath:webView.request.URL.absoluteString];
    #if DEBUG
    NSLog(@"<%p %@: %s line:%d> File name:%@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __PRETTY_FUNCTION__, __LINE__, fileName);
    #endif
    NSURL* fileurl = [NSURL URLWithString:webView.request.URL.absoluteString];
    NSData* data = [NSData dataWithContentsOfURL:fileurl];
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* docsDirectory = [paths objectAtIndex:0];
    NSString* filePath = [docsDirectory stringByAppendingPathComponent:fileName];
    [data writeToFile:filePath atomically:YES];
    NSURL* url = [NSURL fileURLWithPath:filePath];
    //UIDocInteractionController API gets the list of devices that support the file type
    docController = [UIDocumentInteractionController interactionControllerWithURL:url];
    [docController retain]; //Very important, if "retain" is not called, the application crashes
    //Present a drop down list of the apps that support the file type,
    //clicking on an item in the list will open that app while passing in the file.
    BOOL isValid = [docController presentOpenInMenuFromRect:CGRectZero inView:webView animated:YES]; //Using "webView" instead of "self.view"
    if (!isValid)
    {
        [self showAlertSaveFileError:fileName]; //Shows an alert message
    }
}
</code>```

That is, passing to method "presentOpenInMenuFromRect: inView: animated:" the view "webView" (which is a UIWebView), instead of "self.view".

Body:
I am observing a different behavior when "presentOpenInMenuFromRect" is executed in iPhone4 and iPad2 (both running in iOS 4.3.5). In iPad2 it is shown a drop down list, with all the applications that can open a specific file, and it works fine; however, in iPhone4 it is also shown a drop down list (and also works fine), but at the end of the drop  down list there is the button "Cancel", which seems to be inactive.

In iPad2 this problem does not happen because the button "Cancel" does not appears, only appears the drop down list, and when I tap onto another area different from the drop down list, this list is closed; which is the desired behavior.

What I mean saying that the button "Cancel", in iPhone/iPhone4, seems to be inactive is: When I touch it, then nothing happens! Well, to be more specific, if I touch it several times in a short period or time, then, later than sooner, the button "Cancel" seems to respond (it changes its color from gray to blue) and then the drop down list is really closed; which is the desired behavior.

I am using the "presentOpenInMenuFromRect" in the following way: I have implemented a "Save" button, which by default is hidden; however, in the method "-(void)webViewDidFinishLoad:(UIWebView *)webView" I detect the "path extension" of the URL, and if it has the ".pdf" extension, then I show the "Save" button; that is:

-  (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if ([[[myWebViewOL.request.URL.absoluteString pathExtension] lowercaseString] isEqualToString:@"pdf"])
    {
        saveFile0L.hidden = NO;
    }
}

And the "action" related to the "save" button (saveFile0L) is the following method "saveFile":

[saveFile0L addTarget:self action:@selector(saveFile) forControlEvents:UIControlEventTouchUpInside];

where "saveFile" has the following code:

- (void) saveFile
{
    //Do not worry about "FileManager" is only a singleton class
    //which I have defined in order to implement some common methods
    //and one of them is "saveFile:(UIWebView*) withUIView:(UIView*)
    [[FileManager sharedInstance] saveFile:myWebView withUIView:self.view];
}

And "saveFile:(UIWebView*)myWebView withUIView:(UIView*)self.view" has the following code:

- (void) saveFile:(UIWebView*)webView withUIView:(UIView*)view
{
    NSString* fileName  = [[NSFileManager defaultManager] displayNameAtPath:webView.request.URL.absoluteString];
    NSURL* fileurl = [NSURL URLWithString:webView.request.URL.absoluteString];
    NSData* data = [NSData dataWithContentsOfURL:fileurl];
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* docsDirectory = [paths objectAtIndex:0];
    NSString* filePath = [docsDirectory stringByAppendingPathComponent:fileName];
    [data writeToFile:filePath atomically:YES];
    NSURL* url = [NSURL fileURLWithPath:filePath];
    //UIDocInteractionController API gets the list of devices that support the file type
    docController = [UIDocumentInteractionController interactionControllerWithURL:url];
    [docController retain];
    //Note:[docController presentOpenInMenuFromRect:CGRectZero inView:view animated:YES]
    //presents a drop down list of the apps that support the file type,
    //clicking on an item in the list will open that app while passing in the file.
    //Note: [[UIApplication sharedApplication] canOpenURL:fileurl]
    //will return YES if there is an app that can handle the specific file
    BOOL isValid = ([[UIApplication sharedApplication] canOpenURL:fileurl] &&
                    [docController presentOpenInMenuFromRect:CGRectZero inView:view animated:YES]);
    if (!isValid)
    {
        [self showAlertSaveFileError:fileName];
    }
}

At present, I do not know how to make work properly the "Cancel" button which only appears in iPhone (not in the iPad) at the end of the drop down list.

Thanks in advance,

Body:
It was my fault; finally I could solve the problem.

The mistake was to use "self.view" and passe it as a parameter for the function "presentOpenInMenuFromRect"

[docController presentOpenInMenuFromRect:CGRectZero inView:view animated:YES]

However, this"view" (self.view) was not be the suitable one to handle the touch events; this mistake could be noticed thanks to the following warning, which was shown in the Xcode console:

2011-08-17 18:12:56.389 MyApplication[287:707] Presenting action sheet clipped by its superview. Some controls might not respond to touches. On iPhone try -[UIActionSheet showFromTabBar:] or -[UIActionSheet showFromToolbar:] instead of -[UIActionSheet showInView:].

This message has given to me the clue and I have modified the code in the following way:

The new and right code is:

- (void) saveFile:(UIWebView*)webView
{
    NSString* fileName  = [[NSFileManager defaultManager]  displayNameAtPath:webView.request.URL.absoluteString];
    #if DEBUG
    NSLog(@"<%p %@: %s line:%d> File name:%@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __PRETTY_FUNCTION__, __LINE__, fileName);
    #endif
    NSURL* fileurl = [NSURL URLWithString:webView.request.URL.absoluteString];
    NSData* data = [NSData dataWithContentsOfURL:fileurl];
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* docsDirectory = [paths objectAtIndex:0];
    NSString* filePath = [docsDirectory stringByAppendingPathComponent:fileName];
    [data writeToFile:filePath atomically:YES];
    NSURL* url = [NSURL fileURLWithPath:filePath];
    //UIDocInteractionController API gets the list of devices that support the file type
    docController = [UIDocumentInteractionController interactionControllerWithURL:url];
    [docController retain]; //Very important, if "retain" is not called, the application crashes
    //Present a drop down list of the apps that support the file type,
    //clicking on an item in the list will open that app while passing in the file.
    BOOL isValid = [docController presentOpenInMenuFromRect:CGRectZero inView:webView animated:YES]; //Using "webView" instead of "self.view"
    if (!isValid)
    {
        [self showAlertSaveFileError:fileName]; //Shows an alert message
    }
}

That is, passing to method "presentOpenInMenuFromRect: inView: animated:" the view "webView" (which is a UIWebView), instead of "self.view".


问:
Docker blocked on NPM install - Socket Timeout
I have a simple Dockerfile which is running node, this is the configuration:

```<code>FROM node:latest

WORKDIR /usr/src/auth-starter-server

COPY ./ ./

RUN npm install

CMD ["sh"]
</code>```

Which is being used on a docker-compose.yml as such:

```<code>version: "3.8"

services:
  # Node Server
  auth-starter-server:
    container_name: server
    restart: unless-stopped
    build: ./
    command: npm run start:live
    working_dir: /usr/src/auth-starter-server
    ports:
      - "5000:5000"
    volumes:
      - ./:/usr/src/auth-starter-server
</code>```

From a day to the other happened I couldn't build the image any longer. It starts without problems,

```<code>Creating network "react-auth-starter_default" with the default driver
Building auth-starter-server
Step 1/5 : FROM node:latest
 ---> 6f7f341ab8b8
Step 2/5 : WORKDIR /usr/src/auth-starter-server
 ---> Using cache
 ---> b25f7c08d3eb
Step 3/5 : COPY ./ ./
 ---> Using cache
 ---> 2a06e76bab32
Step 4/5 : RUN npm install
 ---> Running in 0034d6afa38e
</code>```

but when building with docker-compose up --build (or simply docker build -t auth-starter-server .) it just times out on 'npm install' and it returns the following error:

```<code>npm notice
npm notice New minor version of npm available! 7.0.15 -> 7.3.0
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v7.3.0>
npm notice Run `npm install -g npm@7.3.0` to update!
npm notice
npm ERR! code ERR_SOCKET_TIMEOUT
npm ERR! errno ERR_SOCKET_TIMEOUT
npm ERR! request to https://registry.companyregistry.com/yargs-parser/-/yargs-parser-13.1.2.tgz failed, reason: Socket timeout

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-12-21T15_37_42_509Z-debug.log
ERROR: Service 'auth-starter-server' failed to build : The command '/bin/sh -c npm install' returned a non-zero code: 1
</code>```

Something I noticed is that's not using the official npm registry, even though that hasn't been set up as the default registry. Here the npm configuration (got by running npm config ls -l):

```<code>cli configs
long = true
metrics-registry = "https://registry.npmjs.org/"
scope = ""
user-agent = "npm/6.14.9 node/v15.4.0 darwin x64"

; builtin config undefined
prefix = "/usr/local"

; default values
access = null
allow-same-version = false
also = null
always-auth = false
audit = true
audit-level = "low"
auth-type = "legacy"
before = null
bin-links = true
browser = null
ca = null
cache = "/Users/ale917k/.npm"
cache-lock-retries = 10
cache-lock-stale = 60000
cache-lock-wait = 10000
cache-max = null
cache-min = 10
cafile = undefined
cert = null
cidr = null
color = true
commit-hooks = true
depth = null
description = true
dev = false
dry-run = false
editor = "vi"
engine-strict = false
fetch-retries = 2
fetch-retry-factor = 10
fetch-retry-maxtimeout = 60000
fetch-retry-mintimeout = 10000
force = false
format-package-lock = true
fund = true
git = "git"
git-tag-version = true
global = false
global-style = false
globalconfig = "/usr/local/etc/npmrc"
globalignorefile = "/usr/local/etc/npmignore"
group = 20
ham-it-up = false
heading = "npm"
https-proxy = null
if-present = false
ignore-prepublish = false
ignore-scripts = false
init-author-email = ""
init-author-name = ""
init-author-url = ""
init-license = "ISC"
init-module = "/Users/ale917k/.npm-init.js"
init-version = "1.0.0"
json = false
key = null
legacy-bundling = false
link = false
local-address = undefined
loglevel = "notice"
logs-max = 10
; long = false (overridden)
maxsockets = 50
message = "%s"
; metrics-registry = null (overridden)
node-options = null
node-version = "15.4.0"
noproxy = null
offline = false
onload-script = null
only = null
optional = true
otp = null
package-lock = true
package-lock-only = false
parseable = false
prefer-offline = false
prefer-online = false
; prefix = "/usr/local/Cellar/node/15.4.0" (overridden)
preid = ""
production = false
progress = true
proxy = null
read-only = false
rebuild-bundle = true
registry = "https://registry.npmjs.org/"
rollback = true
save = true
save-bundle = false
save-dev = false
save-exact = false
save-optional = false
save-prefix = "^"
save-prod = false
scope = ""
script-shell = null
scripts-prepend-node-path = "warn-only"
searchexclude = null
searchlimit = 20
searchopts = ""
searchstaleness = 900
send-metrics = false
shell = "/bin/zsh"
shrinkwrap = true
sign-git-commit = false
sign-git-tag = false
sso-poll-frequency = 500
sso-type = "oauth"
strict-ssl = true
tag = "latest"
tag-version-prefix = "v"
timing = false
tmp = "/var/folders/2t/36_q44_s62d1b57hnl0l8khw0000gn/T"
umask = 18
unicode = true
unsafe-perm = true
update-notifier = true
usage = false
user = 0
; user-agent = "npm/{npm-version} node/{node-version} {platform} {arch} {ci}" (overridden)
userconfig = "/Users/ale917k/.npmrc"
version = false
versions = false
viewer = "man"
</code>```

Can it be the reason why it stopped building is because it's pointing to the wrong registry? And if so, how can that be fixed?

Bit on a side, I noticed as well that warning regarding the npm update; How can I update the npm package inside a docker image?

Any answer is highly appreciated, so thank you for your inputs!

答:
i have the same issue with Dockerfile node base image version 16, so downgrade to 14 solve the problem
instead of "node:latest" use "node:14"</p>

Body:
I have a simple Dockerfile which is running node, this is the configuration:

FROM node:latest

WORKDIR /usr/src/auth-starter-server

COPY ./ ./

RUN npm install

CMD ["sh"]

Which is being used on a docker-compose.yml as such:

version: "3.8"

services:
  # Node Server
  auth-starter-server:
    container_name: server
    restart: unless-stopped
    build: ./
    command: npm run start:live
    working_dir: /usr/src/auth-starter-server
    ports:
      - "5000:5000"
    volumes:
      - ./:/usr/src/auth-starter-server

From a day to the other happened I couldn't build the image any longer. It starts without problems,

Creating network "react-auth-starter_default" with the default driver
Building auth-starter-server
Step 1/5 : FROM node:latest
 ---> 6f7f341ab8b8
Step 2/5 : WORKDIR /usr/src/auth-starter-server
 ---> Using cache
 ---> b25f7c08d3eb
Step 3/5 : COPY ./ ./
 ---> Using cache
 ---> 2a06e76bab32
Step 4/5 : RUN npm install
 ---> Running in 0034d6afa38e

but when building with docker-compose up --build (or simply docker build -t auth-starter-server .) it just times out on 'npm install' and it returns the following error:

npm notice
npm notice New minor version of npm available! 7.0.15 -> 7.3.0
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v7.3.0>
npm notice Run `npm install -g npm@7.3.0` to update!
npm notice
npm ERR! code ERR_SOCKET_TIMEOUT
npm ERR! errno ERR_SOCKET_TIMEOUT
npm ERR! request to https://registry.companyregistry.com/yargs-parser/-/yargs-parser-13.1.2.tgz failed, reason: Socket timeout

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-12-21T15_37_42_509Z-debug.log
ERROR: Service 'auth-starter-server' failed to build : The command '/bin/sh -c npm install' returned a non-zero code: 1

Something I noticed is that's not using the official npm registry, even though that hasn't been set up as the default registry. Here the npm configuration (got by running npm config ls -l):

cli configs
long = true
metrics-registry = "https://registry.npmjs.org/"
scope = ""
user-agent = "npm/6.14.9 node/v15.4.0 darwin x64"

; builtin config undefined
prefix = "/usr/local"

; default values
access = null
allow-same-version = false
also = null
always-auth = false
audit = true
audit-level = "low"
auth-type = "legacy"
before = null
bin-links = true
browser = null
ca = null
cache = "/Users/ale917k/.npm"
cache-lock-retries = 10
cache-lock-stale = 60000
cache-lock-wait = 10000
cache-max = null
cache-min = 10
cafile = undefined
cert = null
cidr = null
color = true
commit-hooks = true
depth = null
description = true
dev = false
dry-run = false
editor = "vi"
engine-strict = false
fetch-retries = 2
fetch-retry-factor = 10
fetch-retry-maxtimeout = 60000
fetch-retry-mintimeout = 10000
force = false
format-package-lock = true
fund = true
git = "git"
git-tag-version = true
global = false
global-style = false
globalconfig = "/usr/local/etc/npmrc"
globalignorefile = "/usr/local/etc/npmignore"
group = 20
ham-it-up = false
heading = "npm"
https-proxy = null
if-present = false
ignore-prepublish = false
ignore-scripts = false
init-author-email = ""
init-author-name = ""
init-author-url = ""
init-license = "ISC"
init-module = "/Users/ale917k/.npm-init.js"
init-version = "1.0.0"
json = false
key = null
legacy-bundling = false
link = false
local-address = undefined
loglevel = "notice"
logs-max = 10
; long = false (overridden)
maxsockets = 50
message = "%s"
; metrics-registry = null (overridden)
node-options = null
node-version = "15.4.0"
noproxy = null
offline = false
onload-script = null
only = null
optional = true
otp = null
package-lock = true
package-lock-only = false
parseable = false
prefer-offline = false
prefer-online = false
; prefix = "/usr/local/Cellar/node/15.4.0" (overridden)
preid = ""
production = false
progress = true
proxy = null
read-only = false
rebuild-bundle = true
registry = "https://registry.npmjs.org/"
rollback = true
save = true
save-bundle = false
save-dev = false
save-exact = false
save-optional = false
save-prefix = "^"
save-prod = false
scope = ""
script-shell = null
scripts-prepend-node-path = "warn-only"
searchexclude = null
searchlimit = 20
searchopts = ""
searchstaleness = 900
send-metrics = false
shell = "/bin/zsh"
shrinkwrap = true
sign-git-commit = false
sign-git-tag = false
sso-poll-frequency = 500
sso-type = "oauth"
strict-ssl = true
tag = "latest"
tag-version-prefix = "v"
timing = false
tmp = "/var/folders/2t/36_q44_s62d1b57hnl0l8khw0000gn/T"
umask = 18
unicode = true
unsafe-perm = true
update-notifier = true
usage = false
user = 0
; user-agent = "npm/{npm-version} node/{node-version} {platform} {arch} {ci}" (overridden)
userconfig = "/Users/ale917k/.npmrc"
version = false
versions = false
viewer = "man"

Can it be the reason why it stopped building is because it's pointing to the wrong registry? And if so, how can that be fixed?

Bit on a side, I noticed as well that warning regarding the npm update; How can I update the npm package inside a docker image?

Any answer is highly appreciated, so thank you for your inputs!


问:
iText Generated PDF Viewing in IE7
I am generating a pdf using iText. When I open the pdf through the link it does not open in IE 7 but works fine in Chrome. I also noticed if I remove the / from web.xml then it opens perfectly fine in IE 7.
 My security-constraint in web.xml is:

      Entire Application
      /

I have to use the  /* because of security concern.

答: Your browser does not interpret the pdf as an actual pdf. Try to trick it by adding .pdf in the url. It happened to me too back in the days..</p>

Title: iText Generated PDF Viewing in IE7


问:
SQL ignore parenthesis in name field for ORDER BY
I would like rows returned in a MySQL query to be sorted alphabetically by surname for which I have an SQL query like:

```<code>SELECT
  id,
  substring_index(name, ' ', -1) as surname
FROM
  my_table
ORDER BY
  surname asc
</code>```

However, some names have parenthesis to denote some special circumstance such as: Laura Angel (retired)

How can I modify my SQL above to ignore the parenthesised text, to sort by surname alphabetically?

答:
Try with nested replaces to remove the parentheses.

```<code>SELECT
  id,
  substring_index(name, ' ', -1) as surname
ORDER BY
REPLACE( REPLACE( surname  , '(' , '') , ')' , '') ASC;
</code>```

Test and modify according to you version of SQL.
Not tested.

Body:
I would like rows returned in a MySQL query to be sorted alphabetically by surname for which I have an SQL query like:

SELECT
  id,
  substring_index(name, ' ', -1) as surname
FROM
  my_table
ORDER BY
  surname asc

However, some names have parenthesis to denote some special circumstance such as: Laura Angel (retired)

How can I modify my SQL above to ignore the parenthesised text, to sort by surname alphabetically?

Body:
Try with nested replaces to remove the parentheses.

SELECT
  id,
  substring_index(name, ' ', -1) as surname
ORDER BY
REPLACE( REPLACE( surname  , '(' , '') , ')' , '') ASC;

Test and modify according to you version of SQL.
Not tested.


问:
React-native animation lagging on android
I'm using the Reanimated library(2.2.0), and I have a fairly simple animation to expand a Animated.View , that I call when pressing a TouchableOpacity:

```<code>    height.value = withTiming(calculatedHeight, {
      duration: 300,
      easing: Easing.inOut(Easing.ease),
    });
</code>```

On IOS is running very nice on 60fps, but on some Android phones like Samsung S20,S21 Ultra, the animation is lagging a lot. I tried it on an older Samsung(A5) and on it is running fine again. Any suggestions are appreciated.

答: Animate the Y scale instead of the height. left top width height are slow</p>

Body:
I'm using the Reanimated library(2.2.0), and I have a fairly simple animation to expand a Animated.View , that I call when pressing a TouchableOpacity:

    height.value = withTiming(calculatedHeight, {
      duration: 300,
      easing: Easing.inOut(Easing.ease),
    });

On IOS is running very nice on 60fps, but on some Android phones like Samsung S20,S21 Ultra, the animation is lagging a lot. I tried it on an older Samsung(A5) and on it is running fine again. Any suggestions are appreciated.


问:
Confusion about this pointer and callback functions
Let's say I have the following scenario where I define a callback function m_deleter.

```<code>
class B {
public:
    B() = default;
    ~B(){
        if (m_deleter) {
            m_deleter();
        }
    }

    std::function<void()> m_deleter = nullptr;
};

class A {
public:
    void createB(B& b) {
        auto func = [this]() {
            this->printMessage();
        };

        b.m_deleter = func;
    }

    void printMessage() {
        std::cout << "Here is the message!" << std::endl;
    }
};
</code>```

And here is our main function:

```<code>int main() {
    B b;

    {
        A a;
        a.createB(b);
    } // a falls out of scope.

}
</code>```

Here is my confusion. When the stack instance a falls out of scope, is the memory not deallocated? How can the this pointer, used here in the callback: this->printMessage(); still point to a valid object?

When I run the above program, it prints:
Here is the message!

Edit:
Follow up question, is there any way for b to know that a has fallen out of scope and is no longer a valid object, and therefore should not call the callback?

答:
When the stack instance a falls out of scope, is the memory not deallocated?

The storage duration has ended. The compiler is free to use its memory for other objects.

How can the this pointer, used here in the callback

It can't be used. Attempting to use it will result in undefined behaviour.

still point to a valid object?

It doesn't point to a valid object.

Edit: Follow up question, is there any way for b to know that a has fallen out of scope

You know that it has fallen out of scope by virtue of knowing that the program has exited the scope. There is no general way to test within the program, whether an object has been destroyed or not. You could enable certain tools such as undefined behaviour sanitiser and address sanitiser, which will terminate the program and tell you that you've attempted to use an invalid pointer.

What you must do, is structure the program in such way that it becomes impossible for the pointer to become invalid until it's no longer being used. It's not a trivial task, but it is achievable by following safe patterns, and by paying close attention when ever you use indirection.

Body:
Let's say I have the following scenario where I define a callback function m_deleter.

class B {
public:
    B() = default;
    ~B(){
        if (m_deleter) {
            m_deleter();
        }
    }

    std::function<void()> m_deleter = nullptr;
};

class A {
public:
    void createB(B& b) {
        auto func = [this]() {
            this->printMessage();
        };

        b.m_deleter = func;
    }

    void printMessage() {
        std::cout << "Here is the message!" << std::endl;
    }
};

And here is our main function:

int main() {
    B b;

    {
        A a;
        a.createB(b);
    } // a falls out of scope.

}

Here is my confusion. When the stack instance a falls out of scope, is the memory not deallocated? How can the this pointer, used here in the callback: this->printMessage(); still point to a valid object?

When I run the above program, it prints:
Here is the message!

Edit:
Follow up question, is there any way for b to know that a has fallen out of scope and is no longer a valid object, and therefore should not call the callback?


问:
SSIS package: Method not found Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient
SSIS package

Method not found: 'Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient Microsoft.DataTransfer.Runtime.AzureBlobConnectorHelper.CreateBlobClient(System.Collections.Generic.IDictionary`2<System.String,System.Object>)

I have installed Azure Feature Pack for Integration Services (SSIS).. .but it still throws the above error while trying to run the package to download files from Blob Storage

答:
Just Need to Change the Target Server to 2016 in the project properties of the SSIS, it should be sufficient and to address the TLS issue , instead of downgrading to lower version and which is not safe as per the Microsoft recommendations.
We can follow these 2 simple steps to just upgrade .Net Version to circumvent the TLS downgrade.

Use TLS 1.2
The TLS version used by Azure Feature Pack follows system .NET Framework settings. To use TLS 1.2, add a REG_DWORD value named SchUseStrongCrypto with data 1 under the following two registry keys.

HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft.NETFramework\v4.0.30319
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework\v4.0.30319


问:
Is this the proper way to get the end of day in PHP?
I'm getting the End Of Day like this:

```<code>function endofday($date_to_change)
{
  $date_to_change = date('Y-m-d');
  $date_to_change = date('Y-m-d H:i:s', strtotime("+23 hours 59 minutes  59 seconds", strtotime($date_to_change)));
  return date("Y-m-d H:i:s", $date_to_change);
}
</code>```

It works but is this the proper and most efficient way to get 23:59:59 from a date? My goal is to select rows from a mysql database between 00:00:00 and 23:59:59 from a date passed in with or without time.

答:
This could potentially be another solution.</p>
```<code>$today = new \DateTime('midnight today');
$endOfDay = (new \DateTime('midnight tomorrow'));
var_dump($today < $endOfDay);

var_dump($today->format('Y-m-d H:i:s')); // 2022-02-08 00:00:00
var_dump($endOfDay->format('Y-m-d H:i:s')); // 2022-02-09 00:00:00
</code>```

Body:
I'm getting the End Of Day like this:

function endofday($date_to_change)
{
  $date_to_change = date('Y-m-d');
  $date_to_change = date('Y-m-d H:i:s', strtotime("+23 hours 59 minutes  59 seconds", strtotime($date_to_change)));
  return date("Y-m-d H:i:s", $date_to_change);
}

It works but is this the proper and most efficient way to get 23:59:59 from a date? My goal is to select rows from a mysql database between 00:00:00 and 23:59:59 from a date passed in with or without time.

Body:
This could potentially be another solution.

$today = new \DateTime('midnight today');
$endOfDay = (new \DateTime('midnight tomorrow'));
var_dump($today < $endOfDay);

var_dump($today->format('Y-m-d H:i:s')); // 2022-02-08 00:00:00
var_dump($endOfDay->format('Y-m-d H:i:s')); // 2022-02-09 00:00:00


问:
how to detect events in a html page embedded inside another html page?
I am working on a website which has an html page embedded inside the html page using iframe tag.

I need to capture an event in the inner html page (when a login event takes place) from the outer html page. How can i do that?

答:
This works on the same domain, I'm not sure it will work for the content from another domain though:

```<code>window.frames[0].document.getElementById("myElementId").onclick = function(){
        alert("Testing...")
}
</code>```

assume that the element with an id myElementId is in the iframe.

Body:
This works on the same domain, I'm not sure it will work for the content from another domain though:

window.frames[0].document.getElementById("myElementId").onclick = function(){
        alert("Testing...")
}

assume that the element with an id myElementId is in the iframe.


答:
push_back is a method of std::vector for appending an element to the end of the vector, not removing. What you need is one of the erase methods.

However, you should be careful while erasing elements of the vector you're iterating over. Care must be taken to avoid incrementing the index when you remove the element.

The better way to do this is to use std::remove_if algorithm instead of iterating the vector yourself.

```<code>void evenRemove(vector<int>& arr) {
    auto it = std::remove_if(arr.begin(), arr.end(),
        [](int n) { return (n % 2) == 0; });
    arr.erase(it, arr.end());
}
</code>```

Despite the name, std::remove_if doesn't actually remove any elements from the vector. Instead, it moves the elements that match the predicate (in our case - all even integers) to the end of the vector and returns an iterator pointing to the first of such elements. Therefore, to actually remove the elements you need to call erase with the iterators denoting the tail of the vector that contains the even integers.

Body:
can somebody help me with this function: suppose that I need to remove all even numbers from a vector using reference: can I do that? Is the push_back correct or should I use something else?

void evenRemoe(vector<int>& arr) {
    for(int i = 0; i < arr.size(); i++) {
        if(arr[i] % 2 != 0) {
            push_back(arr[i]);
        }
    }
}

Body:
push_back is a method of std::vector for appending an element to the end of the vector, not removing. What you need is one of the erase methods.

However, you should be careful while erasing elements of the vector you're iterating over. Care must be taken to avoid incrementing the index when you remove the element.

The better way to do this is to use std::remove_if algorithm instead of iterating the vector yourself.

void evenRemove(vector<int>& arr) {
    auto it = std::remove_if(arr.begin(), arr.end(),
        [](int n) { return (n % 2) == 0; });
    arr.erase(it, arr.end());
}

Despite the name, std::remove_if doesn't actually remove any elements from the vector. Instead, it moves the elements that match the predicate (in our case - all even integers) to the end of the vector and returns an iterator pointing to the first of such elements. Therefore, to actually remove the elements you need to call erase with the iterators denoting the tail of the vector that contains the even integers.


问:
Go json.Unmarshal does not work with type definition of json.RawMessage
I have a small Go program like this:

package main

import "encoding/json"

func main() {
    bs := []byte(`{"items": ["foo", "bar"]}`)

    data := Data{}
    err := json.Unmarshal(bs, &data)
    if err != nil {
        panic(err)
    }
}

type Data struct {
    Items []Raw `json:"items"`
}

// If I do this, this program panics with "illegal base64 data at input byte 0"
type Raw json.RawMessage

// This works
type Raw = json.RawMessage
```

Why does json.Unmarshal work with type alias but not type definition?  What does that error message mean?

答:
This is a new type definition:

```<code>type Raw json.RawMessage
</code>```

The Raw type is derived from json.RawMessage, but it is a new type without any of the methods defined for json.RawMessage. So, if json.RawMessage has a json unmarshaler method, Raw does not have that. Code such as following will not recognize a variable t of type Raw as a json.RawMessage:

```<code>if t, ok:=item.(json.RawMessage); ok {
  ...
}
</code>```

This is a type alias:

```<code>type Raw = json.RawMessage
</code>```

Here, Raw has all the methods json.RawMessage has, and type assertion to json.RawMessage will work, because Raw is simply another name for json.RawMessage.

Body:
I have a small Go program like this:

package main

import "encoding/json"

func main() {
    bs := []byte(`{"items": ["foo", "bar"]}`)

    data := Data{}
    err := json.Unmarshal(bs, &data)
    if err != nil {
        panic(err)
    }
}

type Data struct {
    Items []Raw `json:"items"`
}

// If I do this, this program panics with "illegal base64 data at input byte 0"
type Raw json.RawMessage

// This works
type Raw = json.RawMessage

Why does json.Unmarshal work with type alias but not type definition?  What does that error message mean?

Body:
This is a new type definition:

type Raw json.RawMessage

The Raw type is derived from json.RawMessage, but it is a new type without any of the methods defined for json.RawMessage. So, if json.RawMessage has a json unmarshaler method, Raw does not have that. Code such as following will not recognize a variable t of type Raw as a json.RawMessage:

if t, ok:=item.(json.RawMessage); ok {
  ...
}

This is a type alias:

type Raw = json.RawMessage

Here, Raw has all the methods json.RawMessage has, and type assertion to json.RawMessage will work, because Raw is simply another name for json.RawMessage.