问:
How can I insert element in Recycler View?
I have a problem with RecyclerView.
Every time I try to manage a Rec View for insert or delete or update some element I have to fight with Recycler View and the evil notifyDataSetChange.

I tried with runOnUiThread and everytime this solution is useless.
I tried to call notifyDataSetChange in the Adapter or in the Activity that instance the Rec View.

I really need to know how to make this work everytime to be a little better developer.
I really hope to solve this problem definitely.

This is my new try

```<code>
public class MainActivity extends AppCompatActivity {

    private Button nextTurn;
    private Button submit;
    private EditText name;
    private EditText number;

    private CounterElementAdapter mAdapter;
    private RecyclerView recV;
    private List<CounterElement> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nextTurn = (Button) findViewById(R.id.button2);
        submit = (Button) findViewById(R.id.button);
        name = (EditText) findViewById(R.id.editText);
        number = (EditText) findViewById(R.id.editText2);
        recV = (RecyclerView) findViewById(R.id.recV);

        list = new ArrayList<CounterElement>();

        mAdapter = new CounterElementAdapter(list);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recV.setLayoutManager(mLayoutManager);
        recV.setItemAnimator(new DefaultItemAnimator());
        recV.setAdapter(mAdapter);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(name.getText().toString().length() > 0 && number.getText().toString().length() > 0) {
                    mAdapter.addElement(new CounterElement(name.getText().toString(), Integer.parseInt(number.getText().toString())));
                }
            }
        });

        nextTurn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter.nextTurn();
            }
        });
    }
}

</code>```

```<code>public class CounterElementAdapter extends RecyclerView.Adapter<CounterElementAdapter.MyViewHolder> {

    private List<CounterElement> elementList;

    public class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView name, counter;

        public MyViewHolder(View view) {
            super(view);
            name = view.findViewById(R.id.name);
            counter = view.findViewById(R.id.counter);
        }
    }

    public CounterElementAdapter(List<CounterElement> elementList) {
        this.elementList = elementList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.element, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        CounterElement ce = elementList.get(position);
        holder.name.setText(ce.getName());
        holder.counter.setText(ce.getDuration());
    }

    @Override
    public int getItemCount() {
        return elementList.size();
    }

    public void addElement(CounterElement ce){
        elementList.add(ce);
        notifyDataSetChanged();
    }

    public void nextTurn(){
        for(CounterElement ce : elementList){
            if(ce.getStatus() >= 1)
                ce.setStatus(ce.getStatus() - 1);
            else {
                elementList.remove(elementList.indexOf(ce));
                notifyDataSetChanged();
            }
        }
    }
}
</code>```

Thanks in advance

答:
Looked at your code for a while, didn't seem to find anything wrong,  Are you using an android emulator for testing or a physical device? Sometimes emulators tend to be buggy.
Try initializing your array list with a few dummy values at first and then try to add or remove and see if that helps </p>

Body:
I have a problem with RecyclerView.
Every time I try to manage a Rec View for insert or delete or update some element I have to fight with Recycler View and the evil notifyDataSetChange.

I tried with runOnUiThread and everytime this solution is useless.
I tried to call notifyDataSetChange in the Adapter or in the Activity that instance the Rec View.

I really need to know how to make this work everytime to be a little better developer.
I really hope to solve this problem definitely.

This is my new try

public class MainActivity extends AppCompatActivity {

    private Button nextTurn;
    private Button submit;
    private EditText name;
    private EditText number;

    private CounterElementAdapter mAdapter;
    private RecyclerView recV;
    private List<CounterElement> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nextTurn = (Button) findViewById(R.id.button2);
        submit = (Button) findViewById(R.id.button);
        name = (EditText) findViewById(R.id.editText);
        number = (EditText) findViewById(R.id.editText2);
        recV = (RecyclerView) findViewById(R.id.recV);

        list = new ArrayList<CounterElement>();

        mAdapter = new CounterElementAdapter(list);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recV.setLayoutManager(mLayoutManager);
        recV.setItemAnimator(new DefaultItemAnimator());
        recV.setAdapter(mAdapter);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(name.getText().toString().length() > 0 && number.getText().toString().length() > 0) {
                    mAdapter.addElement(new CounterElement(name.getText().toString(), Integer.parseInt(number.getText().toString())));
                }
            }
        });

        nextTurn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter.nextTurn();
            }
        });
    }
}

public class CounterElementAdapter extends RecyclerView.Adapter<CounterElementAdapter.MyViewHolder> {

    private List<CounterElement> elementList;

    public class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView name, counter;

        public MyViewHolder(View view) {
            super(view);
            name = view.findViewById(R.id.name);
            counter = view.findViewById(R.id.counter);
        }
    }

    public CounterElementAdapter(List<CounterElement> elementList) {
        this.elementList = elementList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.element, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        CounterElement ce = elementList.get(position);
        holder.name.setText(ce.getName());
        holder.counter.setText(ce.getDuration());
    }

    @Override
    public int getItemCount() {
        return elementList.size();
    }

    public void addElement(CounterElement ce){
        elementList.add(ce);
        notifyDataSetChanged();
    }

    public void nextTurn(){
        for(CounterElement ce : elementList){
            if(ce.getStatus() >= 1)
                ce.setStatus(ce.getStatus() - 1);
            else {
                elementList.remove(elementList.indexOf(ce));
                notifyDataSetChanged();
            }
        }
    }
}

Thanks in advance


来源: stackexchange

问:
Getting admin template errors when changed default django user model
Hello I get this errors in log file when open http://127.0.0.1:8000/admin/custom_users/customuser/
I create a custom user model to let my users login by email.
I googled some errors in this log and maybe it is known django bug, but I not find any solution.

```<code>Exception while resolving variable 'errors' in template 'admin/change_list.html'.
Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'NoneType' object has no attribute 'errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [errors] in None
Exception while resolving variable 'show' in template 'admin/change_list.html'.
Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__
    raise KeyError(key)
KeyError: 'show'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 835, in _resolve_lookup
    if isinstance(current, BaseContext) and getattr(type(current), bit):
AttributeError: type object 'RequestContext' has no attribute 'show'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'show'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [show] in [{'True': True, 'False': False, 'None': None, 'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x106d22ea0>>}]
(0.000) SELECT DISTINCT "custom_users_customuser"."email" FROM "custom_users_customuser" ORDER BY "custom_users_customuser"."email" ASC; args=()
Exception while resolving variable 'is_multipart' in template 'admin/change_list.html'.
Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'NoneType' object has no attribute 'is_multipart'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'is_multipart'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [is_multipart] in None
Exception while resolving variable 'non_field_errors' in template 'admin/change_list.html'.
Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'NoneType' object has no attribute 'non_field_errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'non_field_errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [non_field_errors] in None
Exception while resolving variable 'non_field_errors' in template 'admin/change_list.html'.
Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'NoneType' object has no attribute 'non_field_errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'non_field_errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [non_field_errors] in None
"GET /admin/custom_users/customuser/ HTTP/1.1" 200 6810
</code>```

Custom user model from a lot of tutorials from the internet

```<code>from .managers import CustomUserManager

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    is_staff = models.BooleanField(default=False)  # is_staff - can user login to admin dash
    is_active = models.BooleanField(default=False)
    confirmed_on = models.DateTimeField(default=timezone.now)
    confirmed = models.BooleanField(default=False)

    first_name = models.CharField(max_length=200, null=True, blank=True)
    middle_name = models.CharField(max_length=200, null=True, blank=True)
    last_name = models.CharField(max_length=200, null=True, blank=True)
    avatar = models.ImageField(upload_to='uploads/%Y/%m/%d/')

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def __str__(self):
        return self.email

    def get_short_name(self):
        """Returns the short name for the user."""
        return self.email
</code>```

Logging settings

```<code>LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            # exact format is not important, this is the minimum information
            'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'debug.log'),
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}
</code>```

答:
in your settings file, add "django.template" after "django" in "logger" like below:</p>

