问:
My Django form is not validating and storing information in database
I have created a custom user model and using that model I have created sign up form. but whenever I click submit button ,form does not validate and don't store data in database. It just redirects me to home without storing data in database. but I can store data manually in database.

models.py

```<code>from django.db import models

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class SignUpManager(BaseUserManager):
    def create_user(self, email,age,name, username, password=None):
        if not email:
            raise ValueError("insert user")
        if not username:
            raise ValueError("insert username")
        if not name:
            raise ValueError("insert name")
        if not age:
            raise ValueError("insert age")
        user = self.model(
           email=self.normalize_email(email),
           username=username,
           age=age,
           name=name,
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email,name,age,username, password):

        user = self.create_user(
            email=self.normalize_email(email),
            username=username,
            password=password,
            age=age,
            name=name,
        )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True

        user.save(using=self._db)
        return user

class UserSignupModel(AbstractBaseUser):
    email = models.EmailField(verbose_name="email", max_length=60, unique=True)
    age = models.CharField(max_length=15)
    name = models.CharField(max_length=15)
    username = models.CharField(max_length=15, unique=True)
    date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True)
    last_login = models.DateTimeField(verbose_name="last login", auto_now=True)

    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ['email','name','age']
    objects = SignUpManager()

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True
#migrate --run-syncdb in case no work
</code>```

forms.py

```<code>from django import forms

from django.contrib.auth.forms import UserCreationForm
from diabetes.models import UserSignupModel

class UserSignupForm(UserCreationForm):
    email=forms.EmailField(max_length=60,help_text="add a valid email address")
    name=forms.CharField(max_length=15,help_text="add a valid name")
    age=forms.CharField(max_length=15)

    class Meta:
        model=UserSignupModel
        fields=('email','name',"username",'age',"password1","password2")
</code>```

views.py

```<code>from django.shortcuts import render,redirect
from django.contrib.auth import login,authenticate
from diabetes.forms import UserSignupForm

# Create your views here.
def home(request):
    return render(request,'diabetes/home.html')

def signupuser(request):
    if request.method == 'POST':
        form=UserSignupForm(request.POST)
        if form.is_valid():
            form.save()
            email=form.cleaned_data.get('email')
            raw_password=form.cleaned_data.get('password1')
            account=authenticate(email=email,password=raw_password)
            login(request,account)
            return redirect('home')
        else:
            return redirect('home')

    else:
        form = UserSignupForm()
    return render (request,'diabetes/signupuser.html',{'form':form})
</code>```

signupuser.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form method="POST">
    {% csrf_token %}
    {{ form.as_p}}
    <input type="submit">SUBMIT</input>
</form>

</body>
</html>
</code>```

答:
You have got error in the signup method in views.py. Refer to this code and see what changes can be made.</p>

```<code># method for registration page
def register_view(request):
register_form = AddUserForm(request.POST or None)

# if the data provided in the form is valid than save the form
if register_form.is_valid():
    user = register_form.save(commit=False)
    user = register_form.save()
    raw_password = register_form.cleaned_data.get('password1')

    user = authenticate(request, email=user.email, password=raw_password)
    group = Group.objects.get(name='Student')
    user.groups.add(group)
    if user is not None:
        login(request, user)
    return redirect('login')

return render(request, 'apps/register.html', {'register_form': register_form})
</code>```

Body:
I have created a custom user model and using that model I have created sign up form. but whenever I click submit button ,form does not validate and don't store data in database. It just redirects me to home without storing data in database. but I can store data manually in database.

models.py

from django.db import models

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class SignUpManager(BaseUserManager):
    def create_user(self, email,age,name, username, password=None):
        if not email:
            raise ValueError("insert user")
        if not username:
            raise ValueError("insert username")
        if not name:
            raise ValueError("insert name")
        if not age:
            raise ValueError("insert age")
        user = self.model(
           email=self.normalize_email(email),
           username=username,
           age=age,
           name=name,
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email,name,age,username, password):

        user = self.create_user(
            email=self.normalize_email(email),
            username=username,
            password=password,
            age=age,
            name=name,
        )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True

        user.save(using=self._db)
        return user

class UserSignupModel(AbstractBaseUser):
    email = models.EmailField(verbose_name="email", max_length=60, unique=True)
    age = models.CharField(max_length=15)
    name = models.CharField(max_length=15)
    username = models.CharField(max_length=15, unique=True)
    date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True)
    last_login = models.DateTimeField(verbose_name="last login", auto_now=True)

    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ['email','name','age']
    objects = SignUpManager()

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True
#migrate --run-syncdb in case no work

forms.py

from django import forms

from django.contrib.auth.forms import UserCreationForm
from diabetes.models import UserSignupModel

class UserSignupForm(UserCreationForm):
    email=forms.EmailField(max_length=60,help_text="add a valid email address")
    name=forms.CharField(max_length=15,help_text="add a valid name")
    age=forms.CharField(max_length=15)

    class Meta:
        model=UserSignupModel
        fields=('email','name',"username",'age',"password1","password2")

views.py

from django.shortcuts import render,redirect
from django.contrib.auth import login,authenticate
from diabetes.forms import UserSignupForm

# Create your views here.
def home(request):
    return render(request,'diabetes/home.html')

def signupuser(request):
    if request.method == 'POST':
        form=UserSignupForm(request.POST)
        if form.is_valid():
            form.save()
            email=form.cleaned_data.get('email')
            raw_password=form.cleaned_data.get('password1')
            account=authenticate(email=email,password=raw_password)
            login(request,account)
            return redirect('home')
        else:
            return redirect('home')

    else:
        form = UserSignupForm()
    return render (request,'diabetes/signupuser.html',{'form':form})

signupuser.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

<form method="POST">
    {% csrf_token %}
    {{ form.as_p}}
    <input type="submit">SUBMIT</input>
</form>

Body:
You have got error in the signup method in views.py. Refer to this code and see what changes can be made.

# method for registration page
def register_view(request):
register_form = AddUserForm(request.POST or None)

# if the data provided in the form is valid than save the form
if register_form.is_valid():
    user = register_form.save(commit=False)
    user = register_form.save()
    raw_password = register_form.cleaned_data.get('password1')

    user = authenticate(request, email=user.email, password=raw_password)
    group = Group.objects.get(name='Student')
    user.groups.add(group)
    if user is not None:
        login(request, user)
    return redirect('login')

return render(request, 'apps/register.html', {'register_form': register_form})


来源: stackexchange

问:
How to setup period (time period) for Notifications?
I want to setup a time period for my Notifications.
I created a UNTimeIntervalNotificationTrigger, that the App sends everyday 3 Notifications.
But I also want to do that the 3 Notifications will send between 10:00am and 11:00am or whatever.

So anyone knows how to code a time period for Notifications, that the App sends in that period a few Notifications?

Thank you!

答:
Instead of UNTimeIntervalNotificationTrigger, you should use UNCalendarNotificationTrigger

But for 3 notifications between 10AM and 11AM, you need to create 3 notifications.

```<code>func scheduleNotification(hour: Int, minute: Int) {

    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Your title"
    content.body = "Your body"
    content.categoryIdentifier = "AlarmAt\(hour)\(minute)"
    content.userInfo = ["customKey": "customValue"]
    content.sound = UNNotificationSound.default

    var dateComponents = DateComponents()
    dateComponents.hour = hour
    dateComponents.minute = minute
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

    center.add(request)
}

scheduleNotification(hour: 10, minute: 15)
scheduleNotification(hour: 10, minute: 30)
scheduleNotification(hour: 10, minute: 45)
</code>```

More Info :-

To better understand the scope of UNCalendarNotificationTrigger , I am adding some more options. Note, for your requirement you shouldn't add the below 2 lines, it will give you unexpected results.

If you want this to repeat only any particular day in the week, add :-

```<code>dateComponents.weekday = 2 // Only mondays
</code>```

If you want this to repeat only any particular day in a month, add :-

```<code>dateComponents.day = 12 // Only 12th day of the month
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Instead of UNTimeIntervalNotificationTrigger, you should use UNCalendarNotificationTrigger

But for 3 notifications between 10AM and 11AM, you need to create 3 notifications.

func scheduleNotification(hour: Int, minute: Int) {

    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Your title"
    content.body = "Your body"
    content.categoryIdentifier = "AlarmAt\(hour)\(minute)"
    content.userInfo = ["customKey": "customValue"]
    content.sound = UNNotificationSound.default

    var dateComponents = DateComponents()
    dateComponents.hour = hour
    dateComponents.minute = minute
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

    center.add(request)
}