```<code>'loggers': {
    'django': {
        'handlers': ['file'],
        'level': 'DEBUG',
        'propagate': True,
    },
    'django.template': {
        'handlers': ['file'],
        'level': 'INFO',
        'propagate': True,
    },
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hello I get this errors in log file when open http://127.0.0.1:8000/admin/custom_users/customuser/
I create a custom user model to let my users login by email.
I googled some errors in this log and maybe it is known django bug, but I not find any solution.

Exception while resolving variable 'errors' in template 'admin/change_list.html'.
Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'NoneType' object has no attribute 'errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [errors] in None
Exception while resolving variable 'show' in template 'admin/change_list.html'.
Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__
    raise KeyError(key)
KeyError: 'show'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 835, in _resolve_lookup
    if isinstance(current, BaseContext) and getattr(type(current), bit):
AttributeError: type object 'RequestContext' has no attribute 'show'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'show'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [show] in [{'True': True, 'False': False, 'None': None, 'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x106d22ea0>>}]
(0.000) SELECT DISTINCT "custom_users_customuser"."email" FROM "custom_users_customuser" ORDER BY "custom_users_customuser"."email" ASC; args=()
Exception while resolving variable 'is_multipart' in template 'admin/change_list.html'.
Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'NoneType' object has no attribute 'is_multipart'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'is_multipart'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [is_multipart] in None
Exception while resolving variable 'non_field_errors' in template 'admin/change_list.html'.
Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'NoneType' object has no attribute 'non_field_errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'non_field_errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [non_field_errors] in None
Exception while resolving variable 'non_field_errors' in template 'admin/change_list.html'.
Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'NoneType' object has no attribute 'non_field_errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'non_field_errors'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [non_field_errors] in None
"GET /admin/custom_users/customuser/ HTTP/1.1" 200 6810

Custom user model from a lot of tutorials from the internet

from .managers import CustomUserManager

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    is_staff = models.BooleanField(default=False)  # is_staff - can user login to admin dash
    is_active = models.BooleanField(default=False)
    confirmed_on = models.DateTimeField(default=timezone.now)
    confirmed = models.BooleanField(default=False)

    first_name = models.CharField(max_length=200, null=True, blank=True)
    middle_name = models.CharField(max_length=200, null=True, blank=True)
    last_name = models.CharField(max_length=200, null=True, blank=True)
    avatar = models.ImageField(upload_to='uploads/%Y/%m/%d/')

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def __str__(self):
        return self.email

    def get_short_name(self):
        """Returns the short name for the user."""
        return self.email

Logging settings

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            # exact format is not important, this is the minimum information
            'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'debug.log'),
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

Body:
in your settings file, add "django.template" after "django" in "logger" like below:

'loggers': {
    'django': {
        'handlers': ['file'],
        'level': 'DEBUG',
        'propagate': True,
    },
    'django.template': {
        'handlers': ['file'],
        'level': 'INFO',
        'propagate': True,
    },
}


问:
What is the idiomatic strategy for creating docker container in a build system
I've a somewhat complex project - about a dozen of micro services, a little bit more libraries (shared objects or static), some static folders with html resources. The project has C++ and Python components. The project is ultimately shipped as Docker's images, which are pushed to docker hub as part of the build process.

I'm using cmake to do it all.

I wonder if the community have developed an idiomatic strategy for building the images. In terms of makefile, I'm doing something like:

```<code>main_executable: a.cpp b.cpp
    gcc ...

docker_image: main_executable Dockerfile ... other stuff that gets into the containers
    docker build --tag my_image --file Dockerfile .
</code>```

main_executable is a real file, and dependency check is working great. However, docker_image is a phony target. It represents a docker image somewhere in docker land. As a phony target is is always "out of date", and docker build is always executed, even though the changes in the source don't affect the respective executable. Multiply by dozens of images, it is very time consuming, which I would like to save.

Ideally, I would like to tell make to compare the date of the docker image (maybe with 'docker image inspect') with the dependencies.

I'll be surprised if I'm the first person with this issue. What is your strategy? I'm happy with cmake, but familiar with bunch of others (gradle, Scons, maven) and would switch if required.

答:
It's safe and efficient to blindly re-run docker build as you show.  Because of Docker's image caching, even if it has to run through all of the steps of the Dockerfile, Docker is able to detect that none of the inputs have changed (including that the main_executable is the same file as before) and will skip all of the work, producing an identical image output.

If you still want to skip the rebuild, it's reasonably idiomatic to have the build process generate a real file.  (The GNU Make Manual has an example in a different context.)  This approach works better if you can exhaustively list out all of the files that go into the image build (but this is possible especially if the image mostly consists of a compiled binary).

main_executable: a.cpp b.cpp
        gcc -o $@ ...

# This is a phony convenience target
docker_image: .build.docker

# This is a real file, on success we touch it to update its timestamp
.build.docker: main_executable Dockerfile ...
        docker build --tag my_image --file Dockerfile .
        touch $@

clean:
        rm -f main_executable .build.docker

.PHONY: docker_image clean
```

Body:
I've a somewhat complex project - about a dozen of micro services, a little bit more libraries (shared objects or static), some static folders with html resources. The project has C++ and Python components. The project is ultimately shipped as Docker's images, which are pushed to docker hub as part of the build process.

I'm using cmake to do it all.

I wonder if the community have developed an idiomatic strategy for building the images. In terms of makefile, I'm doing something like:

main_executable: a.cpp b.cpp
    gcc ...

docker_image: main_executable Dockerfile ... other stuff that gets into the containers
    docker build --tag my_image --file Dockerfile .

main_executable is a real file, and dependency check is working great. However, docker_image is a phony target. It represents a docker image somewhere in docker land. As a phony target is is always "out of date", and docker build is always executed, even though the changes in the source don't affect the respective executable. Multiply by dozens of images, it is very time consuming, which I would like to save.

Ideally, I would like to tell make to compare the date of the docker image (maybe with 'docker image inspect') with the dependencies.

I'll be surprised if I'm the first person with this issue. What is your strategy? I'm happy with cmake, but familiar with bunch of others (gradle, Scons, maven) and would switch if required.


问:
How to make flutter widgets adaptive to different screen sizes
I`m using width and height params of Container to determine widget size. but the widget is not adaptive if tested on other devices. I came from native android where i used to use density independent pixels(dp) that is adaptive to any screen size. what is the equivalent to dp in flutter ?
I dont want to use MediaQuery every time to calculate screen width and height.</p>

答:
You can use the SizeBox.expand widget to let your widget expand to take the available space regardless of size documentation

```<code>SizedBox.expand(

  child:MyButton(),
),
</code>```

And if you want to keep an aspect ratio regardless of screen size you can use the AspectRatio widget documentation

```<code>AspectRatio(

 aspectRatio: 3/2,

  child:MyButton(),
),
</code>```

If your widgets are just in a row or column and you want to add weights among them to fill the spaces you can use the Expanded widget

```<code>  Expanded(
            flex: 1,//weight for the widget
            child: Container(
              color: Colors.amber,
              height: 100,
            ),
          )
</code>```

,

Body:
You can use the SizeBox.expand widget to let your widget expand to take the available space regardless of size documentation

SizedBox.expand(

  child:MyButton(),
),

And if you want to keep an aspect ratio regardless of screen size you can use the AspectRatio widget documentation

AspectRatio(

 aspectRatio: 3/2,

  child:MyButton(),
),

If your widgets are just in a row or column and you want to add weights among them to fill the spaces you can use the Expanded widget

  Expanded(
            flex: 1,//weight for the widget
            child: Container(
              color: Colors.amber,
              height: 100,
            ),
          )

,


问:
Trouble implementing a recursive Add method for a Linked-List class
I am required to implement the add method for a linked list class recursively. I cannot get my code to work. This is what I have so far:

class LinkedList:
    def __init__(self):
        self.head = None

    def add(self, val, current_node=0):

        if current_node == 0:
            current_node = self.head

        if current_node is None:
            current_node = Node(val)
        else:
            self.add(self, val, current_node.next)
```

Where have I gone wrong with this implementation?

答:
This is a misuse of recursion. If the length of the linked list is more than the call stack size, the class breaks for no reason. It's also less efficient and less intuitive to write than an iterative implementation.

Having said that, it's common for professors to require algorithms that aren't naturally suited for recursion to be implemented recursively. Playing along, I'd write an inner helper that handles the actual recursion. This avoids the awkward default parameter that can confuse the caller and can enable them to break the function's contract.

```<code>def add(self, val):
    def add_recursively(curr, prev):
        if curr:
            add_recursively(curr.next, curr)
        else:
            if prev:
                prev.next = Node(val)
            else:
                self.head = Node(val)

    add_recursively(self.head, None)
</code>```

The main issue with the original attempt is this:

```<code>if current_node is None:
    current_node = Node(val)
</code>```

Without a reference to the previous node in the chain, current_node isn't actually attached to anything using the above operation, so it just gets garbage collected when the function returns.

If you're allowed to use iteration, this is a more natural approach:

```<code>def add(self, val):
    curr = self.head
    prev = None

    while curr:
        prev, curr = curr, curr.next

    if prev:
        prev.next = Node(val)
    else:
        self.head = Node(val)
</code>```

Here's a minimal, complete usage example:

```<code>class Node:
    def __init__(self, val, next_node=None):
        self.val = val
        self.next = next_node

    def __str__(self):
        return str(self.val)

class LinkedList:
    def __init__(self):
        self.head = None

    def add(self, val):
        curr = self.head
        prev = None

        while curr:
            prev, curr = curr, curr.next

        if prev:
            prev.next = Node(val)
        else:
            self.head = Node(val)

    def __str__(self):
        nodes = []
        curr = self.head

        while curr:
            nodes.append(curr.val)
            curr = curr.next

        return "[" + " -> ".join(nodes) + "]"

if __name__ == "__main__":
    llist = LinkedList()
    llist.add("bananas")
    llist.add("apples")
    llist.add("cranberries")
    print(llist) # => [bananas -> apples -> cranberries]
</code>```

Beyond this, consider keeping a self.tail node reference for your LinkedList class. This would make add operations O(1) instead of O(n).

Body:
I am required to implement the add method for a linked list class recursively. I cannot get my code to work. This is what I have so far:

class LinkedList:
    def __init__(self):
        self.head = None

    def add(self, val, current_node=0):

        if current_node == 0:
            current_node = self.head

        if current_node is None:
            current_node = Node(val)
        else:
            self.add(self, val, current_node.next)

Where have I gone wrong with this implementation?

Body:
This is a misuse of recursion. If the length of the linked list is more than the call stack size, the class breaks for no reason. It's also less efficient and less intuitive to write than an iterative implementation.

Having said that, it's common for professors to require algorithms that aren't naturally suited for recursion to be implemented recursively. Playing along, I'd write an inner helper that handles the actual recursion. This avoids the awkward default parameter that can confuse the caller and can enable them to break the function's contract.

def add(self, val):
    def add_recursively(curr, prev):
        if curr:
            add_recursively(curr.next, curr)
        else:
            if prev:
                prev.next = Node(val)
            else:
                self.head = Node(val)

    add_recursively(self.head, None)

The main issue with the original attempt is this:

if current_node is None:
    current_node = Node(val)

Without a reference to the previous node in the chain, current_node isn't actually attached to anything using the above operation, so it just gets garbage collected when the function returns.

If you're allowed to use iteration, this is a more natural approach:

def add(self, val):
    curr = self.head
    prev = None

    while curr:
        prev, curr = curr, curr.next

    if prev:
        prev.next = Node(val)
    else:
        self.head = Node(val)

Here's a minimal, complete usage example:

class Node:
    def __init__(self, val, next_node=None):
        self.val = val
        self.next = next_node

    def __str__(self):
        return str(self.val)

class LinkedList:
    def __init__(self):
        self.head = None

    def add(self, val):
        curr = self.head
        prev = None

        while curr:
            prev, curr = curr, curr.next

        if prev:
            prev.next = Node(val)
        else:
            self.head = Node(val)

    def __str__(self):
        nodes = []
        curr = self.head

        while curr:
            nodes.append(curr.val)
            curr = curr.next

        return "[" + " -> ".join(nodes) + "]"

if __name__ == "__main__":
    llist = LinkedList()
    llist.add("bananas")
    llist.add("apples")
    llist.add("cranberries")
    print(llist) # => [bananas -> apples -> cranberries]

Beyond this, consider keeping a self.tail node reference for your LinkedList class. This would make add operations O(1) instead of O(n).