scheduleNotification(hour: 10, minute: 15)
scheduleNotification(hour: 10, minute: 30)
scheduleNotification(hour: 10, minute: 45)

More Info :-

To better understand the scope of UNCalendarNotificationTrigger , I am adding some more options. Note, for your requirement you shouldn't add the below 2 lines, it will give you unexpected results.

If you want this to repeat only any particular day in the week, add :-

dateComponents.weekday = 2 // Only mondays

If you want this to repeat only any particular day in a month, add :-

dateComponents.day = 12 // Only 12th day of the month


问:
how to unit test subprocess.call() to check is it called in python
Hey I am trying to write unittest to check if subprocess.call() called in the function flash_it that does not return anything.

def flash_it('flash.bat'):
    file = open('file.txt', 'w')
    subprocess.call(['flash.bat', '-d'], stdout = file, stderr = subprocess.STDOUT)
```

<pre class="lang-py prettyprint-override"><code>@mock.patch('subprocess.call')
def test_subprocess_call_passed(self, mock_subproc_call):
    main.flash_it('flash.bat')
    self.assertTrue(mock_subproc_call.called)
</code>```

答:
You probably need something like this:

```<code>import subprocess
import mock

def flash_it(filename):
    with open(filename, 'w') as f:
        subprocess.call(['cmd to flash', '-d'], stdout=f, stderr=subprocess.STDOUT)

@mock.patch('subprocess.call')
def test_subprocess_call_passed(mock_subproc_call):
    flash_it('flash.bat')
    mock_subproc_call.assert_called_once()
</code>```

Note that I didn't actually run that.

Of course there is also assert_called_once_with that lets you assert what parameters were passed to function. Check documentation: https://docs.python.org/3/library/unittest.mock.html

EDIT:
Ok I've run it with pytest:

Body:
Hey I am trying to write unittest to check if subprocess.call() called in the function flash_it that does not return anything.

def flash_it('flash.bat'):
    file = open('file.txt', 'w')
    subprocess.call(['flash.bat', '-d'], stdout = file, stderr = subprocess.STDOUT)

@mock.patch('subprocess.call')
def test_subprocess_call_passed(self, mock_subproc_call):
    main.flash_it('flash.bat')
    self.assertTrue(mock_subproc_call.called)

Body:
You probably need something like this:

import subprocess
import mock

def flash_it(filename):
    with open(filename, 'w') as f:
        subprocess.call(['cmd to flash', '-d'], stdout=f, stderr=subprocess.STDOUT)

@mock.patch('subprocess.call')
def test_subprocess_call_passed(mock_subproc_call):
    flash_it('flash.bat')
    mock_subproc_call.assert_called_once()

Note that I didn't actually run that.

Of course there is also assert_called_once_with that lets you assert what parameters were passed to function. Check documentation: https://docs.python.org/3/library/unittest.mock.html

EDIT:
Ok I've run it with pytest:


问:
Not able to get output from python script when trying to run command on SSH server
My script is -

```<code>import paramiko
import sys
from subprocess import STDOUT
host=str(sys.argv[1])
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='88888',username='admin',password='888888',key_filename='88888')
stdin,stdout,stderr = ssh.exec_command('cpstat -f cpu os')
print(STDOUT)
ssh.close()
</code>```

Here i am checking cpu usage of remote machine , but in output only -2 is printing everytime.
Please help how can i get correct output from this script.

答:
This is what your script should look like </p>

```<code>import paramiko
import sys
host=str(sys.argv[1])
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='88888',username='admin',password='888888',key_filename='88888')
stdin,stdout,stderr = ssh.exec_command('cpstat -f cpu os')
if stdout.channel.recv_exit_status() != 0:
    print("Error encountered")
else:
    print("Got something")
    print(stdout.channel.recv(-1).decode('utf-8'))
ssh.close()
</code>```

Body:
My script is -

import paramiko
import sys
from subprocess import STDOUT
host=str(sys.argv[1])
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='88888',username='admin',password='888888',key_filename='88888')
stdin,stdout,stderr = ssh.exec_command('cpstat -f cpu os')
print(STDOUT)
ssh.close()

Here i am checking cpu usage of remote machine , but in output only -2 is printing everytime.
Please help how can i get correct output from this script.

Body:
This is what your script should look like

import paramiko
import sys
host=str(sys.argv[1])
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='88888',username='admin',password='888888',key_filename='88888')
stdin,stdout,stderr = ssh.exec_command('cpstat -f cpu os')
if stdout.channel.recv_exit_status() != 0:
    print("Error encountered")
else:
    print("Got something")
    print(stdout.channel.recv(-1).decode('utf-8'))
ssh.close()


问:
Get Multiple Toggle Button values on the basis of id in Angular?
I am trying to get value of toggle button as yes or no .. since there are so many questions coming dynamically .I want to get this of basis of item.id .. I am using Angular and Required to write the logic in TS file . Any help will be appreciated

My Html:-

```<code>                  <div class="form-group">
                     {{item.id}}.<label>{{item.question}}</label>
                      <label class="switch">
                      <input type="checkbox" id="togBtn" (change)="getToggleButtonValue($event)">
                      <div class="slider round">
                        <span class="on">ON</span>
                        <span class="off">OFF</span>
                      </div>
                    </label>
</code>```

答:
You should to attach the event of click for the toggle button. For example:

https://stackblitz.com/edit/angular-ivy-hx9czl

Body:
I am trying to get value of toggle button as yes or no .. since there are so many questions coming dynamically .I want to get this of basis of item.id .. I am using Angular and Required to write the logic in TS file . Any help will be appreciated

My Html:-

                     {{item.id}}.{{item.question}}

                      <input type="checkbox" id="togBtn" (change)="getToggleButtonValue($event)">

                        ON
                        OFF


问:
Getting key with maximum value in dictionary?
I have a dictionary where keys are strings, and values are integers.

```<code>stats = {'a': 1, 'b': 3000, 'c': 0}
</code>```

How do I get the key with the maximum value? In this case, it is 'b'.

Is there a nicer approach than using an intermediate list with reversed key-value tuples?

```<code>inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
</code>```

答:
Much simpler to understand approach:

```<code>mydict = { 'a':302, 'e':53, 'g':302, 'h':100 }
max_value_keys = [key for key in mydict.keys() if mydict[key] == max(mydict.values())]
print(max_value_keys) # prints a list of keys with max value
</code>```

Output: ['a', 'g']

Now you can choose only one key:

```<code>maximum = mydict[max_value_keys[0]]
</code>```

Body:
I have a dictionary where keys are strings, and values are integers.

stats = {'a': 1, 'b': 3000, 'c': 0}

How do I get the key with the maximum value? In this case, it is 'b'.

Is there a nicer approach than using an intermediate list with reversed key-value tuples?

inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])

Body:
Much simpler to understand approach:

mydict = { 'a':302, 'e':53, 'g':302, 'h':100 }
max_value_keys = [key for key in mydict.keys() if mydict[key] == max(mydict.values())]
print(max_value_keys) # prints a list of keys with max value

Output: ['a', 'g']

Now you can choose only one key:

maximum = mydict[max_value_keys[0]]


问:
DNNClassifier - How to obtain the parameters of various layers after training
```<code>def Classifier(parameters):

    learning = parameters[0]
    layers = parameters[1]
    nodes = parameters[2]
    hidden_layers =  [nodes for i in range(layers)]
    activation_function = tf.nn.sigmoid if parameters[3] == 0 else tf.nn.relu

    age_var = tf.feature_column.numeric_column('Age')
    shape_var = tf.feature_column.numeric_column('Shape')
    margin_var = tf.feature_column.numeric_column('Margin')
    density_var =tf.feature_column.numeric_column('Density')
    features = [age_var,shape_var,margin_var,density_var]

    return tf.estimator.DNNClassifier(hidden_units=hidden_layers,
                                      n_classes=2,
                                      feature_columns=features,
                                      activation_fn=activation_function,
                                      model_dir='/tmp/'+uuid.uuid4().hex,
                                      optimizer=tf.train.AdamOptimizer(learning_rate=learning),
                                      config=tf.contrib.learn.RunConfig(save_checkpoints_steps=250,
                                                                        save_checkpoints_secs=None,
                                                                        save_summary_steps=500))
</code>```

Is it possible to get the parameters of the various layers after training the model defined as above ?

If yes could you give me th commands for that

I am new/learning tensorflow

答:
I simple way would be to loop over the list of variable names of the DNNClassifier model returned by the Classifier function and call get_variable_value passing the name of each:

```<code>for variable_name in model.get_variable_names():
    print('Parameter Name: ', variable_name, ' Parameter Value: ', model.get_variable_value(variable_name))
</code>```

But this would still need you to pick out the weights of each single layer (/hiddenlayer_0/..., /hiddenlayer_1/... etc is what the DNNClassifier names its model's hidden layers by default).

You will have to loop over these param names and fetch the values of only those params for which the name has hiddenlayer_<num> in it, which means performing some string pattern matching. E.g. :

```<code>hidden_layer_0_params = {}
for variable_name in model.get_variable_names():
    if variable_name.startswith("dnn/hiddenlayer0"):
        hidden_layer_0_params[variable_name] = model.get_variable_value(variable_name)
</code>```

You can help improve this though! One way is to create and compile a separate tf.keras model first and then convert it into the required estimator instance using the tf.keras.estimator.model_to_estimator function.

The reason its advantageous is that tf.keras names its model params a little better, and they don't have a dnn/hiddenlayer_ prefix for the layer param names by default. For example, the param names for a tf.keras model will have no prefixes and are formatted like layer_with_weights-0/bias by default.

Here is a good tutorial to create an estimator instance from a keras model and using it for training and evaluation..

Body:
def Classifier(parameters):

    learning = parameters[0]
    layers = parameters[1]
    nodes = parameters[2]
    hidden_layers =  [nodes for i in range(layers)]
    activation_function = tf.nn.sigmoid if parameters[3] == 0 else tf.nn.relu

    age_var = tf.feature_column.numeric_column('Age')
    shape_var = tf.feature_column.numeric_column('Shape')
    margin_var = tf.feature_column.numeric_column('Margin')
    density_var =tf.feature_column.numeric_column('Density')
    features = [age_var,shape_var,margin_var,density_var]

    return tf.estimator.DNNClassifier(hidden_units=hidden_layers,
                                      n_classes=2,
                                      feature_columns=features,
                                      activation_fn=activation_function,
                                      model_dir='/tmp/'+uuid.uuid4().hex,
                                      optimizer=tf.train.AdamOptimizer(learning_rate=learning),
                                      config=tf.contrib.learn.RunConfig(save_checkpoints_steps=250,
                                                                        save_checkpoints_secs=None,
                                                                        save_summary_steps=500))

Is it possible to get the parameters of the various layers after training the model defined as above ?

If yes could you give me th commands for that

I am new/learning tensorflow

Body:
I simple way would be to loop over the list of variable names of the DNNClassifier model returned by the Classifier function and call get_variable_value passing the name of each:

for variable_name in model.get_variable_names():
    print('Parameter Name: ', variable_name, ' Parameter Value: ', model.get_variable_value(variable_name))

But this would still need you to pick out the weights of each single layer (/hiddenlayer_0/..., /hiddenlayer_1/... etc is what the DNNClassifier names its model's hidden layers by default).

You will have to loop over these param names and fetch the values of only those params for which the name has hiddenlayer_<num> in it, which means performing some string pattern matching. E.g. :

hidden_layer_0_params = {}
for variable_name in model.get_variable_names():
    if variable_name.startswith("dnn/hiddenlayer0"):
        hidden_layer_0_params[variable_name] = model.get_variable_value(variable_name)

You can help improve this though! One way is to create and compile a separate tf.keras model first and then convert it into the required estimator instance using the tf.keras.estimator.model_to_estimator function.

The reason its advantageous is that tf.keras names its model params a little better, and they don't have a dnn/hiddenlayer_ prefix for the layer param names by default. For example, the param names for a tf.keras model will have no prefixes and are formatted like layer_with_weights-0/bias by default.

Here is a good tutorial to create an estimator instance from a keras model and using it for training and evaluation..


问:
Search the object with like in "Find database objects" on snowflake.com
How to search the object with like instead of just starting with.

"Find database objects" currently allow only the object search with Starting name as name%.

is there a way to make it a %name% ?

答:
I think your question is about UI's search option. Unfortunately it only supports searching with starting name. On the other hand, you can use SHOW OBJECTS command to search everything in your account:

```<code>SHOW OBJECTS LIKE '%ATI%' IN ACCOUNT;
</code>```

https://docs.snowflake.com/en/sql-reference/sql/show-objects.html

Body:
I think your question is about UI's search option. Unfortunately it only supports searching with starting name. On the other hand, you can use SHOW OBJECTS command to search everything in your account:

SHOW OBJECTS LIKE '%ATI%' IN ACCOUNT;

https://docs.snowflake.com/en/sql-reference/sql/show-objects.html


问:
Submitting reCAPTCHA v2 with selenium and python - no form submit button
So I recently signed up with anti-captcha and have been testing with the https://github.com/ad-m/python-anticaptcha/blob/master/examples/recaptcha_selenium.py script.

I cannot get past a reCAPTCHA that has no submit button (hidden or visible) nor a clear way to submit for verification. I've used the anti-captcha firefox plugin, so I know it can be passed. But I am stuck at the point of doing this manually myself.

I thought this was going to be a helpful answer, but it doesn't go into depth. I am able to get the job.get_solution_response() token and enter it into the required textfield, but I cannot submit the "form."

Does anyone have success with this? I am also looking to do this in a headless version of the browser. Would a solution be different based on headless vs non-headless?

BTW, realtor(dot)com is the website I am having trouble with. If I am not aloud to post this site, please let me know so I can remove it.

答:
try to sendKeys of \n or Keys.Enter to the textfield.
This was my solution in my projects.
Also this is generic one</p>


问:
App description is not showing in tab configuration page header MS Bot for Teams (nodejs)
When the tab configuration page is loaded the description that I have added in AppDetails is not showing beside my app icon like it is shown for trello. I dont see anywhere in the docs regarding this.

I would be thankful for any help

答: The behavior is by design.Quite a while back we started giving developers more control (and vertical pixels) in the tab configuration flow and allow them to render their own description within the iframe. Everything within that header area is now controlled by the app. App description appears on click of about link. </p>


问:
Periodic "Lost connection to MySQL server during query" after Dockerizing Flask Web App
I have a Flask web app that used to run on a standalone server using the following:

Flask/SQLAlchemy

MariaDB

uwsgi

nginx

On the stand alone server this application ran fine.

I have since "dockerized" this application across two containers:

uwsgi-nginx-flask

MariaDB

Every since dockerizing I occasionally get this error (entire traceback posted at the end):

```<code>Lost connection to MySQL server during query
</code>```

The MariaDB log shows the following errors with verbose logging:

```<code>2020-05-10 18:35:32 130 [Warning] Aborted connection 130 to db: 'flspection2' user: 'fl-server' host: '172.19.0.1' (Got an error reading communication packets)
2020-05-10 18:45:34 128 [Warning] Aborted connection 128 to db: 'flspection2' user: 'fl-server' host: '172.19.0.1' (Got timeout reading communication packets)
</code>```

This is experienced by the user as a 502 Bad Gateway. If the user refreshes the page, this will often solve the problem. This issue arises at random. I have not been able to reproduce it at will, but over time it will inevitably show up.

What is causing this and how can I solve it?

What I've done:

Verified that the MariaDB container has a timeout is 28800. I've seen the error occur much sooner than 28800 seconds after restarting all the containers, so I don't think it is actually a timeout issue.

Set pool_recycle option to 120

Verified that Flask-SQLAlchemy is using a scoped_session which should avoid these timing out issues.

Changed network_mode to default per a comment. This did not solve the problem.

My thoughts are that it acts like the connection between flask and the database is unreliable, but as docker containers running on the same host, shouldn't that be quite reliable?

Relevant code:

database.py

```<code>from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
</code>```

config.py

```<code>class Config:
    ...
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://username:password@127.0.0.1/database?charset=utf8mb4'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ENGINE_OPTIONS = {
        'pool_recycle': 120
    }
    ...
</code>```

docker-compose.yml

```<code>version: "3.7"
services:
  db:
    restart: "always"
    build: ./docker/db
    volumes:
      - "~/db:/var/lib/mysql"
    environment:
      MYSQL_ROOT_PASSWORD: "password"
      MYSQL_DATABASE: "database"
      MYSQL_USER: "user"
      MYSQL_PASSWORD: "password"
    ports:
      - '3306:3306'
  nginx-uwsgi-flask:
    restart: "always"
    depends_on:
      - "db"
    build:
      context: .
      dockerfile: ./docker/nginx-uwsgi-flask/Dockerfile
    volumes:
      - "~/data/fileshare:/fileshare"
    ports:
      - "80:80"
      - "443:443"
    network_mode: "host"
</code>```

traceback

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
    context)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 509, in do_execute
    cursor.execute(statement, parameters)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute
    result = self._query(query)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query
    conn.query(q)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 517, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 732, in _read_query_result
    result.read()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1075, in read
    first_packet = self.connection._read_packet()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 657, in _read_packet
    packet_header = self._read_bytes(4)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 707, in _read_bytes
    CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python3.6/site-packages/flask_user/decorators.py", line 132, in decorator
    allowed = _is_logged_in_with_confirmed_email(user_manager)
  File "/usr/local/lib/python3.6/site-packages/flask_user/decorators.py", line 17, in _is_logged_in_with_confirmed_email
    if user_manager.call_or_get(current_user.is_authenticated):
  File "/usr/local/lib/python3.6/site-packages/werkzeug/local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/usr/local/lib/python3.6/site-packages/werkzeug/local.py", line 306, in _get_current_object
    return self.__local()
  File "/usr/local/lib/python3.6/site-packages/flask_login/utils.py", line 26, in <lambda>
    current_user = LocalProxy(lambda: _get_user())
  File "/usr/local/lib/python3.6/site-packages/flask_login/utils.py", line 335, in _get_user
    current_app.login_manager._load_user()
  File "/usr/local/lib/python3.6/site-packages/flask_login/login_manager.py", line 359, in _load_user
    return self.reload_user()
  File "/usr/local/lib/python3.6/site-packages/flask_login/login_manager.py", line 321, in reload_user
    user = self.user_callback(user_id)
  File "/usr/local/lib/python3.6/site-packages/flask_user/user_manager.py", line 130, in load_user_by_user_token
    user = self.db_manager.UserClass.get_user_by_token(user_token)
  File "/usr/local/lib/python3.6/site-packages/flask_user/user_mixin.py", line 51, in get_user_by_token
    user = user_manager.db_manager.get_user_by_id(user_id)
  File "/usr/local/lib/python3.6/site-packages/flask_user/db_manager.py", line 179, in get_user_by_id
    return self.db_adapter.get_object(self.UserClass, id=id)
  File "/usr/local/lib/python3.6/site-packages/flask_user/db_adapters/sql_db_adapter.py", line 48, in get_object
    return ObjectClass.query.get(id)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 924, in get
    ident, loading.load_on_pk_identity)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 1007, in _get_impl
    return db_load_fn(self, primary_key_identity)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/loading.py", line 250, in load_on_pk_identity
    return q.one()
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 2954, in one
    ret = self.one_or_none()
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 2924, in one_or_none
    ret = list(self)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 2995, in __iter__
    return self._execute_and_instances(context)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 3018, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 948, in execute
    return meth(self, multiparams, params)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 269, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1060, in _execute_clauseelement
    compiled_sql, distilled_params
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1200, in _execute_context
    context)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1413, in _handle_dbapi_exception
    exc_info
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 265, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 248, in reraise
    raise value.with_traceback(tb)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
    context)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 509, in do_execute
    cursor.execute(statement, parameters)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute
    result = self._query(query)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query
    conn.query(q)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 517, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 732, in _read_query_result
    result.read()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1075, in read
    first_packet = self.connection._read_packet()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 657, in _read_packet
    packet_header = self._read_bytes(4)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 707, in _read_bytes
    CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query') [SQL: 'SELECT user.is_active AS user_is_active, user.id AS user_id, user.username AS user_username, user.password AS user_password, user.reset_password_token AS user_reset_password_token, user.email AS user_email, user.email_confirmed_at AS user_email_confirmed_at, user.first_name AS user_first_name, user.last_name AS user_last_name \nFROM user \nWHERE user.id = %(param_1)s'] [parameters: {'param_1': 13}] (Background on this error at: http://sqlalche.me/e/e3q8)