问:
Changing the colour of text when printing
I am currently designing a simple game and I am trying to change the colour of specific things I am printing. Already I have downloaded the colorama module and ran my code using a sample I've found online, but this doesn't work (I'll tell the details later). I am aware of a setting within the Python options but this affects the whole text not specific sections. If this helps my computer runs Windows and I am running Python 3.8. Here is the setup code, and then a few lines after is the code I have in a separate file. A few lines after that is the output:</p>

```<code>from setuptools import setup, find_packages

name = 'colorama'
version = '0.1'

def get_long_description(filename):
    readme = join(dirname(__file__), filename)
    return open(readme).read()

setup(
    name=name,
    version=version,
    description="Cross-platform colored terminal text.",
    long_description=get_long_description('README.txt'),
    keywords='color colour terminal text ansi windows crossplatform xplatform',
    author='Jonathan Hartley',
    author_email='tartley@tartley.com',
    url='http://code.google.com/p/colorama/',
    license='BSD',
    packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
    include_package_data=True,
    zip_safe=True,
    install_requires=[
      # -*- Extra requirements: -*-
    ],
    entry_points="""
# -*- Entry points: -*-
    """,
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.6',
        'Topic :: Terminals',
    ]
    # see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
)

import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")

[34mHello World
</code>```

答:
The documentation states that you need to start by calling the init() function

Applications should initialize Colorama using:

```<code>   from colorama import init
   init()
</code>```

which has the following effect

On Windows, calling init() will filter ANSI escape sequences out of any text sent to stdout or stderr, and replace them with equivalent Win32 calls.

which is exactly what you see it's happening to you because you see the [34m in the beginning.

Body:
I am currently designing a simple game and I am trying to change the colour of specific things I am printing. Already I have downloaded the colorama module and ran my code using a sample I've found online, but this doesn't work (I'll tell the details later). I am aware of a setting within the Python options but this affects the whole text not specific sections. If this helps my computer runs Windows and I am running Python 3.8. Here is the setup code, and then a few lines after is the code I have in a separate file. A few lines after that is the output:

from setuptools import setup, find_packages

name = 'colorama'
version = '0.1'

def get_long_description(filename):
    readme = join(dirname(__file__), filename)
    return open(readme).read()

setup(
    name=name,
    version=version,
    description="Cross-platform colored terminal text.",
    long_description=get_long_description('README.txt'),
    keywords='color colour terminal text ansi windows crossplatform xplatform',
    author='Jonathan Hartley',
    author_email='tartley@tartley.com',
    url='http://code.google.com/p/colorama/',
    license='BSD',
    packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
    include_package_data=True,
    zip_safe=True,
    install_requires=[
      # -*- Extra requirements: -*-
    ],
    entry_points="""
# -*- Entry points: -*-
    """,
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.6',
        'Topic :: Terminals',
    ]
    # see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
)

import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")

[34mHello World

Body:
The documentation states that you need to start by calling the init() function

Applications should initialize Colorama using:

   from colorama import init
   init()

which has the following effect

On Windows, calling init() will filter ANSI escape sequences out of any text sent to stdout or stderr, and replace them with equivalent Win32 calls.

which is exactly what you see it's happening to you because you see the [34m in the beginning.


问:
How to omit data in dataframe pandas python
I'm trying to pair opening and closing transactions in a column from each symbol in another column while omitting what I can't pair. All I need to do is omit what I can't pair, but I can't omit that until I can pair things together; no matter how I sort, I will have unnecessary data in my equations.

What you see below is about the fifth different try at this problem.

```<code>import pandas as pd

with open('TastyTrades.csv', 'r') as trade_history:
    trade_reader = pd.read_csv('TastyTrades.csv')
    options_frame = trade_reader.loc[(trade_reader['Instrument Type'] == 'Equity Option')]
    date_frame = options_frame.sort_values(by=['Symbol', 'Date', 'Action'], ascending=True)
    for date_frame['Symbol'] in date_frame:
        if date_frame['Action'] == ['BUY_TO_OPEN' and 'SELL_TO_CLOSE'] or ['SELL_TO_OPEN' and 'BUY_TO_CLOSE']:
            date_frame.to_csv('new_taste.csv')

</code>```

This results in :

```<code>ValueError: Lengths must match to compare

Process finished with exit code 1

</code>```

Even further below is an earlier attempt:

```<code>import pandas as pd

with open('TastyTrades.csv', 'r') as trade_history:
    trade_reader = pd.read_csv('TastyTrades.csv')
    options_frame = trade_reader.loc[(trade_reader['Instrument Type'] == 'Equity Option')]
    date_frame = options_frame.sort_values(by=['Symbol', 'Date', 'Action'], ascending=True)
    close_frame = date_frame[date_frame['Action'].isin(['BUY_TO_OPEN' and 'SELL_TO_CLOSE'] or
                                                       ['SELL_TO_OPEN' and 'BUY_TO_CLOSE'])]

    close_frame.to_csv('new_taste.csv')

</code>```

Which resulted in:

```<code>,Date,Type,Action,Symbol,Instrument Type,Description,Value,Quantity,Average Price,Commissions,Fees,Multiplier,Underlying Symbol,Expiration Date,Strike Price,Call or Put
75,2020-02-05T09:34:42-0500,Trade,SELL_TO_CLOSE,AA    200320P00013000,Equity Option,Sold 1 AA 03/20/20 Put 13.00 @ 0.12,12,1,12.0,0.0,-0.15,100.0,AA,3/20/2020,13.0,PUT
38,2020-02-12T11:58:10-0500,Trade,SELL_TO_CLOSE,AAL   200320P00023000,Equity Option,Sold 1 AAL 03/20/20 Put 23.00 @ 0.09,9,1,9.0,0.0,-0.15,100.0,AAL,3/20/2020,23.0,PUT
166,2020-01-29T09:41:30-0500,Trade,SELL_TO_CLOSE,AAL   200320P00024000,Equity Option,Sold 1 AAL 03/20/20 Put 24.00 @ 0.48,48,1,48.0,0.0,-0.15,100.0,AAL,3/20/2020,24.0,PUT
216,2020-01-13T15:45:09-0500,Trade,SELL_TO_CLOSE,AAPL  200117C00320000,Equity Option,Sold 1 AAPL 01/17/20 Call 320.00 @ 1.86,186,1,186.0,0.0,-0.15,100.0,AAPL,1/17/2020,320.0,CALL
</code>```

As you can see with this example, it's only grabbing SELL_TO_CLOSE.

答:
To understand what's going on try to interpret your plain Python code ['BUY_TO_OPEN' and 'SELL_TO_CLOSE'] or ['SELL_TO_OPEN' and 'BUY_TO_CLOSE'] which is just equal to ['SELL_TO_CLOSE'], try to make filters with logical disjunction:

filter1 = date_frame['Action'].isin(['BUY_TO_OPEN', 'SELL_TO_CLOSE'])
filter2 = date_frame['Action'].isin(['SELL_TO_OPEN', 'BUY_TO_CLOSE'])
date_frame[filter1 | filter2]
```

Body:
I'm trying to pair opening and closing transactions in a column from each symbol in another column while omitting what I can't pair. All I need to do is omit what I can't pair, but I can't omit that until I can pair things together; no matter how I sort, I will have unnecessary data in my equations.

What you see below is about the fifth different try at this problem.

import pandas as pd

with open('TastyTrades.csv', 'r') as trade_history:
    trade_reader = pd.read_csv('TastyTrades.csv')
    options_frame = trade_reader.loc[(trade_reader['Instrument Type'] == 'Equity Option')]
    date_frame = options_frame.sort_values(by=['Symbol', 'Date', 'Action'], ascending=True)
    for date_frame['Symbol'] in date_frame:
        if date_frame['Action'] == ['BUY_TO_OPEN' and 'SELL_TO_CLOSE'] or ['SELL_TO_OPEN' and 'BUY_TO_CLOSE']:
            date_frame.to_csv('new_taste.csv')

This results in :

ValueError: Lengths must match to compare

Process finished with exit code 1

Even further below is an earlier attempt:

import pandas as pd

with open('TastyTrades.csv', 'r') as trade_history:
    trade_reader = pd.read_csv('TastyTrades.csv')
    options_frame = trade_reader.loc[(trade_reader['Instrument Type'] == 'Equity Option')]
    date_frame = options_frame.sort_values(by=['Symbol', 'Date', 'Action'], ascending=True)
    close_frame = date_frame[date_frame['Action'].isin(['BUY_TO_OPEN' and 'SELL_TO_CLOSE'] or
                                                       ['SELL_TO_OPEN' and 'BUY_TO_CLOSE'])]

    close_frame.to_csv('new_taste.csv')

Which resulted in:

,Date,Type,Action,Symbol,Instrument Type,Description,Value,Quantity,Average Price,Commissions,Fees,Multiplier,Underlying Symbol,Expiration Date,Strike Price,Call or Put
75,2020-02-05T09:34:42-0500,Trade,SELL_TO_CLOSE,AA    200320P00013000,Equity Option,Sold 1 AA 03/20/20 Put 13.00 @ 0.12,12,1,12.0,0.0,-0.15,100.0,AA,3/20/2020,13.0,PUT
38,2020-02-12T11:58:10-0500,Trade,SELL_TO_CLOSE,AAL   200320P00023000,Equity Option,Sold 1 AAL 03/20/20 Put 23.00 @ 0.09,9,1,9.0,0.0,-0.15,100.0,AAL,3/20/2020,23.0,PUT
166,2020-01-29T09:41:30-0500,Trade,SELL_TO_CLOSE,AAL   200320P00024000,Equity Option,Sold 1 AAL 03/20/20 Put 24.00 @ 0.48,48,1,48.0,0.0,-0.15,100.0,AAL,3/20/2020,24.0,PUT
216,2020-01-13T15:45:09-0500,Trade,SELL_TO_CLOSE,AAPL  200117C00320000,Equity Option,Sold 1 AAPL 01/17/20 Call 320.00 @ 1.86,186,1,186.0,0.0,-0.15,100.0,AAPL,1/17/2020,320.0,CALL

As you can see with this example, it's only grabbing SELL_TO_CLOSE.


问:
subtract two lists from each other and get the lowest answer and its corresponding values
I have two lists of lists and I want to subtract values from each other and get the lowest result as well as the letters each operand corresponds to. For example, I have :

```<code>lst1 = [['A', 2], ['B', 39], ['C', 75]]
lst2 = [['D', 9], ['D', 10], ['D', 11]]
</code>```

And I want to get the output as ['A', 'D', 7], since 9-2 = 7 and it is the smallest result I can get when subtracting any of lst1 numbers from lst2.

Another example:

```<code>lst1 = [['A', 45], ['B', 39], ['C', 75]]
lst2 = [['D', 9]]
</code>```

The output should be ['B', 'D', 30].

答:
Use itertools.product to enumerate all the possible pairings of elements from the lists and generate results using a list comprehension, then use min to find the smallest 3rd element:

```<code>from operator import itemgetter
from itertools import product

lst1 = [['A', 2] , ['B', 39] , ['C', 75]]
lst2 = [['D', 12] , ['E', 10] , ['F', 11], ['G', 9]]

results = [[a[0],b[0],abs(a[1]-b[1])] for a,b in product(lst1,lst2)]
print(results)
result = min(results,key=itemgetter(2))
print(result)
</code>```

Output:

```<code>[['A', 'D', 10], ['A', 'E', 8], ['A', 'F', 9], ['A', 'G', 7], ['B', 'D', 27], ['B', 'E', 29], ['B', 'F', 28], ['B', 'G', 30], ['C', 'D', 63], ['C', 'E', 65], ['C', 'F', 64], ['C', 'G', 66]]
['A', 'G', 7]
</code>```

Body:
I have two lists of lists and I want to subtract values from each other and get the lowest result as well as the letters each operand corresponds to. For example, I have :

lst1 = [['A', 2], ['B', 39], ['C', 75]]
lst2 = [['D', 9], ['D', 10], ['D', 11]]

And I want to get the output as ['A', 'D', 7], since 9-2 = 7 and it is the smallest result I can get when subtracting any of lst1 numbers from lst2.

Another example:

lst1 = [['A', 45], ['B', 39], ['C', 75]]
lst2 = [['D', 9]]

The output should be ['B', 'D', 30].

Body:
Use itertools.product to enumerate all the possible pairings of elements from the lists and generate results using a list comprehension, then use min to find the smallest 3rd element:

from operator import itemgetter
from itertools import product

lst1 = [['A', 2] , ['B', 39] , ['C', 75]]
lst2 = [['D', 12] , ['E', 10] , ['F', 11], ['G', 9]]

results = [[a[0],b[0],abs(a[1]-b[1])] for a,b in product(lst1,lst2)]
print(results)
result = min(results,key=itemgetter(2))
print(result)

Output:

[['A', 'D', 10], ['A', 'E', 8], ['A', 'F', 9], ['A', 'G', 7], ['B', 'D', 27], ['B', 'E', 29], ['B', 'F', 28], ['B', 'G', 30], ['C', 'D', 63], ['C', 'E', 65], ['C', 'F', 64], ['C', 'G', 66]]
['A', 'G', 7]


问:
N/A error while using the correct VLookup formula to get value from other sheet
In excel, I was trying to get fund value of a particular mutual fund by using VLookup to search another sheet. In the process, I am getting N/A error even if the VLookup formula seems correct.

The below screenshot is of the sheet with the VLookup excel formula:

Is there any issues with the vlookup formula that I am using here.
=VLOOKUP(D4,Sheet1!$A$5072:$E$5075,5,FALSE)
I have tried many version of the vlookup but to no avail. Could anyone please help? Thanks!

答:
Cleaning the data is the best option, so that both values are either all text, or all numbers.

But a quick and dirty work aroubd would be to use to convert the text to numbers

```<code>=INDEX($E$5072:$E$5075,MATCH(D4,VALUE($A$5072:$A$5075),0))
</code>```

or

```<code>=XLOOKUP(D4,VALUE($A$5072:$A$5075),$E$5072:$E$5075,,0,1)
</code>```

Body:
Cleaning the data is the best option, so that both values are either all text, or all numbers.

But a quick and dirty work aroubd would be to use to convert the text to numbers

=INDEX($E$5072:$E$5075,MATCH(D4,VALUE($A$5072:$A$5075),0))

or

=XLOOKUP(D4,VALUE($A$5072:$A$5075),$E$5072:$E$5075,,0,1)


问:
Boost / increase volume of text to speech (AVSpeechUtterance) to make it louder
I have a navigation app that gives direction voice instruction (e.g. " In 200 feet turn left") using AVSpeechUtterance. I have put volume to 1 like so. speechUtteranceInstance.volume = 1, but still the volume is very low compared to the music or podcast coming from the iPhone, especially when the sound is on a Bluetooth or cabled connection (like connected to car with Bluetooth)

Is there any way to boost the volume?
(I know this has been asked before on SO but so far have not found a solution that works for me.)

答:
After a lot more research and playing around, I found a good workaround solution.

First of all I think this is an iOS bug. When all below conditions are true I found that the voice instruction itself is also ducked (or at least it sounds ducked) resulting in the voice instruction playing at the same volume as the DUCKED music (thus way too soft to hear well).

Playing music in the background

Ducking this background music through
the .duckOther audioSessionCategory

Playing a voiceUtterance through AVSpeechSynthesizer

Playing audio over a connected bluetooth
device (like bluetooth headset or bluetooth car speakers)

The workaround solution I found is to feed the speechUtterance to an AVAudioEngine. This can only be done on iOS13 or above, since that adds the .write method to AVSpeechSynthesizer

In short I use AVAudioEngine, AVAudioUnitEQ and AVAudioPlayerNode, setting the globalGain property of the AVAudioUnitEQ to about 10 dB. There are also a few quirks with this, but they can be worked around (see code comments).

Here's the complete code:

```<code>import UIKit
import AVFoundation
import MediaPlayer

class ViewController: UIViewController {

    // MARK: AVAudio properties
    var engine = AVAudioEngine()
    var player = AVAudioPlayerNode()
    var eqEffect = AVAudioUnitEQ()
    var converter = AVAudioConverter(from: AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16, sampleRate: 22050, channels: 1, interleaved: false)!, to: AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatFloat32, sampleRate: 22050, channels: 1, interleaved: false)!)
    let synthesizer = AVSpeechSynthesizer()
    var bufferCounter: Int = 0

    let audioSession = AVAudioSession.sharedInstance()

    override func viewDidLoad() {
        super.viewDidLoad()

        let outputFormat = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatFloat32, sampleRate: 22050, channels: 1, interleaved: false)!
        setupAudio(format: outputFormat, globalGain: 0)

    }

    func activateAudioSession() {
        do {
            try audioSession.setCategory(.playback, mode: .voicePrompt, options: [.mixWithOthers, .duckOthers])
            try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
        } catch {
            print("An error has occurred while setting the AVAudioSession.")
        }
    }

    @IBAction func tappedPlayButton(_ sender: Any) {

        eqEffect.globalGain = 0
        play()

    }

    @IBAction func tappedPlayLoudButton(_ sender: Any) {
        eqEffect.globalGain = 10
        play()

    }

    func play() {
        let path = Bundle.main.path(forResource: "voiceStart", ofType: "wav")!
        let file = try! AVAudioFile(forReading: URL(fileURLWithPath: path))
        self.player.scheduleFile(file, at: nil, completionHandler: nil)
        let utterance = AVSpeechUtterance(string: "This is to test if iOS is able to boost the voice output above the 100% limit.")
        synthesizer.write(utterance) { buffer in
            guard let pcmBuffer = buffer as? AVAudioPCMBuffer, pcmBuffer.frameLength > 0 else {
                print("could not create buffer or buffer empty")
                return
            }

            // QUIRCK Need to convert the buffer to different format because AVAudioEngine does not support the format returned from AVSpeechSynthesizer
            let convertedBuffer = AVAudioPCMBuffer(pcmFormat: AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatFloat32, sampleRate: pcmBuffer.format.sampleRate, channels: pcmBuffer.format.channelCount, interleaved: false)!, frameCapacity: pcmBuffer.frameCapacity)!
            do {
                try self.converter!.convert(to: convertedBuffer, from: pcmBuffer)
                self.bufferCounter += 1
                self.player.scheduleBuffer(convertedBuffer, completionCallbackType: .dataPlayedBack, completionHandler: { (type) -> Void in
                    DispatchQueue.main.async {
                        self.bufferCounter -= 1
                        print(self.bufferCounter)
                        if self.bufferCounter == 0 {
                            self.player.stop()
                            self.engine.stop()
                            try! self.audioSession.setActive(false, options: [])
                        }
                    }

                })

                self.converter!.reset()
                //self.player.prepare(withFrameCount: convertedBuffer.frameLength)
            }
            catch let error {
                print(error.localizedDescription)
            }
        }
        activateAudioSession()
        if !self.engine.isRunning {
            try! self.engine.start()
        }
        if !self.player.isPlaying {
            self.player.play()
        }
    }

    func setupAudio(format: AVAudioFormat, globalGain: Float) {
        // QUIRCK: Connecting the equalizer to the engine somehow starts the shared audioSession, and if that audiosession is not configured with .mixWithOthers and if it's not deactivated afterwards, this will stop any background music that was already playing. So first configure the audio session, then setup the engine and then deactivate the session again.
        try? self.audioSession.setCategory(.playback, options: .mixWithOthers)

        eqEffect.globalGain = globalGain
        engine.attach(player)
        engine.attach(eqEffect)
        engine.connect(player, to: eqEffect, format: format)
        engine.connect(eqEffect, to: engine.mainMixerNode, format: format)
        engine.prepare()

        try? self.audioSession.setActive(false)

    }

}
</code>```

Body:
After a lot more research and playing around, I found a good workaround solution.

First of all I think this is an iOS bug. When all below conditions are true I found that the voice instruction itself is also ducked (or at least it sounds ducked) resulting in the voice instruction playing at the same volume as the DUCKED music (thus way too soft to hear well).

Playing music in the background

Ducking this background music through
the .duckOther audioSessionCategory

Playing a voiceUtterance through AVSpeechSynthesizer

Playing audio over a connected bluetooth
device (like bluetooth headset or bluetooth car speakers)

The workaround solution I found is to feed the speechUtterance to an AVAudioEngine. This can only be done on iOS13 or above, since that adds the .write method to AVSpeechSynthesizer

In short I use AVAudioEngine, AVAudioUnitEQ and AVAudioPlayerNode, setting the globalGain property of the AVAudioUnitEQ to about 10 dB. There are also a few quirks with this, but they can be worked around (see code comments).

Here's the complete code:

import UIKit
import AVFoundation
import MediaPlayer

class ViewController: UIViewController {

    // MARK: AVAudio properties
    var engine = AVAudioEngine()
    var player = AVAudioPlayerNode()
    var eqEffect = AVAudioUnitEQ()
    var converter = AVAudioConverter(from: AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16, sampleRate: 22050, channels: 1, interleaved: false)!, to: AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatFloat32, sampleRate: 22050, channels: 1, interleaved: false)!)
    let synthesizer = AVSpeechSynthesizer()
    var bufferCounter: Int = 0

    let audioSession = AVAudioSession.sharedInstance()

    override func viewDidLoad() {
        super.viewDidLoad()

        let outputFormat = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatFloat32, sampleRate: 22050, channels: 1, interleaved: false)!
        setupAudio(format: outputFormat, globalGain: 0)

    }

    func activateAudioSession() {
        do {
            try audioSession.setCategory(.playback, mode: .voicePrompt, options: [.mixWithOthers, .duckOthers])
            try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
        } catch {
            print("An error has occurred while setting the AVAudioSession.")
        }
    }

    @IBAction func tappedPlayButton(_ sender: Any) {

        eqEffect.globalGain = 0
        play()

    }

    @IBAction func tappedPlayLoudButton(_ sender: Any) {
        eqEffect.globalGain = 10
        play()

    }

    func play() {
        let path = Bundle.main.path(forResource: "voiceStart", ofType: "wav")!
        let file = try! AVAudioFile(forReading: URL(fileURLWithPath: path))
        self.player.scheduleFile(file, at: nil, completionHandler: nil)
        let utterance = AVSpeechUtterance(string: "This is to test if iOS is able to boost the voice output above the 100% limit.")
        synthesizer.write(utterance) { buffer in
            guard let pcmBuffer = buffer as? AVAudioPCMBuffer, pcmBuffer.frameLength > 0 else {
                print("could not create buffer or buffer empty")
                return
            }

            // QUIRCK Need to convert the buffer to different format because AVAudioEngine does not support the format returned from AVSpeechSynthesizer
            let convertedBuffer = AVAudioPCMBuffer(pcmFormat: AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatFloat32, sampleRate: pcmBuffer.format.sampleRate, channels: pcmBuffer.format.channelCount, interleaved: false)!, frameCapacity: pcmBuffer.frameCapacity)!
            do {
                try self.converter!.convert(to: convertedBuffer, from: pcmBuffer)
                self.bufferCounter += 1
                self.player.scheduleBuffer(convertedBuffer, completionCallbackType: .dataPlayedBack, completionHandler: { (type) -> Void in
                    DispatchQueue.main.async {
                        self.bufferCounter -= 1
                        print(self.bufferCounter)
                        if self.bufferCounter == 0 {
                            self.player.stop()
                            self.engine.stop()
                            try! self.audioSession.setActive(false, options: [])
                        }
                    }

                })

                self.converter!.reset()
                //self.player.prepare(withFrameCount: convertedBuffer.frameLength)
            }
            catch let error {
                print(error.localizedDescription)
            }
        }
        activateAudioSession()
        if !self.engine.isRunning {
            try! self.engine.start()
        }
        if !self.player.isPlaying {
            self.player.play()
        }
    }

    func setupAudio(format: AVAudioFormat, globalGain: Float) {
        // QUIRCK: Connecting the equalizer to the engine somehow starts the shared audioSession, and if that audiosession is not configured with .mixWithOthers and if it's not deactivated afterwards, this will stop any background music that was already playing. So first configure the audio session, then setup the engine and then deactivate the session again.
        try? self.audioSession.setCategory(.playback, options: .mixWithOthers)

        eqEffect.globalGain = globalGain
        engine.attach(player)
        engine.attach(eqEffect)
        engine.connect(player, to: eqEffect, format: format)
        engine.connect(eqEffect, to: engine.mainMixerNode, format: format)
        engine.prepare()

        try? self.audioSession.setActive(false)

    }

}


问:
Why is the compiler stating that I am applying to many arguments?
For this function I am given two ints and I am supposed to place the range of numbers from num1 to num2 into a list.

```<code>let rec range num1 num2 =
  (* YOUR CODE HERE *)
  if num2 < num1 then raise IncorrectRange
  else if num1 = num2 then [num1]
  else let num3 = num1 +1 in num1::(range num3 num2)

let range() = assert (range 2 5 = [2;3;4;5])
</code>```

For some reason when I test my code it states that the function is type unit -> unit and that it is applied too too many arguments. What am I doing wrong?

答:
Your code consists of two definitions of a function named range, with different types. This is legitimate OCaml code (the second definition hides the first one), but this seems very unlikely to be what is intended.

My guess is that there's a typo in the assert line.

At any rate, any code that you enter after this will be using the second definition of range, which indeed has the type unit -> unit.

Body:
For this function I am given two ints and I am supposed to place the range of numbers from num1 to num2 into a list.

let rec range num1 num2 =
  (* YOUR CODE HERE *)
  if num2 < num1 then raise IncorrectRange
  else if num1 = num2 then [num1]
  else let num3 = num1 +1 in num1::(range num3 num2)

let range() = assert (range 2 5 = [2;3;4;5])

For some reason when I test my code it states that the function is type unit -> unit and that it is applied too too many arguments. What am I doing wrong?


问:
Laravel 5.6 - creation user not working
my application used to working well with registration user but now it dont.

here a portion of my model User

```<code> protected $fillable = [
    'prenom', 'nom', 'email','photo_path','password',
];
</code>```

here my validation function :

```<code> protected function validator(array $data)
{

    return Validator::make($data, [
        'prenom' => 'required|string|max:255',
        'nom' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'photo_path' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
        'password' => 'required|string|min:6|confirmed',
    ]);

}
</code>```

here my create function :

```<code> protected function create(array $data)
{
    dd($data);
    $photoInput = request('photo_path');
    $userPhotoPath='users';
    $storagePhotoPath = Storage::disk('images')->put($userPhotoPath, $photoInput);

    return User::create([
        'prenom' => $data['prenom'],
        'nom' => $data['nom'],
        'email' => $data['email'],
        'photo_path' => $storagePhotoPath,
        'password' => Hash::make($data['password']),
    ]);

}
</code>```

- POST request working ( return 302 ) but return back with input value
- Auth Route are declared in web.php
- Validation working well

but the php interpretor didnt get inside create function...

i just see in debugbar that information :

```<code>The given data was invalid./home/e7250/Laravel/ManageMyWorkLife/vendor/laravel/framework/src/Illuminate/Validation/Validator.php#306Illuminate\Validation\ValidationException