</code>```

答: I solved this issue by migrating from a mariadb container to mysql. I still don't know what the root cause is.

Body:
I have a Flask web app that used to run on a standalone server using the following:

Flask/SQLAlchemy

MariaDB

uwsgi

nginx

On the stand alone server this application ran fine.

I have since "dockerized" this application across two containers:

uwsgi-nginx-flask

MariaDB

Every since dockerizing I occasionally get this error (entire traceback posted at the end):

Lost connection to MySQL server during query

The MariaDB log shows the following errors with verbose logging:

2020-05-10 18:35:32 130 [Warning] Aborted connection 130 to db: 'flspection2' user: 'fl-server' host: '172.19.0.1' (Got an error reading communication packets)
2020-05-10 18:45:34 128 [Warning] Aborted connection 128 to db: 'flspection2' user: 'fl-server' host: '172.19.0.1' (Got timeout reading communication packets)

This is experienced by the user as a 502 Bad Gateway. If the user refreshes the page, this will often solve the problem. This issue arises at random. I have not been able to reproduce it at will, but over time it will inevitably show up.

What is causing this and how can I solve it?

What I've done:

Verified that the MariaDB container has a timeout is 28800. I've seen the error occur much sooner than 28800 seconds after restarting all the containers, so I don't think it is actually a timeout issue.

Set pool_recycle option to 120

Verified that Flask-SQLAlchemy is using a scoped_session which should avoid these timing out issues.

Changed network_mode to default per a comment. This did not solve the problem.

My thoughts are that it acts like the connection between flask and the database is unreliable, but as docker containers running on the same host, shouldn't that be quite reliable?

Relevant code:

database.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

config.py

class Config:
    ...
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://username:password@127.0.0.1/database?charset=utf8mb4'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ENGINE_OPTIONS = {
        'pool_recycle': 120
    }
    ...

docker-compose.yml

version: "3.7"
services:
  db:
    restart: "always"
    build: ./docker/db
    volumes:
      - "~/db:/var/lib/mysql"
    environment:
      MYSQL_ROOT_PASSWORD: "password"
      MYSQL_DATABASE: "database"
      MYSQL_USER: "user"
      MYSQL_PASSWORD: "password"
    ports:
      - '3306:3306'
  nginx-uwsgi-flask:
    restart: "always"
    depends_on:
      - "db"
    build:
      context: .
      dockerfile: ./docker/nginx-uwsgi-flask/Dockerfile
    volumes:
      - "~/data/fileshare:/fileshare"
    ports:
      - "80:80"
      - "443:443"
    network_mode: "host"

traceback

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
    context)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 509, in do_execute
    cursor.execute(statement, parameters)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute
    result = self._query(query)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query
    conn.query(q)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 517, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 732, in _read_query_result
    result.read()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1075, in read
    first_packet = self.connection._read_packet()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 657, in _read_packet
    packet_header = self._read_bytes(4)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 707, in _read_bytes
    CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python3.6/site-packages/flask_user/decorators.py", line 132, in decorator
    allowed = _is_logged_in_with_confirmed_email(user_manager)
  File "/usr/local/lib/python3.6/site-packages/flask_user/decorators.py", line 17, in _is_logged_in_with_confirmed_email
    if user_manager.call_or_get(current_user.is_authenticated):
  File "/usr/local/lib/python3.6/site-packages/werkzeug/local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/usr/local/lib/python3.6/site-packages/werkzeug/local.py", line 306, in _get_current_object
    return self.__local()
  File "/usr/local/lib/python3.6/site-packages/flask_login/utils.py", line 26, in <lambda>
    current_user = LocalProxy(lambda: _get_user())
  File "/usr/local/lib/python3.6/site-packages/flask_login/utils.py", line 335, in _get_user
    current_app.login_manager._load_user()
  File "/usr/local/lib/python3.6/site-packages/flask_login/login_manager.py", line 359, in _load_user
    return self.reload_user()
  File "/usr/local/lib/python3.6/site-packages/flask_login/login_manager.py", line 321, in reload_user
    user = self.user_callback(user_id)
  File "/usr/local/lib/python3.6/site-packages/flask_user/user_manager.py", line 130, in load_user_by_user_token
    user = self.db_manager.UserClass.get_user_by_token(user_token)
  File "/usr/local/lib/python3.6/site-packages/flask_user/user_mixin.py", line 51, in get_user_by_token
    user = user_manager.db_manager.get_user_by_id(user_id)
  File "/usr/local/lib/python3.6/site-packages/flask_user/db_manager.py", line 179, in get_user_by_id
    return self.db_adapter.get_object(self.UserClass, id=id)
  File "/usr/local/lib/python3.6/site-packages/flask_user/db_adapters/sql_db_adapter.py", line 48, in get_object
    return ObjectClass.query.get(id)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 924, in get
    ident, loading.load_on_pk_identity)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 1007, in _get_impl
    return db_load_fn(self, primary_key_identity)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/loading.py", line 250, in load_on_pk_identity
    return q.one()
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 2954, in one
    ret = self.one_or_none()
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 2924, in one_or_none
    ret = list(self)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 2995, in __iter__
    return self._execute_and_instances(context)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 3018, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 948, in execute
    return meth(self, multiparams, params)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 269, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1060, in _execute_clauseelement
    compiled_sql, distilled_params
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1200, in _execute_context
    context)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1413, in _handle_dbapi_exception
    exc_info
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 265, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 248, in reraise
    raise value.with_traceback(tb)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
    context)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 509, in do_execute
    cursor.execute(statement, parameters)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute
    result = self._query(query)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query
    conn.query(q)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 517, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 732, in _read_query_result
    result.read()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1075, in read
    first_packet = self.connection._read_packet()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 657, in _read_packet
    packet_header = self._read_bytes(4)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 707, in _read_bytes
    CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query') [SQL: 'SELECT user.is_active AS user_is_active, user.id AS user_id, user.username AS user_username, user.password AS user_password, user.reset_password_token AS user_reset_password_token, user.email AS user_email, user.email_confirmed_at AS user_email_confirmed_at, user.first_name AS user_first_name, user.last_name AS user_last_name \nFROM user \nWHERE user.id = %(param_1)s'] [parameters: {'param_1': 13}] (Background on this error at: http://sqlalche.me/e/e3q8)


问:
How to set cookie for a different website when open new browser tab
Good afternoon,
I have a problem that I would like to get your help with if it were possible.

First of all I would like to mention that I am using Angular with TypeScript.
I am trying to make a kind of single sign on of several websites in a single application and I am having some problems when it comes to redirecting to the desired website.
All websites that I am trying to sign in cannot be changed and I can only make changes to the application I am developing.
On the client side, I make a request to the API (NodeJS) that performs the authentication on the intended website and returns an authentication cookie to the client.

So far so good, it's working perfectly. The problem arises when I need to open a new browser tab and pass the authentication cookie I received.
When opening a new tab I am forwarding to the page after login and I need the cookie for that task.

I tried to set the cookie in the browser to a different domain but without success.
Can someone help me, whether it is trying to find a solution or indicating a possible different way to solve the problem?
I would like to mention that the domain of all websites are different from each other and different from the application I am developing.

Thank you in advance to anyone who can help or direct me to the solution and I apologize if I did not understand perfectly what I want. Any doubts tell me that I try to explain better.

Regards,
André Pinto

答:
As mentioned above you won't be able to achieve this with cookies; being able to set cookies for other domains would be a massive security issue.

If you control the other website and have access to the backend, then your backend can handshake to identify the user. Otherwise you could look at using a querystring redirection to authenticate the user.

All the best.


问:
The right way to pass a input to the typescript file
I know about this way to send a input from the user to the typescript (angular) :

```<code>    <form >
    <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" />
    </form>