public function validate()
    {
        if ($this->fails()) {
            throw new ValidationException($this);
        }

        $data = collect($this->getData())
</code>```

but my validation working because i have error message near my InputTexte.
so i dont understand that error message ...

Do  you have any clue ?

答: Check if your User Model has a constructor, if so remove it and check if the problem still accours. This fixed it for me.</p>

Title: Laravel 5.6 - creation user not working

Body:
my application used to working well with registration user but now it dont.

here a portion of my model User

 protected $fillable = [
    'prenom', 'nom', 'email','photo_path','password',
];

here my validation function :

 protected function validator(array $data)
{

    return Validator::make($data, [
        'prenom' => 'required|string|max:255',
        'nom' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'photo_path' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
        'password' => 'required|string|min:6|confirmed',
    ]);

}

here my create function :

 protected function create(array $data)
{
    dd($data);
    $photoInput = request('photo_path');
    $userPhotoPath='users';
    $storagePhotoPath = Storage::disk('images')->put($userPhotoPath, $photoInput);

    return User::create([
        'prenom' => $data['prenom'],
        'nom' => $data['nom'],
        'email' => $data['email'],
        'photo_path' => $storagePhotoPath,
        'password' => Hash::make($data['password']),
    ]);

}

- POST request working ( return 302 ) but return back with input value
- Auth Route are declared in web.php
- Validation working well

but the php interpretor didnt get inside create function...

i just see in debugbar that information :

The given data was invalid./home/e7250/Laravel/ManageMyWorkLife/vendor/laravel/framework/src/Illuminate/Validation/Validator.php#306Illuminate\Validation\ValidationException

public function validate()
    {
        if ($this->fails()) {
            throw new ValidationException($this);
        }

        $data = collect($this->getData())

but my validation working because i have error message near my InputTexte.
so i dont understand that error message ...

Do  you have any clue ?


问:
How can I "rotate" a relationship in laravel most efficiently?
Im building an ecommerce website in Laravel. I have an attributes table filled with the attribute information, like "Color" and "Size". The **attribute_values table holds all the attribute values like "red", "blue" and "XXL".

Since I want to re-use the attributes I don't create a new attribute set per product, but I link all the attribute values to the products with the pivot table attribute_value_product.

The model relationship structure is:

```<code>Attribute -> hasMany -> AttributeValue
Product -> belongsToMany -> AttributeValue
</code>```

The tables are as follows:

```<code>products
--------------------------------
| id | name            | price |
--------------------------------
| 1  | Example product | 200   |
--------------------------------

attributes
--------------
| id | name  |
--------------
| 1  | Color |
--------------

attribute_values
-----------------------------
| id | attribute_id | value |
-----------------------------
| 1  | 1            | Red   |
-----------------------------
| 2  | 1            | Blue  |
-----------------------------

attribute_value_product
----------------------------------------
| id | attribute_value_id | product_id |
----------------------------------------
| 1  | 1                  | 1          |
----------------------------------------
| 2  | 2                  | 1          |
----------------------------------------

</code>```

The controller code (a bit simplified) looks like this:

```<code>public function show($id) {

  $product = Product::where('id', $id)
    ->with('attributeValues.attribute')
    ->first();

  return view('product')->withProduct($product);

}
</code>```

the JSON result when I return the $product variable from the controller looks like this:

```<code>{
    id: 1,
    name: "Example product",
    price: 200,
    attribute_values: [
        {
            id: 1,
            attribute_id: 1,
            value: "Red",
            attribute: {
                id: 1,
                name: "Color",
            }
        },
        {
            id: 2,
            attribute_id: 1,
            value: "Blue",
            attribute: {
                id: 1,
                name: "Color",
            }
        }
    ]
}
</code>```

As you can see, this is kinda 'nasty'. When I retrieve lots of attributes for lots of products the attribute get's loaded for every value. When I only need it once actually. Also the way the data is structured is "wrong" in my opinion.

The preferred output I would like to see is:

```<code>{
    id: 1,
    name: "Example product",
    price: 200,
    attributes: [
        {
            id: 1,
            name: "Color",
            values: [
                {
                    id: 1,
                    attribute_id: 1,
                    value: "Blue",
                },
                {
                    id: 2,
                    attribute_id: 1,
                    value: "Red",
                }
            ]
        },
    ]
}
</code>```

So the values would be loaded per attribute per product. Is there a (Laravel) way to structure the relationships in a way that I can retrieve the data in the latter format while still keeping the database schema I have?

I'd rather not loop over all the items every time I need to retrieve the attributes. Especially when querying for lot's of products with some other relations.

答:
You haven't actually provided any controller code to help you ensure that you achieve the result that you are looking for but here are a few ways I would consider tackling this issue. But you will have to decide what would fit your coding style.

Method 1: Use the HasManyThrough Relationship on your Product::class

Laravel's $this->hasManyThrough() relationship was intended to allow
  you to access a nested relationship which fits your use case.

```<code>class Product extends Model
{
    /**
     * Get all of the attributes for the product.
     */
    public function attributes()
    {
        return $this->hasManyThrough('App\Attribute', 'App\AttributeValue');
    }
}
</code>```

And use Product::with('attributes.attributeValues')->first()

The use of dot notation above is to prevents n+1 issues by also eager
  loading the nested attributeValues relationship. see the Eager Loading Docs

Method 2: Use an Eloquent Resource

Essentially, this is a model presenter which gives you the ability to
  control the data provided returned via an API endpoint.

Eloquent Resources can be created via a console command

```<code>php artisan make:resource ProductResource
</code>```

Which will generate a ProductResource.php file in the app\Http\Resources directory.

```<code><?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        // This will use the Default Eloquent Model toArray methods
        $resource = $this->resource->toArray();

        // Now you can append in any custom fields that you need.

        if($this->whenLoaded('attributeValues'){
            // whenLoaded is used here to dynamically append this attribute only when the relationship has been eager loaded
            $resource['attributes'] = $this->resource->attributeValues->groupBy('attribute.name');
        }

        return $resource;
    }
}
</code>```

The use of $this->whenLoaded above accomplishes two things:

Limits N+1 errors (only for the $product->attributeValues and not the nested relationship of $product->attributeValues->attributes)

Allows for reusability of the ProductResource::class in situations where Attribute and AttributeValue are not
  loaded/needed.

Note: This line $resource['attributes'] =
  $this->resource->attributeValues->groupBy('attribute.name'); could
  very well be replaced with calls to an Eloquent Resource
  Collection with additional nested Resources and/or
  ResourceColletions, if you decide to fully adopt the Model Presenter
  pattern.

Finally in your controller you would do something like the following:

```<code>// Use of dot notation here will eager load the attributes as well avoiding potential n+1 problems

$product = Product::with('attributeValues.attribute')->first()

return new App\Http\Resources\Product($product);
</code>```

Body:
Im building an ecommerce website in Laravel. I have an attributes table filled with the attribute information, like "Color" and "Size". The **attribute_values table holds all the attribute values like "red", "blue" and "XXL".

Since I want to re-use the attributes I don't create a new attribute set per product, but I link all the attribute values to the products with the pivot table attribute_value_product.

The model relationship structure is:

Attribute -> hasMany -> AttributeValue
Product -> belongsToMany -> AttributeValue

The tables are as follows:

products
--------------------------------
| id | name            | price |
--------------------------------
| 1  | Example product | 200   |
--------------------------------

attributes
--------------
| id | name  |
--------------
| 1  | Color |
--------------

attribute_values
-----------------------------
| id | attribute_id | value |
-----------------------------
| 1  | 1            | Red   |
-----------------------------
| 2  | 1            | Blue  |
-----------------------------

attribute_value_product
----------------------------------------
| id | attribute_value_id | product_id |
----------------------------------------
| 1  | 1                  | 1          |
----------------------------------------
| 2  | 2                  | 1          |
----------------------------------------

The controller code (a bit simplified) looks like this:

public function show($id) {

  $product = Product::where('id', $id)
    ->with('attributeValues.attribute')
    ->first();

  return view('product')->withProduct($product);

}

the JSON result when I return the $product variable from the controller looks like this:

{
    id: 1,
    name: "Example product",
    price: 200,
    attribute_values: [
        {
            id: 1,
            attribute_id: 1,
            value: "Red",
            attribute: {
                id: 1,
                name: "Color",
            }
        },
        {
            id: 2,
            attribute_id: 1,
            value: "Blue",
            attribute: {
                id: 1,
                name: "Color",
            }
        }
    ]
}

As you can see, this is kinda 'nasty'. When I retrieve lots of attributes for lots of products the attribute get's loaded for every value. When I only need it once actually. Also the way the data is structured is "wrong" in my opinion.

The preferred output I would like to see is:

{
    id: 1,
    name: "Example product",
    price: 200,
    attributes: [
        {
            id: 1,
            name: "Color",
            values: [
                {
                    id: 1,
                    attribute_id: 1,
                    value: "Blue",
                },
                {
                    id: 2,
                    attribute_id: 1,
                    value: "Red",
                }
            ]
        },
    ]
}

So the values would be loaded per attribute per product. Is there a (Laravel) way to structure the relationships in a way that I can retrieve the data in the latter format while still keeping the database schema I have?

I'd rather not loop over all the items every time I need to retrieve the attributes. Especially when querying for lot's of products with some other relations.

Body:
You haven't actually provided any controller code to help you ensure that you achieve the result that you are looking for but here are a few ways I would consider tackling this issue. But you will have to decide what would fit your coding style.

Method 1: Use the HasManyThrough Relationship on your Product::class

Laravel's $this->hasManyThrough() relationship was intended to allow
  you to access a nested relationship which fits your use case.

class Product extends Model
{
    /**
     * Get all of the attributes for the product.
     */
    public function attributes()
    {
        return $this->hasManyThrough('App\Attribute', 'App\AttributeValue');
    }
}

And use Product::with('attributes.attributeValues')->first()

The use of dot notation above is to prevents n+1 issues by also eager
  loading the nested attributeValues relationship. see the Eager Loading Docs

Method 2: Use an Eloquent Resource

Essentially, this is a model presenter which gives you the ability to
  control the data provided returned via an API endpoint.

Eloquent Resources can be created via a console command

php artisan make:resource ProductResource

Which will generate a ProductResource.php file in the app\Http\Resources directory.

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        // This will use the Default Eloquent Model toArray methods
        $resource = $this->resource->toArray();

        // Now you can append in any custom fields that you need.

        if($this->whenLoaded('attributeValues'){
            // whenLoaded is used here to dynamically append this attribute only when the relationship has been eager loaded
            $resource['attributes'] = $this->resource->attributeValues->groupBy('attribute.name');
        }

        return $resource;
    }
}

The use of $this->whenLoaded above accomplishes two things:

Limits N+1 errors (only for the $product->attributeValues and not the nested relationship of $product->attributeValues->attributes)

Allows for reusability of the ProductResource::class in situations where Attribute and AttributeValue are not
  loaded/needed.

Note: This line $resource['attributes'] =
  $this->resource->attributeValues->groupBy('attribute.name'); could
  very well be replaced with calls to an Eloquent Resource
  Collection with additional nested Resources and/or
  ResourceColletions, if you decide to fully adopt the Model Presenter
  pattern.

Finally in your controller you would do something like the following:

// Use of dot notation here will eager load the attributes as well avoiding potential n+1 problems

$product = Product::with('attributeValues.attribute')->first()

return new App\Http\Resources\Product($product);


问:
How do I mark URL's to appear as href's when viewed via the eclipse editor
// Refer: http://en.wikipedia.org/wiki/Decimal

I have a snippet like this in my java source code, viewed via the Eclipse editor. How do I make this appear as a href, so that users can just click on it, instead of doing a cut-n-paste.

Is is possible?

答: It depends on the user's editor, if it's able to interpret url's inside comments. At least for Eclipse, I couldn't find a plugin that does this for you. You might need to write your own or ask the Eclipse community for one.</p>

ContentLicense: CC BY-SA 3.0


问:
Requests.py Redirect URL
When you go to the site, https://www.jimmyjazz.com/search?keywords=11468285, you are redirected to https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528.

I would like to use requests to enter that search link, then return the url that it is redirected to.

Here is my code to do that:

```<code>import requests
from bs4 import BeautifulSoup
sitename = "https://www.jimmyjazz.com/search?keywords=11468285"
response = requests.get(sitename, allow_redirects=True)
print(response.url)
</code>```

But it still returns the original url:

```<code>PS C:\Users\jokzc\Desktop\python\learning requests> py test2.py
https://www.jimmyjazz.com/search?keywords=11468285
</code>```

How would I append my code to make fix that? Thanks :)

答:
This doesn't actually send a 302 redirect code back. I did the same HTTP GET call in postman, and it appears that it returns a 200 OK response:

Same goes for chrome dev tools, looking at the network traffic:

I think that somewhere in their JavaScript code they are setting the location.href to be a new url. I didn't go through the whole JS stack trace to prove it, but that is my best guess.

Title: Requests.py Redirect URL

Body:
When you go to the site, https://www.jimmyjazz.com/search?keywords=11468285, you are redirected to https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528.

I would like to use requests to enter that search link, then return the url that it is redirected to.

Here is my code to do that:

import requests
from bs4 import BeautifulSoup
sitename = "https://www.jimmyjazz.com/search?keywords=11468285"
response = requests.get(sitename, allow_redirects=True)
print(response.url)

But it still returns the original url:

PS C:\Users\jokzc\Desktop\python\learning requests> py test2.py
https://www.jimmyjazz.com/search?keywords=11468285

How would I append my code to make fix that? Thanks :)


问:
EmbedIO with a list of unknown web APIs
I want to have a modular EmbedIO setup with a dynamic list of unknown web API controller types. I thought it'd be easy :( But at the moment I'm stuck at registering the web APIs:

```<code>// Some APIs to setup at the EmbedIO webserver in "Server"
Dictionary<string, WebApiController> apis = ...;

// Register the APIs at the webserver
foreach(KeyValuePair<string, WebApiController> kvp in apis)
{
    // Exception: "Controller type must be a subclass of WebApiController."
    Server.WithWebApi(kvp.Key, m => m.WithController(() => kvp.Value));
}
</code>```

The problem is: The factory method needs to return the final type of the controller object. Everything else seems to fail.

I tried with dynamic instead of WebApiController or returning object and giving the type as first parameter for WithController - whatever I tried, it resulted in an exception; Or when I use a class WebApiControllerWrapper : WebApiController and a Dictionary<string, WebApiControllerWrapper>, the exported controller methods of the final type are missing, because they're not defined in WebApiControllerWrapper.

It seems the only way is to use reflection for the generic call of WithController - or does anyone know another working solution (I'm in .NET Standard 2.1)?

答:
I was able to solve it with an expression tree that calls a generic method to create the factory function:

```<code>public class ModularWebApiController : WebApiController
{
    public Func<T> CreateFactoryMethod<T>() where T : WebApiController => () => (T)this;
}