</code>```

But its looking for not very effective , i create a reference to the DOM with #input and after that send the input.value .

After all, I am very confused about the input.value does he refer to #input or to to (input)=...;.

Bottom line, is there a more efficient way to pass the value the user puts into the box, into the typescript file and then use it for another tag in the HTML file?

For example the user put a size of text and i want to use with the use on another tag on HTML ....

答:
I think you are trying to use angular input inside a html input tag, which is not possible.

You need to use a keyboard event handler like "keyup", "keydown"...

```<code><input type="text" [(ngModel)]="inputColor" (keyup)="sendInput($event)" />
</code>```

Body:
I know about this way to send a input from the user to the typescript (angular) :

    <form >
    <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" />
    </form>

But its looking for not very effective , i create a reference to the DOM with #input and after that send the input.value .

After all, I am very confused about the input.value does he refer to #input or to to (input)=...;.

Bottom line, is there a more efficient way to pass the value the user puts into the box, into the typescript file and then use it for another tag in the HTML file?

For example the user put a size of text and i want to use with the use on another tag on HTML ....

Body:
I think you are trying to use angular input inside a html input tag, which is not possible.

You need to use a keyboard event handler like "keyup", "keydown"...

<input type="text" [(ngModel)]="inputColor" (keyup)="sendInput($event)" />


问:
problem with "title" in UINavigationController
I am having a problem with title and UINavigationController. I am using the following code at UIViewControllerCurrent and when I get back from NextViewController, the title of the NavBar is still "Previous" ..Can anyone kindly help me out with this problem ? Thanks.</p>

```<code>[self setTitle:@"Previous"];
NextViewController *controller = [[NextViewController alloc] init];
[[self navigationController] pushViewController:controller animated:YES];
[controller release], controller = nil;