public static class Extensions
{
    public static WebApiModule WithController(this WebApiModule webApiModule, ModularWebApiController api)
    {
        Delegate factoryFunc = Expression
            .Lambda(Expression.Call(
                Expression.Constant(api),
                typeof(ModularWebApiController).GetMethod("CreateFactoryMethod").MakeGenericMethod(api.GetType())
            ))
            .Compile();
        return (WebApiModule)typeof(WebApiModuleExtensions)
                    .GetMethods(BindingFlags.Static | BindingFlags.Public)
                    .Single(mi => mi.IsGenericMethod & mi.Name == "WithController" && mi.GetParameters().Length == 2)
                    .MakeGenericMethod(api.GetType())
            .Invoke(null, new object[] { webApiModule, factoryFunc.DynamicInvoke(Array.Empty<object>()) });
    }
}
</code>```

I only had to ensure that all web API controller types extend the ModularWebApiController type, and I had to change the modular web API setup for EmbedIO:

```<code>Dictionary<string, ModularWebApiController> apis = ...;
foreach(KeyValuePair<string, ModularWebApiController> kvp in apis)
{
    Server.WithWebApi(kvp.Key, m => m.WithController(kvp.Value));
}
</code>```

After browsing the EmbedIO source I think this seems to be the only way to have a modular web API setup, where the code doesn't know which web API controller types are going to be used.

Now I'm able to load and instance any web API controller type configured in a JSON configuration file like this:

```<code>[
    {
        "Type": "name.space.WebApiControllerTypeName",
        "Path": "/webapipath/"
    },
    {
        "Type": "name.space.AnotherWebApiControllerTypeName",
        "Path": "/anotherwebapipath/"
    }
]
</code>```

Just for example. I wonder why it seems that nobody else want to do this ;)

Title: EmbedIO with a list of unknown web APIs

Body:
I want to have a modular EmbedIO setup with a dynamic list of unknown web API controller types. I thought it'd be easy :( But at the moment I'm stuck at registering the web APIs:

// Some APIs to setup at the EmbedIO webserver in "Server"
Dictionary<string, WebApiController> apis = ...;

// Register the APIs at the webserver
foreach(KeyValuePair<string, WebApiController> kvp in apis)
{
    // Exception: "Controller type must be a subclass of WebApiController."
    Server.WithWebApi(kvp.Key, m => m.WithController(() => kvp.Value));
}

The problem is: The factory method needs to return the final type of the controller object. Everything else seems to fail.

I tried with dynamic instead of WebApiController or returning object and giving the type as first parameter for WithController - whatever I tried, it resulted in an exception; Or when I use a class WebApiControllerWrapper : WebApiController and a Dictionary<string, WebApiControllerWrapper>, the exported controller methods of the final type are missing, because they're not defined in WebApiControllerWrapper.

It seems the only way is to use reflection for the generic call of WithController - or does anyone know another working solution (I'm in .NET Standard 2.1)?

Body:
I was able to solve it with an expression tree that calls a generic method to create the factory function:

public class ModularWebApiController : WebApiController
{
    public Func<T> CreateFactoryMethod<T>() where T : WebApiController => () => (T)this;
}

public static class Extensions
{
    public static WebApiModule WithController(this WebApiModule webApiModule, ModularWebApiController api)
    {
        Delegate factoryFunc = Expression
            .Lambda(Expression.Call(
                Expression.Constant(api),
                typeof(ModularWebApiController).GetMethod("CreateFactoryMethod").MakeGenericMethod(api.GetType())
            ))
            .Compile();
        return (WebApiModule)typeof(WebApiModuleExtensions)
                    .GetMethods(BindingFlags.Static | BindingFlags.Public)
                    .Single(mi => mi.IsGenericMethod & mi.Name == "WithController" && mi.GetParameters().Length == 2)
                    .MakeGenericMethod(api.GetType())
            .Invoke(null, new object[] { webApiModule, factoryFunc.DynamicInvoke(Array.Empty<object>()) });
    }
}

I only had to ensure that all web API controller types extend the ModularWebApiController type, and I had to change the modular web API setup for EmbedIO:

Dictionary<string, ModularWebApiController> apis = ...;
foreach(KeyValuePair<string, ModularWebApiController> kvp in apis)
{
    Server.WithWebApi(kvp.Key, m => m.WithController(kvp.Value));
}

After browsing the EmbedIO source I think this seems to be the only way to have a modular web API setup, where the code doesn't know which web API controller types are going to be used.

Now I'm able to load and instance any web API controller type configured in a JSON configuration file like this:

[
    {
        "Type": "name.space.WebApiControllerTypeName",
        "Path": "/webapipath/"
    },
    {
        "Type": "name.space.AnotherWebApiControllerTypeName",
        "Path": "/anotherwebapipath/"
    }
]

Just for example. I wonder why it seems that nobody else want to do this ;)


问:
how to detect trend e using flink CEP
I am new to Flink CEP. For one of our use cases, we need to implement stream analytics for temperature sensor output. if the temperature keeps on increasing for 30 minutes, need to generate an alert to the operator. I went through the Pattern API but not able to find a way to model this in Pattern? Please suggest a possible way to detect this pattern using Pattern</p>

答:
You have two possible options here that You may consider.

First one is to use the iterative condition in cep that will check if the temperature of the current event is higher than all of previously accepted events. There is an example of the IterativeCondition in the documentation here.
The key is to call the ctx.getEventsForPattern and then compare the current event with previously accepted ones.

The second solution depends on the exact use-case, but perhaps It would be possible for You to use the sliding windows to gather elements in 30 min windows with some slide depending on the frequency of data collection. Then it should be very easy to sort the elements according to timestamps and verify that You have the growing trend in the window.

Title: how to detect trend e using flink CEP


问:
aws elasticsearch getting signature error on post request
Got a 403 signature error , when using the below fetch function:

```<code>    function elasticsearchFetch(AWS, elasticsearchDomain, endpointPath, options = {}, region = process.env.AWS_REGION) {
  return new Promise((resolve, reject) => {
    const { body, method = 'GET' } = options;
    const endpoint = new AWS.Endpoint(elasticsearchDomain);
    const request = new AWS.HttpRequest(endpoint, region);
    request.method = method;
    request.path += endpointPath;
    request.headers.host = elasticsearchDomain;
    if (body) {
      request.body = body;
      request.headers['Content-Type'] = 'application/json';
      request.headers['Content-Length'] = request.body.length;
    }
    const credentials = new AWS.EnvironmentCredentials('AWS');
    const signer = new AWS.Signers.V4(request, 'es');
    signer.addAuthorization(credentials, new Date());
    const client = new AWS.HttpClient();
    client.handleRequest(request, null, (res) => {
      let chunks = '';
      res.on('data', (chunk) => {
        chunks += chunk;
      });
      res.on('end', () => {
        if (res.statusCode !== 201) console.log('Got these options STATUSCODE', JSON.stringify(options, false, 2));
        return resolve({ statusCode: res.statusCode, body: chunks });
      });
    }, (error) => {
      console.log('Got these options ERROR', JSON.stringify(options, false, 2));
      return reject(error);
    });
  });
}
</code>```

This is the options used for the request in above function :

```<code>{
    "method": "POST",
    "body": "{\"prefix\":\"image_233/ArtService/articles-0/GB/ART-60297885/\",\"id\":\"ART-60297885\",\"retailUnit\":\"GB\",\"commercial\":{\"name\":{\"en-GB\":\"FÖRBÄTTRA\"}},\"schemaType\":\"product\",\"productType\":\"ART\"}"
}
</code>```

and got this error :

```<code>{
    "statusCode": 403,
    "body": "{\"message\":\"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\"}"
}
</code>```

This is the endpoint : 233/_doc/

答:
By the way, why not use elasticsearch client for nodejs to communicate with elasticsearch rather than writing your own logic. You can consider using http-aws-es which does the request signing part for you. The code will look like

```<code>const { Client } = require("elasticsearch");
const esConnectionClass = require("http-aws-es");

const elasticsearchConfig = {
  host: "somePath",
  connectionClass: esConnectionClass
};

const nativeClient = new Client(elasticsearchConfig);

const result = await nativeClient.search({});
</code>```

Body:
Got a 403 signature error , when using the below fetch function:

    function elasticsearchFetch(AWS, elasticsearchDomain, endpointPath, options = {}, region = process.env.AWS_REGION) {
  return new Promise((resolve, reject) => {
    const { body, method = 'GET' } = options;
    const endpoint = new AWS.Endpoint(elasticsearchDomain);
    const request = new AWS.HttpRequest(endpoint, region);
    request.method = method;
    request.path += endpointPath;
    request.headers.host = elasticsearchDomain;
    if (body) {
      request.body = body;
      request.headers['Content-Type'] = 'application/json';
      request.headers['Content-Length'] = request.body.length;
    }
    const credentials = new AWS.EnvironmentCredentials('AWS');
    const signer = new AWS.Signers.V4(request, 'es');
    signer.addAuthorization(credentials, new Date());
    const client = new AWS.HttpClient();
    client.handleRequest(request, null, (res) => {
      let chunks = '';
      res.on('data', (chunk) => {
        chunks += chunk;
      });
      res.on('end', () => {
        if (res.statusCode !== 201) console.log('Got these options STATUSCODE', JSON.stringify(options, false, 2));
        return resolve({ statusCode: res.statusCode, body: chunks });
      });
    }, (error) => {
      console.log('Got these options ERROR', JSON.stringify(options, false, 2));
      return reject(error);
    });
  });
}

This is the options used for the request in above function :

{
    "method": "POST",
    "body": "{\"prefix\":\"image_233/ArtService/articles-0/GB/ART-60297885/\",\"id\":\"ART-60297885\",\"retailUnit\":\"GB\",\"commercial\":{\"name\":{\"en-GB\":\"FÖRBÄTTRA\"}},\"schemaType\":\"product\",\"productType\":\"ART\"}"
}

and got this error :

{
    "statusCode": 403,
    "body": "{\"message\":\"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\"}"
}

This is the endpoint : 233/_doc/

Body:
By the way, why not use elasticsearch client for nodejs to communicate with elasticsearch rather than writing your own logic. You can consider using http-aws-es which does the request signing part for you. The code will look like

const { Client } = require("elasticsearch");
const esConnectionClass = require("http-aws-es");

const elasticsearchConfig = {
  host: "somePath",
  connectionClass: esConnectionClass
};

const nativeClient = new Client(elasticsearchConfig);

const result = await nativeClient.search({});