- (void)viewWillAppear:(BOOL)animated; {
[self setTitle:@"Real Title"];
[super viewWillAppear:animated]; }
</code>```

答:
If dasdoms solution is not working the try the following.

In the NextViewController just before poping out run this code.

```<code>for (int i =0; i < [[self.navigationController viewControllers] count]; i++)
    {
        UIViewController *aController = [[self.navigationController viewControllers] objectAtIndex:i];

        if ([aController isKindOfClass:[PreviousViewController class]])
        {
            PreviousViewController *aPreviousViewController = (PreviousViewController *)aController;
            aPreviousViewController.title = @" Real Title";
        }

    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having a problem with title and UINavigationController. I am using the following code at UIViewControllerCurrent and when I get back from NextViewController, the title of the NavBar is still "Previous" ..Can anyone kindly help me out with this problem ? Thanks.

[self setTitle:@"Previous"];
NextViewController *controller = [[NextViewController alloc] init];
[[self navigationController] pushViewController:controller animated:YES];
[controller release], controller = nil;

- (void)viewWillAppear:(BOOL)animated; {
[self setTitle:@"Real Title"];
[super viewWillAppear:animated]; }

Body:
If dasdoms solution is not working the try the following.

In the NextViewController just before poping out run this code.

for (int i =0; i < [[self.navigationController viewControllers] count]; i++)
    {
        UIViewController *aController = [[self.navigationController viewControllers] objectAtIndex:i];

        if ([aController isKindOfClass:[PreviousViewController class]])
        {
            PreviousViewController *aPreviousViewController = (PreviousViewController *)aController;
            aPreviousViewController.title = @" Real Title";
        }

    }


问:
Pattern Observer and Spring
I use Spring. I implemented the pattern Observer as shown in the examples on the Internet.

```<code>@Component
public class ObserverManager {

    private Map<String, List<IObserver>> observers = new HashMap<>();

    public void subscribe(String type, IObserver observer){
        // do something
    }

    public void notifyObserver(String type, Object data){
        observers.get(type).forEach(observer -> observer.update(data));
    }

    // more
}
</code>```

```<code>@Component
public class NewsObserver implements IObserver {
    @Override
    public void update(Object o) {
        //do something
    }
}
</code>```

But I don't understand how to correctly add an observer to ObserverManager. It can be injected via the constructor. But if the observers are 7-8? This is a lot for the constructor.How to solve this problem correctly?

答:
There are many approaches to this problem, which include (could be more):

Observers registering themselves

A very common approach to this problem is to have the observers register themselves, this is clean as an observer knows exactly what it wants to observe.

@Component
public class NewsObserver implements IObserver {
    @Autowired
    public NewsObserver(IObserverManager observerManager) {
        observerManager.subscribe("interestingType", this);
    }

    @Override
    public void update(Object o) {
        //do something
    }
}
```

<p><strong>Inject a collection</strong></p>

<p>Another approach would be to use a <code>List<IObserver></code> in the <code>ObserverManager</code> constructor:</p>

<pre class="lang-java prettyprint-override"><code>@Autowired
public ObserverManager(List<IObserver> observers) {
    observersByType.put(type, observers);
}
</code>```

But where this type comes from? If it's the observer that knows about it, you would have to first iterate the received list and get the proper type from the observer and register each one of them with that type.

Using configuration Beans

By dropping the @Component from the NewsObserver and registering the beans manually, you can do something like:

@Bean
@Autowired
public IObserver newsObserver1(ObserverManager manager) {
    IObserver o1 = new NewsObserver();
    manager.subscribe("type1", o1);
    return o1;
}

@Bean
@Autowired
public IObserver newsObserver2(ObserverManager manager) {
    IObserver o2 = new NewsObserver();
    manager.subscribe("type2", o2);
    return o2;
}
```

What to choose?

I guess it depends.

IMO, the cleaner approach is the first. Notice how easy is to inject a mocked ObserverManager for testing. And who better to know what type of news the observer is interested in than the observer itself? The observers can control what and when they are observing and when to stop it.

EDIT: As correctly pointed out in the comments, this introduces a cyclic dependency between the observer and the observer manager. As it stands, because the instance of observer manager is not kept in the observer and there's no way you can call the observer constructor twice for the same observer instance, the loop won't ever happen. But it's still a design smell that may lead to problems in the future.

Cyclic dependencies between two entities are generally solved by introducing a third-party to manage the relationship between those two entities, which leads us to one of the mentioned alternatives.

The configuration beans approach is interesting, in the sense that there's no dependency in the NewsObserver, hence, no cyclic dependency, it just sits there's and waits for updates. It should be noted though, that managing which observer receives which type and when to stop the subscription needs to be done outside the observer, which may not seem natural.

Notes:

As a side note, consider using a Multimap (available for example with Guava) for the observers map. It's easier to manage than a Map of List, but it requires an extra dependency because Java has no built-in type like it.

Also, unless you really want, there's no need to implement the Observer pattern yourself. These are really robust implementations of it and offer really good operations on top of it:

ReactiveX, especially the Java implementation.

Vertx, especially the EventBus.

Title: Pattern Observer and Spring

Body:
I use Spring. I implemented the pattern Observer as shown in the examples on the Internet.

@Component
public class ObserverManager {

    private Map<String, List<IObserver>> observers = new HashMap<>();

    public void subscribe(String type, IObserver observer){
        // do something
    }

    public void notifyObserver(String type, Object data){
        observers.get(type).forEach(observer -> observer.update(data));
    }

    // more
}

@Component
public class NewsObserver implements IObserver {
    @Override
    public void update(Object o) {
        //do something
    }
}

But I don't understand how to correctly add an observer to ObserverManager. It can be injected via the constructor. But if the observers are 7-8? This is a lot for the constructor.How to solve this problem correctly?

Body:
There are many approaches to this problem, which include (could be more):

Observers registering themselves

A very common approach to this problem is to have the observers register themselves, this is clean as an observer knows exactly what it wants to observe.

@Component
public class NewsObserver implements IObserver {
    @Autowired
    public NewsObserver(IObserverManager observerManager) {
        observerManager.subscribe("interestingType", this);
    }

    @Override
    public void update(Object o) {
        //do something
    }
}

Inject a collection

Another approach would be to use a List<IObserver> in the ObserverManager constructor:

@Autowired
public ObserverManager(List<IObserver> observers) {
    observersByType.put(type, observers);
}

But where this type comes from? If it's the observer that knows about it, you would have to first iterate the received list and get the proper type from the observer and register each one of them with that type.

Using configuration Beans

By dropping the @Component from the NewsObserver and registering the beans manually, you can do something like:

@Bean
@Autowired
public IObserver newsObserver1(ObserverManager manager) {
    IObserver o1 = new NewsObserver();
    manager.subscribe("type1", o1);
    return o1;
}

@Bean
@Autowired
public IObserver newsObserver2(ObserverManager manager) {
    IObserver o2 = new NewsObserver();
    manager.subscribe("type2", o2);
    return o2;
}

What to choose?

I guess it depends.

IMO, the cleaner approach is the first. Notice how easy is to inject a mocked ObserverManager for testing. And who better to know what type of news the observer is interested in than the observer itself? The observers can control what and when they are observing and when to stop it.

EDIT: As correctly pointed out in the comments, this introduces a cyclic dependency between the observer and the observer manager. As it stands, because the instance of observer manager is not kept in the observer and there's no way you can call the observer constructor twice for the same observer instance, the loop won't ever happen. But it's still a design smell that may lead to problems in the future.

Cyclic dependencies between two entities are generally solved by introducing a third-party to manage the relationship between those two entities, which leads us to one of the mentioned alternatives.

The configuration beans approach is interesting, in the sense that there's no dependency in the NewsObserver, hence, no cyclic dependency, it just sits there's and waits for updates. It should be noted though, that managing which observer receives which type and when to stop the subscription needs to be done outside the observer, which may not seem natural.

Notes:

As a side note, consider using a Multimap (available for example with Guava) for the observers map. It's easier to manage than a Map of List, but it requires an extra dependency because Java has no built-in type like it.

Also, unless you really want, there's no need to implement the Observer pattern yourself. These are really robust implementations of it and offer really good operations on top of it:

ReactiveX, especially the Java implementation.

Vertx, especially the EventBus.


问:
Insert value list does not match column list on Laravel nullable()
I have a DB table with the following structure:

Table Migration:

```<code>Schema::create('initiatives', function (Blueprint $table) {

    $table->id();
    $table->string('name');
    $table->unsignedBigInteger('initiative_group_id');
    $table->string('initiative_owner')->nullable();
    $table->date('start_date')->nullable();
    $table->date('end_date')->nullable();
    $table->timestamps();

    $table->foreign('initiative_group_id')
        ->references('id')
        ->on('initiative_groups')
        ->onDelete('cascade');
});
</code>```

Now, I'm trying to seed that table with some rows:

Database seeder

```<code>public function run()
{
    DB::table('initiatives')->insert([
        ['name' => 'A1', 'initiative_group_id' => 1, 'initiative_owner' => 'Person A'],
        ['name' => 'B1', 'initiative_group_id' => 2, 'initiative_owner' => 'Person B'],
        ['name' => 'B2', 'initiative_group_id' => 2],
        ['name' => 'D1', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D2', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D3', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'E1', 'initiative_group_id' => 5],
    ]);
}
</code>```

I get the following error:

```<code>SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 12;
</code>```

So I know that I am selectively including and excluding some columns in these inserts (sometimes I have an initiative_owner and sometimes not), but can I not specify not to insert some columns as I've set them to nullable? Is there a way to do that?

答:
If you are doing multiple insertions in one go from seeder, but the length of all arrays must be the same.

```<code> DB::table('initiatives')->insert([
        ['name' => 'A1', 'initiative_group_id' => 1, 'initiative_owner' => 'Person A'],
        ['name' => 'B1', 'initiative_group_id' => 2, 'initiative_owner' => 'Person B'],
        ['name' => 'B2', 'initiative_group_id' => 2], //initiative_owner is missing
        ['name' => 'D1', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D2', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D3', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'E1', 'initiative_group_id' => 5], //initiative_owner is missing
    ]);
</code>```

You can set them null but don't skip.

The second option you can insert two different arrays.

```<code>DB::table('initiatives')->insert([
        ['name' => 'A1', 'initiative_group_id' => 1, 'initiative_owner' => 'Person A'],
        ['name' => 'B1', 'initiative_group_id' => 2, 'initiative_owner' => 'Person B'],
        ['name' => 'D1', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D2', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D3', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
    ]);

DB::table('initiatives')->insert([
    ['name' => 'B2', 'initiative_group_id' => 2],
    ['name' => 'E1', 'initiative_group_id' => 5],
]);
</code>```

Body:
I have a DB table with the following structure:

Table Migration:

Schema::create('initiatives', function (Blueprint $table) {

    $table->id();
    $table->string('name');
    $table->unsignedBigInteger('initiative_group_id');
    $table->string('initiative_owner')->nullable();
    $table->date('start_date')->nullable();
    $table->date('end_date')->nullable();
    $table->timestamps();

    $table->foreign('initiative_group_id')
        ->references('id')
        ->on('initiative_groups')
        ->onDelete('cascade');
});

Now, I'm trying to seed that table with some rows:

Database seeder

public function run()
{
    DB::table('initiatives')->insert([
        ['name' => 'A1', 'initiative_group_id' => 1, 'initiative_owner' => 'Person A'],
        ['name' => 'B1', 'initiative_group_id' => 2, 'initiative_owner' => 'Person B'],
        ['name' => 'B2', 'initiative_group_id' => 2],
        ['name' => 'D1', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D2', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D3', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'E1', 'initiative_group_id' => 5],
    ]);
}

I get the following error:

SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 12;

So I know that I am selectively including and excluding some columns in these inserts (sometimes I have an initiative_owner and sometimes not), but can I not specify not to insert some columns as I've set them to nullable? Is there a way to do that?

Body:
If you are doing multiple insertions in one go from seeder, but the length of all arrays must be the same.

 DB::table('initiatives')->insert([
        ['name' => 'A1', 'initiative_group_id' => 1, 'initiative_owner' => 'Person A'],
        ['name' => 'B1', 'initiative_group_id' => 2, 'initiative_owner' => 'Person B'],
        ['name' => 'B2', 'initiative_group_id' => 2], //initiative_owner is missing
        ['name' => 'D1', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D2', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D3', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'E1', 'initiative_group_id' => 5], //initiative_owner is missing
    ]);

You can set them null but don't skip.

The second option you can insert two different arrays.

DB::table('initiatives')->insert([
        ['name' => 'A1', 'initiative_group_id' => 1, 'initiative_owner' => 'Person A'],
        ['name' => 'B1', 'initiative_group_id' => 2, 'initiative_owner' => 'Person B'],
        ['name' => 'D1', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D2', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
        ['name' => 'D3', 'initiative_group_id' => 4, 'initiative_owner' => 'Person C'],
    ]);

DB::table('initiatives')->insert([
    ['name' => 'B2', 'initiative_group_id' => 2],
    ['name' => 'E1', 'initiative_group_id' => 5],
]);


问:
ClassNotFoundException: java.security.acl.Group on WildFly 19.1 using Java 14
I migrated a Web application that worked fine on WildFly 17 on Java 11 to the latest versions of both: WildFly 19 on Java 14. In the end I'm getting a ClassNotFoundException: java.security.acl.Group, probably because the Web application uses JAAS.

Note that a similar Web application built following a tutorial of my own worked fine, but it doesn't use JAAS. That and the package java.security.acl made me think JAAS is related.

Searching the Web I found issue WFCORE-4282 at WildFly's JIRA which seems to imply that although they knew this java.security.acl.Group class was deprecated more than a year ago, WildFly 19 still requires it and Java 14 did actually remove it, thus causing the ClassNotFoundException for me.

Is my interpretation correct? Does WildFly 19 + Java 14 + JAAS = ClassNotFoundException necessarily or has anyone managed to make it work? Or maybe I'm doing something wrong? It just seems to me such a huge problem for JBoss to have overlooked on WildFly...

Update: I removed Java 14, installed Java 13, reinstalled Eclipse and WildFly and redeployed de application and it worked, so WildFly 19 + Java 13 + JAAS = OK!

答:
The java.security.acl API was terminally deprecated and has been removed in Java 14: see release notes:

https://jdk.java.net/14/release-notes


问:
Function overload not compatible with implementation
I'm trying to figure out why some code I'm looking at is not working. I have a structure similar to this:

function getValidity(x: "v1"): boolean;
function getValidity(x: "v2"): { a: number; b: number };
function getValidity(x: any) {
  if (x === 'v1') {
    return true;
  } else {
    return { a: 1, b: 2 };
  }
}
```

But I get the error

This overload signature is not compatible with its implementation signature.(2394)

Looking at examples I thought this would work, but I'm obviously missing something. What is it?

答:
```<code>function getValidity(x: 'v1'): boolean;
function getValidity(x: 'v2'): { a: number; b: number };
function getValidity(x: 'v1' | 'v2'): boolean | { a: number; b: number } {
  if (x === 'v1') {
    return true;
  } else {
    return { a: 1, b: 2 };
  }
}

console.log(getValidity('v1'));
console.log(getValidity('v2'));
</code>```

Body:
I'm trying to figure out why some code I'm looking at is not working. I have a structure similar to this:

function getValidity(x: "v1"): boolean;
function getValidity(x: "v2"): { a: number; b: number };
function getValidity(x: any) {
  if (x === 'v1') {
    return true;
  } else {
    return { a: 1, b: 2 };
  }
}

But I get the error

This overload signature is not compatible with its implementation signature.(2394)

Looking at examples I thought this would work, but I'm obviously missing something. What is it?


问:
Is there a way to perform all Modernizr tests all at once?
I'm new to Modernizr and I'm just looking for a simple way to check for overall browser compatibility. I've generated a Modernizr script to test for only the most essential components of my web application, which is highly dependent on HTML5, CSS3, and modern JavaScript methods. Is there a way to run all of these tests simultaneously? Looking over the documentation, I see plenty of ways to test each feature one by one, but I'm not seeing a way to do it all at once. I'm hoping to do something like this:

Pseudocode

```<code>if (Modernizr.testAll()) {
  // Load site
} else {
  // Redirect to compatibility page
}
</code>```

答:
Use this Code if you want to display all feature detections in the browser:</p>
```<code><!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Modernizr Test</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.0.6/modernizr.min.js"></script>

</head>
<body>
<h1>Feature Detection</h1>
<div id="feature-detection-result">

</div>
<script>
    var features = Object.keys(Modernizr);
    features = features.sort();

    features.forEach(feature => {
        if (typeof Modernizr[feature] === "boolean") {
            var element = document.createElement('p');
            element.innerHTML = feature + ' ' + Modernizr[feature];
            document.getElementById('feature-detection-result').appendChild(element);
        }
    });
</script>
</body>
</html>
</code>```

Body:
I'm new to Modernizr and I'm just looking for a simple way to check for overall browser compatibility. I've generated a Modernizr script to test for only the most essential components of my web application, which is highly dependent on HTML5, CSS3, and modern JavaScript methods. Is there a way to run all of these tests simultaneously? Looking over the documentation, I see plenty of ways to test each feature one by one, but I'm not seeing a way to do it all at once. I'm hoping to do something like this:

Pseudocode

if (Modernizr.testAll()) {
  // Load site
} else {
  // Redirect to compatibility page
}

Body:
Use this Code if you want to display all feature detections in the browser:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Modernizr Test</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.0.6/modernizr.min.js"></script>

</head>
<body>
<h1>Feature Detection</h1>
<div id="feature-detection-result">

</div>
<script>
    var features = Object.keys(Modernizr);
    features = features.sort();

    features.forEach(feature => {
        if (typeof Modernizr[feature] === "boolean") {
            var element = document.createElement('p');
            element.innerHTML = feature + ' ' + Modernizr[feature];
            document.getElementById('feature-detection-result').appendChild(element);
        }
    });
</script>
</body>
</html>


问:
C#: How to keep track of the UID of messages between folders?
I'm moving messages from the inbox folder to a new folder. After a while I need to move some of these messages(not all) to a new folder. The problem with this is that everytime I move a message the uid changes. How can I do this without moving the wrong message?</p>

答: You're "moving" also involves an INSERT into DB to keep track of UIDs? If yes, watch for autogenerated PKs.</p>


问:
How To Get Every Alternate Object In Array In JS
I wanted to know how can we get every alternate object in a array. For EG -

```<code>arr = ["foo","bar","foo1","bar1"]
</code>```

I Need The values -

```<code>fir_alt = ["foo","foo1"]
sec_alt = ["bar","bar1"]
</code>```

If This Helps This Is My Intention -

I am trying to link localstorage and firestore using the js-sdk.. Data is in array and have to take the array to store it back in localstorage.fir_alt would be the keys and sec_alt would be values. So I Can Make it Much More Multi-Device..

Thanks In Advance

答: I'd use an index variable and a loop(for/next or your fav).  Examine the index on each iteration of the loop, and determine if the index is odd or even(or 0), then take the appropriate action to capture the desired values.</p>

Body:
I wanted to know how can we get every alternate object in a array. For EG -

arr = ["foo","bar","foo1","bar1"]

I Need The values -

fir_alt = ["foo","foo1"]
sec_alt = ["bar","bar1"]

If This Helps This Is My Intention -

I am trying to link localstorage and firestore using the js-sdk.. Data is in array and have to take the array to store it back in localstorage.fir_alt would be the keys and sec_alt would be values. So I Can Make it Much More Multi-Device..

Thanks In Advance


问:
Is `.` destination for the ADD/COPY dockerfile commands resolved with respect to WORKDIR?
Dockerfile ADD/COPY commands support the destination value to be a relative (to WORKDIR) path or an absolute path. Also, the source value is always the build context.

However, if the destination is specified as ., then is it resolved with respect to the WORKDIR (and does it default to the root (C:) if WORKDIR is not specified)?

答:
```<code>WORKDIR app
</code>```

this statement creates a folder named app and moves to that directory which is app

```<code>COPY <host> <container>
</code>```

host: relative location where the docker file exists.

container: location in the container which will be relative to where you are presently in the container. You initially start in the root directory of the container but when you use RUN cd or WORKDIR on dockerfile then the location would be relative to where you are presently in the container.

Body:
WORKDIR app

this statement creates a folder named app and moves to that directory which is app

COPY <host> <container>

host: relative location where the docker file exists.

container: location in the container which will be relative to where you are presently in the container. You initially start in the root directory of the container but when you use RUN cd or WORKDIR on dockerfile then the location would be relative to where you are presently in the container.


问:
For loop for iterating between dates
I have the following function that gathers data and parses them to dataframes.

```<code> df <- read_URL('2019-01-15','2019-01-01', token = token)
</code>```

Now i want to iterate this function between a range of the following dates, and bind all the dataframes together. The dates:

```<code> start_dates <- c(seq(as.Date("2019-01-01"), as.Date("2020-06-01"), by = "month"))
 end_dates <- start_dates + 15
</code>```

I have written a for loop but unfortunately it does not work. My for loop is:

```<code> mytempfile <- tempfile()

for (start_date in start_dates){
  for (end_date in end_dates){
    df <- read_URL(start_date,end_date, token = token)
    data <- rbind(df,mytempfile)
  }
}
</code>```

Also please note that the function is irrelevant as it obviously works before trying the for loop, and i'm not including it for confidential reasons.
Any help will be appreciated

答:
You can try something like creating a data.frame of your combinations, which also allows you to track your list:

```<code>dates_df = expand.grid(start=start_dates,end=end_dates)

data = lapply(1:nrow(dates_df),function(i){

    read_URL(dates_df$start[i],dates_df$end[i], token = token)
})

data= do.call(rbind,data)
</code>```

I cannot test this code because the example you have is not reproducible. If you can provide one, it would help a lot.

Title: For loop for iterating between dates

Body:
I have the following function that gathers data and parses them to dataframes.

 df <- read_URL('2019-01-15','2019-01-01', token = token)

Now i want to iterate this function between a range of the following dates, and bind all the dataframes together. The dates:

 start_dates <- c(seq(as.Date("2019-01-01"), as.Date("2020-06-01"), by = "month"))
 end_dates <- start_dates + 15

I have written a for loop but unfortunately it does not work. My for loop is:

 mytempfile <- tempfile()

for (start_date in start_dates){
  for (end_date in end_dates){
    df <- read_URL(start_date,end_date, token = token)
    data <- rbind(df,mytempfile)
  }
}

Also please note that the function is irrelevant as it obviously works before trying the for loop, and i'm not including it for confidential reasons.
Any help will be appreciated

Body:
You can try something like creating a data.frame of your combinations, which also allows you to track your list:

dates_df = expand.grid(start=start_dates,end=end_dates)

data = lapply(1:nrow(dates_df),function(i){

    read_URL(dates_df$start[i],dates_df$end[i], token = token)
})

data= do.call(rbind,data)

I cannot test this code because the example you have is not reproducible. If you can provide one, it would help a lot.


问:
How to pass an element to another component (easiest way)?
I have a string in one of the components and I would like to send it to another component when the submit button is pushed. I found solutions (input, emit...) but none of them worked.

This is my component from where I'd like to pass the variable:

```<code>export class UsersComponent {
  public data: string;

  public exportDocument() { // This function is called, when the submit button is pushed!
     this.data = doc.output("datauristring");
     // I have no idea what to write here, to pass this variable
  }
}
</code>```

Other component:

```<code>export class CvPageComponent implements OnInit {
  public cvData; // This should be equal with the value of "data"
}
</code>```

答:
In your cvPageComponent.html you use output

<user-component (cvData) = "getCvData($event)">

on your page you create a method that handle your cvDate like this:

```<code>public getCvData(cvData: any) {
    // your code

  }
</code>```

and in your userComponent you should mark cvData as output value like this

@output() cvData: EventEmitter<any> = new EventEmitter<any>

in your method:

```<code>public exportDocument() {
// This function is called, when the submit button is pushed!
     this.data = doc.output("datauristring");
     cvData.emit(this.data);
  }
}
</code>```

Body:
I have a string in one of the components and I would like to send it to another component when the submit button is pushed. I found solutions (input, emit...) but none of them worked.

This is my component from where I'd like to pass the variable:

export class UsersComponent {
  public data: string;

  public exportDocument() { // This function is called, when the submit button is pushed!
     this.data = doc.output("datauristring");
     // I have no idea what to write here, to pass this variable
  }
}

Other component:

export class CvPageComponent implements OnInit {
  public cvData; // This should be equal with the value of "data"
}

Body:
In your cvPageComponent.html you use output

<user-component (cvData) = "getCvData($event)">

on your page you create a method that handle your cvDate like this:

public getCvData(cvData: any) {
    // your code

  }

and in your userComponent you should mark cvData as output value like this

@output() cvData: EventEmitter<any> = new EventEmitter<any>

in your method:

public exportDocument() {
// This function is called, when the submit button is pushed!
     this.data = doc.output("datauristring");
     cvData.emit(this.data);
  }
}


问:
Caps Lock problem in Ubuntu VMWare virtual Machine
I'm running a vmware virtual machine (not vmware pro) on which I have given 2 GB RAM from my laptop . The problem is whenever I press caps lock when writing text inside the virtual machine and I get capital letters when I press it again and I write some text I get mixed letters ex. (ExAMPLe instead of example )
I went to my vm settings but I didn't find something about my keyboard functionality . I would appreciate your help with helping me solve this problem . (feel free to ask for more info that I should include about the question )</p>

答:
I had the same problem and fixed it by adding this line to the .vmx file for the Ubuntu VM:

```<code>mks.win32.useInjectedMagic=FALSE
</code>```

Edit 2020-09-17: another user with the same problem had to apply a small adjustment, quoting the "FALSE" value:

```<code>mks.win32.useInjectedMagic = "FALSE"
</code>```

Body:
I had the same problem and fixed it by adding this line to the .vmx file for the Ubuntu VM:

mks.win32.useInjectedMagic=FALSE

Edit 2020-09-17: another user with the same problem had to apply a small adjustment, quoting the "FALSE" value:

mks.win32.useInjectedMagic = "FALSE"


问:
.innerHTML not working or am I using it wrong?
If I understand right, .innerHTML should overwrite whatever was in a certain div or span.
For example:

```<code><table width="90%" border="0" align="center" cellpadding="5" cellspacing="0">

  <tr>
    <td colspan="2" align="left">Via Email:</td>
    <td width="1070" align="right"></td>
  </tr>

  <script>
  $('#addEmail').click(function()       {
document.getElementById('emailList').innerHTML = "12345";
  });
  </script>

      <span  id="emailList">
   <tr>
    <td width="27" align="left"><img src="icon_mail.png" width="24" height="24"></td>
    <td width="228" align="left">123obama@whitehouse.com</td>
    <td align="right"><a href="#" id="dialog_link" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-close"></span>remove</a></td>
  </tr>
     </span>

  <tr>
    <td colspan="3" align="left"><br>
      <input name="input4" type="text" value="vova@kremlin.ru" size="20">
      <a href="#" id="addEmail" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-mail-closed"></span>Add Email</a></td>
    </tr>
</table>
</code>```

Therefor upon click of #addEmail button, everything inside  would be removed and replaced by "12345".

Yet in reality it doesn't do anything to that span, but just prints out 12345 in the place, where the script is.

Any ideas what could be wrong?

答:
You are wrapping a
 in a span. That is going to lead to unpredictable results. Especially if you then remove the table row.

Body:
If I understand right, .innerHTML should overwrite whatever was in a certain div or span.
For example:

    Via Email:

    123obama@whitehouse.com
    remove

      <input name="input4" type="text" value="vova@kremlin.ru" size="20">
      Add Email

Therefor upon click of #addEmail button, everything inside  would be removed and replaced by "12345".

Yet in reality it doesn't do anything to that span, but just prints out 12345 in the place, where the script is.

Any ideas what could be wrong?

Body: You are wrapping a <tr> in a span. That is going to lead to unpredictable results. Especially if you then remove the table row.