问:
Finding combinations of elements in a list based on routing
I'm not sure how to verbally express what I want to achieve, and formulating a proper question for this, so here's an example:

If I have a comprehensive list with elements like this:

```<code>list = ['A to B', 'B to C', 'C to D', 'D to E', 'A to C', 'A to D', 'A to E',
 'B to A', 'B to C', 'B to D', 'B to E', 'C to A', 'E to B', 'E to C', 'E to A']
</code>```

I would like to find all unique combinations of exactly 3 elements expressing a routing, and subsequently, store those combinations in separate lists like so:

```<code>['A to B', 'B to C', 'C to A'],

['B to C', 'C to A', 'A to B'],

etc.
</code>```

So, in the first example output, A reverts back to A, and in the second output, B reverts back to B. I would like to see anything reverting back to itself in this fashion.

I'm new to Python and trying to think of ways to do this, but I get stuck.

How would I achieve this?

答:
Maybe using permutations from itertools maybe not the best choice but it gives the result as you wanted

```<code>#importing permutations from itertools
from itertools import permutations as c
lst= ['A to B', 'B to C', 'C to D', 'D to E', 'A to C', 'A to D', 'A to E',
 'B to A', 'B to C', 'B to D', 'B to E', 'C to A', 'E to B', 'E to C', 'E to A']
#permutation of the list with r as 3
lst_com = c(lst,3)
# this list is to reduce redundancy
d=[]
for i in lst_com:
    t=list(i)
    # if statement to check the express routing and not include redundant values
    if t[0][0] == t[2][-1] and t[0][-1] == t[1][0] and t[1][-1]==t[2][0] and t not in d:
        d.append(t)
        print(t)
</code>```

Output :

```<code>['A to B', 'B to C', 'C to A']
['A to B', 'B to E', 'E to A']
['B to C', 'C to A', 'A to B']
['C to D', 'D to E', 'E to C']
['D to E', 'E to B', 'B to D']
['D to E', 'E to C', 'C to D']
['D to E', 'E to A', 'A to D']
['A to D', 'D to E', 'E to A']
['A to E', 'E to B', 'B to A']
['A to E', 'E to C', 'C to A']
['B to A', 'A to E', 'E to B']
['B to D', 'D to E', 'E to B']
['B to E', 'E to A', 'A to B']
['C to A', 'A to B', 'B to C']
['C to A', 'A to E', 'E to C']
['E to B', 'B to A', 'A to E']
['E to B', 'B to D', 'D to E']
['E to C', 'C to D', 'D to E']
['E to C', 'C to A', 'A to E']
['E to A', 'A to B', 'B to E']
['E to A', 'A to D', 'D to E']
</code>```

Body:
I'm not sure how to verbally express what I want to achieve, and formulating a proper question for this, so here's an example:

If I have a comprehensive list with elements like this:

list = ['A to B', 'B to C', 'C to D', 'D to E', 'A to C', 'A to D', 'A to E',
 'B to A', 'B to C', 'B to D', 'B to E', 'C to A', 'E to B', 'E to C', 'E to A']

I would like to find all unique combinations of exactly 3 elements expressing a routing, and subsequently, store those combinations in separate lists like so:

['A to B', 'B to C', 'C to A'],

['B to C', 'C to A', 'A to B'],

etc.

So, in the first example output, A reverts back to A, and in the second output, B reverts back to B. I would like to see anything reverting back to itself in this fashion.

I'm new to Python and trying to think of ways to do this, but I get stuck.

How would I achieve this?

Body:
Maybe using permutations from itertools maybe not the best choice but it gives the result as you wanted

#importing permutations from itertools
from itertools import permutations as c
lst= ['A to B', 'B to C', 'C to D', 'D to E', 'A to C', 'A to D', 'A to E',
 'B to A', 'B to C', 'B to D', 'B to E', 'C to A', 'E to B', 'E to C', 'E to A']
#permutation of the list with r as 3
lst_com = c(lst,3)
# this list is to reduce redundancy
d=[]
for i in lst_com:
    t=list(i)
    # if statement to check the express routing and not include redundant values
    if t[0][0] == t[2][-1] and t[0][-1] == t[1][0] and t[1][-1]==t[2][0] and t not in d:
        d.append(t)
        print(t)

Output :

['A to B', 'B to C', 'C to A']
['A to B', 'B to E', 'E to A']
['B to C', 'C to A', 'A to B']
['C to D', 'D to E', 'E to C']
['D to E', 'E to B', 'B to D']
['D to E', 'E to C', 'C to D']
['D to E', 'E to A', 'A to D']
['A to D', 'D to E', 'E to A']
['A to E', 'E to B', 'B to A']
['A to E', 'E to C', 'C to A']
['B to A', 'A to E', 'E to B']
['B to D', 'D to E', 'E to B']
['B to E', 'E to A', 'A to B']
['C to A', 'A to B', 'B to C']
['C to A', 'A to E', 'E to C']
['E to B', 'B to A', 'A to E']
['E to B', 'B to D', 'D to E']
['E to C', 'C to D', 'D to E']
['E to C', 'C to A', 'A to E']
['E to A', 'A to B', 'B to E']
['E to A', 'A to D', 'D to E']


来源: stackexchange

问:
How to Instatiate only one object from Array in unity
I want to Instantiate only one object at a time, so I don't know what is wrong with my code because it instantiates all objects from the array at same time. With a random range, it is possible but I want to Instatiate it by order.</p>

```<code>void Update()
    {
        if (timer > maxTime)
        {
           // Shuffle(enemies);

        //    RandomNumber = Random.Range(0, enemies.Length);
            float center = Screen.width / Screen.height;

            CreateEnemies(center);

          //  newEnemie = Instantiate(enemies[RandomNumber]);
          //   newEnemie.transform.position = transform.position+new Vector3(Random.Range(-screenBounds.x -1.5f, screenBounds.x +1.5f), 0, 0);
          //  newEnemie.transform.position = transform.position + new Vector3(Random.Range(-screenBounds.x + 1.5f, screenBounds.x - 1.5f), 0, 0);

            timer = 0;

        }

        timer += Time.deltaTime;
    }
    void Shuffle(GameObject[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            GameObject temp = array[i];
            int random = Random.Range(i, array.Length);
            array[i] = array[random];
            array[random] = temp;
        }
    }
    void CreateEnemies(float positionY)
    {
        for(int i = 0; i < enemies.Length; i++)
        {
            enemies[i] = Instantiate(enemies[i], transform.position + new Vector3(Random.Range(-screenBounds.x - 1.5f, screenBounds.x + 1.5f), 0, 0), Quaternion.identity)as GameObject;
            positionY += 1f;
        }
    }
</code>```

答:
Your create Enemies function does what is says, it instantiates enemies (plural). When the function is called it goes through the entire array and instantiate all enemies. If you only want 1 each time the function is called you could use something like this.</p>

```<code>private int currentEnemyIndex = 0;//Enemy to spwan index

void CreateEnemies(float positionY)
{
    if (currentEnemyIndex < enemies.Length)//Make sure you don't go out of bound for your array. You could also clamp if you want to keep spwaning the last one.
    {
        enemies[currentEnemyIndex] = Instantiate(enemies[currentEnemyIndex], transform.position + new Vector3(Random.Range(-screenBounds.x - 1.5f, screenBounds.x + 1.5f), 0, 0), Quaternion.identity) as GameObject;
        positionY += 1f;
        ++currentEnemyIndex;//Increment the enemy index so next call you spwan the next enemy.
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to Instantiate only one object at a time, so I don't know what is wrong with my code because it instantiates all objects from the array at same time. With a random range, it is possible but I want to Instatiate it by order.

void Update()
    {
        if (timer > maxTime)
        {
           // Shuffle(enemies);

        //    RandomNumber = Random.Range(0, enemies.Length);
            float center = Screen.width / Screen.height;

            CreateEnemies(center);

          //  newEnemie = Instantiate(enemies[RandomNumber]);
          //   newEnemie.transform.position = transform.position+new Vector3(Random.Range(-screenBounds.x -1.5f, screenBounds.x +1.5f), 0, 0);
          //  newEnemie.transform.position = transform.position + new Vector3(Random.Range(-screenBounds.x + 1.5f, screenBounds.x - 1.5f), 0, 0);

            timer = 0;

        }

        timer += Time.deltaTime;
    }
    void Shuffle(GameObject[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            GameObject temp = array[i];
            int random = Random.Range(i, array.Length);
            array[i] = array[random];
            array[random] = temp;
        }
    }
    void CreateEnemies(float positionY)
    {
        for(int i = 0; i < enemies.Length; i++)
        {
            enemies[i] = Instantiate(enemies[i], transform.position + new Vector3(Random.Range(-screenBounds.x - 1.5f, screenBounds.x + 1.5f), 0, 0), Quaternion.identity)as GameObject;
            positionY += 1f;
        }
    }

Body:
Your create Enemies function does what is says, it instantiates enemies (plural). When the function is called it goes through the entire array and instantiate all enemies. If you only want 1 each time the function is called you could use something like this.

private int currentEnemyIndex = 0;//Enemy to spwan index

void CreateEnemies(float positionY)
{
    if (currentEnemyIndex < enemies.Length)//Make sure you don't go out of bound for your array. You could also clamp if you want to keep spwaning the last one.
    {
        enemies[currentEnemyIndex] = Instantiate(enemies[currentEnemyIndex], transform.position + new Vector3(Random.Range(-screenBounds.x - 1.5f, screenBounds.x + 1.5f), 0, 0), Quaternion.identity) as GameObject;
        positionY += 1f;
        ++currentEnemyIndex;//Increment the enemy index so next call you spwan the next enemy.
    }
}


问:
How call two function under onPress in react
Here the addToCart function. i want to call this funtion and navigate to another page.

```<code>addToCart = () => {
    const {product, quantity, variation, meta_data} = this.state;
    const {dispatch} = this.props;
    let check = true;

    // Check select variations
    if (product.get('type') === productType.VARIABLE) {
      const attributeProduct = product
        .get('attributes')
        .filter(attr => attr.get('variation'));
      if (!meta_data.size || attributeProduct.size !== meta_data.size) {
        check = false;
        showMessage({
          message: 'Please select variations',
          type: 'danger',
        });
      }
    }
    if (check) {
      dispatch(
        addToCart(
          {
            product_id: product.get('id'),
            quantity,
            variation,
            product,
            meta_data,
          },
          () => this.setState({isAddToCart: true}),
        ),
      );
    }
  };
</code>```

And Render function

```<code><FooterProduct
          isAddToCart={isAddToCart}
          onPressAddCart={this.addToCart}
          onPressBuyNow={

            this.addToCart // function one
            () => navigation.navigate(homeTabs.cart) // function two

          }
        />
</code>```

how can I run both? actually I try to create a buy now button.
thank you.

答:
Create a custom method that calls both the methods like below

```<code>const combinedMethod = () => {
  this.addToCart();
  navigation.navigate(homeTabs.cart);
}
</code>```

And use the above method like

```<code><FooterProduct
   isAddToCart={isAddToCart}
   onPressAddCart={this.addToCart}
   onPressBuyNow={combinedMethod}
/>
</code>```

Body:
Here the addToCart function. i want to call this funtion and navigate to another page.

addToCart = () => {
    const {product, quantity, variation, meta_data} = this.state;
    const {dispatch} = this.props;
    let check = true;

    // Check select variations
    if (product.get('type') === productType.VARIABLE) {
      const attributeProduct = product
        .get('attributes')
        .filter(attr => attr.get('variation'));
      if (!meta_data.size || attributeProduct.size !== meta_data.size) {
        check = false;
        showMessage({
          message: 'Please select variations',
          type: 'danger',
        });
      }
    }
    if (check) {
      dispatch(
        addToCart(
          {
            product_id: product.get('id'),
            quantity,
            variation,
            product,
            meta_data,
          },
          () => this.setState({isAddToCart: true}),
        ),
      );
    }
  };

And Render function

<FooterProduct
          isAddToCart={isAddToCart}
          onPressAddCart={this.addToCart}
          onPressBuyNow={

            this.addToCart // function one
            () => navigation.navigate(homeTabs.cart) // function two

          }
        />

how can I run both? actually I try to create a buy now button.
thank you.

Body:
Create a custom method that calls both the methods like below

const combinedMethod = () => {
  this.addToCart();
  navigation.navigate(homeTabs.cart);
}

And use the above method like

<FooterProduct
   isAddToCart={isAddToCart}
   onPressAddCart={this.addToCart}
   onPressBuyNow={combinedMethod}
/>


问:
Django 1.8 app mysteriously fails with initial migration due to errno: 150 "Foreign key constraint is incorrectly formed"
I'm writing an app in django 1.8 with python 3.4 and I'm encountering an issue with using MySQL as the database backend which has got me completely stumped.

When I start off with a new database and call ./manage.py migrate (or syncdb) and it tries to create the initial database, I get the following traceback:

```<code>(virtualenv)~/projects/projmoj (master ✘)✹✭ ᐅ ./manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: allauth, rest_framework, registration, rest_auth, projmoj, messages, project, staticfiles
  Apply all migrations: contenttypes, sites, sessions, task, auth, admin, authtoken, static_precompiler, account
Synchronizing apps without migrations:
  Creating tables...
    Creating table project_project
    Creating table project_membership
    Running deferred SQL...
Traceback (most recent call last):
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/django/db/backends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 124, in execute
    return self.cursor.execute(query, args)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 371, in _query
    rowcount = self._do_query(q)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 335, in _do_query
    db.query(q)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1005, 'Can\'t create table `tasks`.`#sql-1c32_9` (errno: 150 "Foreign key constraint is incorrectly formed")')
</code>```

This error happens when I do the same on a web hosting service, it works however using sqlite on both the hosting service and localhost.

I have no migrations, and these are my models:

```<code>class Project(models.Model):
  name = models.CharField(max_length = 32)
  description = models.TextField(null=True, blank=True)
  creation_date = models.DateTimeField(auto_now_add=True)

  def get_owner(self):
    return self.members.filter(status=OWNER).first().user

  def get_membership(self, user):
    return self.members.filter(user=user).first()

  def __str__(self):
    return str(self.name) + " - by " + str(self.get_owner().username)

class Membership(models.Model):
  user = models.ForeignKey(User, related_name='joined_projects')
  project = models.ForeignKey(Project, related_name='members')
  status = models.PositiveSmallIntegerField(choices=MEMBER_STATUS)
  join_date = models.DateTimeField(auto_now_add=True)

  def __str__(self):
    return str(self.user.username)

class Sprint(models.Model):
  name = models.CharField(max_length = 32, null=True, blank=True)
  start_date = models.DateTimeField()
  due_date = models.DateTimeField(null=True, blank=True)
  project = models.ForeignKey(Project, related_name='sprints')
  status = models.PositiveSmallIntegerField(choices=SPRINT_STATUS, default=PLANNING)

  def __str__(self):
    return str(self.name) + " - " + str(self.project)

class Category(models.Model):
  name = models.CharField(max_length = 32)
  project = models.ForeignKey(Project, related_name='categories')

  def __str__(self):
    return str(self.name) + " - " + str(self.project)

class Goal(models.Model):
  name = models.CharField(max_length = 32)
  description = models.TextField(null=True, blank=True)
  project = models.ForeignKey(Project, related_name='goals')
  completion = models.PositiveSmallIntegerField(choices=COMPLETION, default=NOT_COMPLETED)

  def __str__(self):
    return str(self.name) + " - " + str(self.project)

class Task(models.Model):
  name = models.CharField(max_length = 64)
  description = models.TextField(null=True, blank=True)
  project = models.ForeignKey(Project, related_name='tasks')
  category = models.ForeignKey(Category, related_name='tasks', null=True, blank=True)
  goal = models.ForeignKey(Goal, related_name='tasks', null=True, blank=True)
  creation_date = models.DateTimeField(auto_now_add=True)
  sprint = models.ForeignKey(Sprint, related_name='tasks', null=True, blank=True)
  status = models.PositiveSmallIntegerField(choices=TASK_STATUS, default=WAITING)
  dedicated_hours = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
  assigned_worker = models.ForeignKey(User, null=True, blank=True)
  priority = models.PositiveSmallIntegerField(choices=PRIORITY, default=NORMAL)

  def __str__(self):
    return str(self.name) + " - " + str(self.project)

class HourReport(models.Model):
  task = models.ForeignKey(Task, related_name='hour_reports')
  worker = models.ForeignKey(User, related_name='hour_reports')
  hours_spent = models.DecimalField(max_digits=6, decimal_places=2)
  date = models.DateTimeField(auto_now_add=True)

  def __str__(self):
    return str(self.hours_spent) + " on " + str(self.task)
</code>```

My database settings:

```<code>DATABASES = {
  'default': {
      'ENGINE': 'django.db.backends.mysql',
      'NAME': 'tasks',
      'USER': 'root',
      'PASSWORD': 'mysqlmysql',
      'HOST': 'localhost',
  }
}
</code>```

Versions etc:

Django 1.8

Python 3.4

Default storage engine: InnoDB

Mysqlclient 1.3.6

Server: MySQL 5.5.42 on Amazon RDS (at web hosting)

Server: 10.0.21-MariaDB-log MariaDB Server (localhost)

When googling it seems like this error is often when people stuff up their manual SQL code, but I am doing it all automatically through django.

Any ideas?

答:
It's also possible when running python manage.py migrate to get that error of

_mysql.connection.query(self, query)

django.db.utils.OperationalError: (1005, 'Can\'t create table > codelabs.django_admin_log (errno: 150 "Foreign key constraint is incorrectly formed")')

due to having wrong information in settings.py regarding the DATABASES. For instances, if in your database your table has the name tiagoperes and in your settings.py you're refering the NAME to be tiagoPeres, that error will show up. To fix it, just use the correct NAME and run again python manage.py migrate.

ContentLicense: CC BY-SA 3.0

Body:
I'm writing an app in django 1.8 with python 3.4 and I'm encountering an issue with using MySQL as the database backend which has got me completely stumped.

When I start off with a new database and call ./manage.py migrate (or syncdb) and it tries to create the initial database, I get the following traceback:

(virtualenv)~/projects/projmoj (master ✘)✹✭ ᐅ ./manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: allauth, rest_framework, registration, rest_auth, projmoj, messages, project, staticfiles
  Apply all migrations: contenttypes, sites, sessions, task, auth, admin, authtoken, static_precompiler, account
Synchronizing apps without migrations:
  Creating tables...
    Creating table project_project
    Creating table project_membership
    Running deferred SQL...
Traceback (most recent call last):
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/django/db/backends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 124, in execute
    return self.cursor.execute(query, args)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 371, in _query
    rowcount = self._do_query(q)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 335, in _do_query
    db.query(q)
  File "/home/tobbe/projects/projmoj/virtualenv/lib/python3.4/site-packages/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1005, 'Can\'t create table `tasks`.`#sql-1c32_9` (errno: 150 "Foreign key constraint is incorrectly formed")')

This error happens when I do the same on a web hosting service, it works however using sqlite on both the hosting service and localhost.

I have no migrations, and these are my models:

class Project(models.Model):
  name = models.CharField(max_length = 32)
  description = models.TextField(null=True, blank=True)
  creation_date = models.DateTimeField(auto_now_add=True)

  def get_owner(self):
    return self.members.filter(status=OWNER).first().user

  def get_membership(self, user):
    return self.members.filter(user=user).first()

  def __str__(self):
    return str(self.name) + " - by " + str(self.get_owner().username)

class Membership(models.Model):
  user = models.ForeignKey(User, related_name='joined_projects')
  project = models.ForeignKey(Project, related_name='members')
  status = models.PositiveSmallIntegerField(choices=MEMBER_STATUS)
  join_date = models.DateTimeField(auto_now_add=True)

  def __str__(self):
    return str(self.user.username)

class Sprint(models.Model):
  name = models.CharField(max_length = 32, null=True, blank=True)
  start_date = models.DateTimeField()
  due_date = models.DateTimeField(null=True, blank=True)
  project = models.ForeignKey(Project, related_name='sprints')
  status = models.PositiveSmallIntegerField(choices=SPRINT_STATUS, default=PLANNING)

  def __str__(self):
    return str(self.name) + " - " + str(self.project)

class Category(models.Model):
  name = models.CharField(max_length = 32)
  project = models.ForeignKey(Project, related_name='categories')

  def __str__(self):
    return str(self.name) + " - " + str(self.project)

class Goal(models.Model):
  name = models.CharField(max_length = 32)
  description = models.TextField(null=True, blank=True)
  project = models.ForeignKey(Project, related_name='goals')
  completion = models.PositiveSmallIntegerField(choices=COMPLETION, default=NOT_COMPLETED)

  def __str__(self):
    return str(self.name) + " - " + str(self.project)

class Task(models.Model):
  name = models.CharField(max_length = 64)
  description = models.TextField(null=True, blank=True)
  project = models.ForeignKey(Project, related_name='tasks')
  category = models.ForeignKey(Category, related_name='tasks', null=True, blank=True)
  goal = models.ForeignKey(Goal, related_name='tasks', null=True, blank=True)
  creation_date = models.DateTimeField(auto_now_add=True)
  sprint = models.ForeignKey(Sprint, related_name='tasks', null=True, blank=True)
  status = models.PositiveSmallIntegerField(choices=TASK_STATUS, default=WAITING)
  dedicated_hours = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
  assigned_worker = models.ForeignKey(User, null=True, blank=True)
  priority = models.PositiveSmallIntegerField(choices=PRIORITY, default=NORMAL)

  def __str__(self):
    return str(self.name) + " - " + str(self.project)

class HourReport(models.Model):
  task = models.ForeignKey(Task, related_name='hour_reports')
  worker = models.ForeignKey(User, related_name='hour_reports')
  hours_spent = models.DecimalField(max_digits=6, decimal_places=2)
  date = models.DateTimeField(auto_now_add=True)

  def __str__(self):
    return str(self.hours_spent) + " on " + str(self.task)

My database settings:

DATABASES = {
  'default': {
      'ENGINE': 'django.db.backends.mysql',
      'NAME': 'tasks',
      'USER': 'root',
      'PASSWORD': 'mysqlmysql',
      'HOST': 'localhost',
  }
}

Versions etc:

Django 1.8

Python 3.4

Default storage engine: InnoDB

Mysqlclient 1.3.6

Server: MySQL 5.5.42 on Amazon RDS (at web hosting)

Server: 10.0.21-MariaDB-log MariaDB Server (localhost)

When googling it seems like this error is often when people stuff up their manual SQL code, but I am doing it all automatically through django.

Any ideas?


问:
why do I get this error building a static library for my iPhone project using XCode 4?
I have an existing iPhone application, and I just wanted to make a static library out of the code, so that I can use it by a separate test application (within the workspace).  The application compiles fine, but when I try to compile the library version (which has the same code files) I get the following error:

Lexical or Preprocessor Issue - "MyClass.h" file not found

However, the application still runs, even through there is this error.  In fact when I compile the application (which uses the static library) it initially says no errors, and then after a second or two the above mention error then appears.

I'm basically doing:

Create a new target in the project using the Coco Touch Static Library

Add the .m files in the targets "Compile Sources"

Adding the .h files in the targets "Copy Headers"

Adding the same set of libraries in the "Link binaries with libraries"

Go into the Profile and modified the Target to be RELEASE

Any suggestions?  Am I missing a step here?

答: So, the issue turned out to be I had "-ObjC" set in the "Other Link Flags" option, which I'd put there as at one stage trying to get things working I read this was required - Dereks advice to review the compilation log worked well here </p>


问:
How to open tabbar BY click notification
I want to open APP in specific tabbar by click notification on lock screen

Now I used

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
{
    print("user clicked on the notification")
    if let tabBarController = self.window!.rootViewController as? UITabBarController {
        tabBarController.selectedIndex = 2
    }
}
</code>```

and it have error

```<code>Value of type 'AppDelegate' has no member 'window'
</code>```

on Swift5, Is it have better way?

答:
solve it!!!</p>

```<code>DispatchQueue.main.async{
        let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first

        if var topController = keyWindow?.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController

                let tabbarController = presentedViewController as! UITabBarController
                tabbarController.selectedIndex = 2
            }
        }
    }
</code>```

Body:
I want to open APP in specific tabbar by click notification on lock screen

Now I used

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
{
    print("user clicked on the notification")
    if let tabBarController = self.window!.rootViewController as? UITabBarController {
        tabBarController.selectedIndex = 2
    }
}

and it have error

Value of type 'AppDelegate' has no member 'window'

on Swift5, Is it have better way?

Body:
solve it!!!

DispatchQueue.main.async{
        let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first

        if var topController = keyWindow?.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController

                let tabbarController = presentedViewController as! UITabBarController
                tabbarController.selectedIndex = 2
            }
        }
    }


问:
Retrieval of image failed
I tried to download these images to a local PC, there is no error, but the downloaded images cannot be opened, what did I do wrong? Image url</p>

```<code>import urllib.request
import urllib
url = 'https://szaniterplaza.hu/images/itempic/Grohe_Euroeco_bidé_csaptelep_32737_000_32737000.jpg'
url = urllib.parse.quote(url, encoding='utf8', safe = '://')
urllib.request.urlretrieve(url, './image.jpg')
</code>```

答:
That image URL is invalid.
Your translated URL is invalid too:

https://szaniterplaza.hu/images/itempic/Grohe_Euroeco_bid%C3%A9_csaptelep_32743_000_32743000.jpg

Try it in a browser. I just did.

Perhaps if you gave us the correct URL and the URL you need it transformed from we can help with the transformation.

What you have downloaded is just the html you see in the browser, just because you named it image.jpg doesn't make it a jpeg.

There's nothing wrong with your download code (apart from urlretrieve being deprecated). It worked for https://ichef.bbci.co.uk/news/660/cpsprodpb/12A9B/production/_111434467_gettyimages-1143489763.jpg.

Title: Retrieval of image failed

Body:
I tried to download these images to a local PC, there is no error, but the downloaded images cannot be opened, what did I do wrong? Image url

import urllib.request
import urllib
url = 'https://szaniterplaza.hu/images/itempic/Grohe_Euroeco_bidé_csaptelep_32737_000_32737000.jpg'
url = urllib.parse.quote(url, encoding='utf8', safe = '://')
urllib.request.urlretrieve(url, './image.jpg')


问:
Every vue component returning Cannot read property 'parseComponent' of undefined
So i've tried researching this but none of the solutions are working. I think it's specifically an issue with some of my vue dependencies, potentially vue-loader, but I'm not sure what specifically to do to fix it. I have tried:

deleting node_modules and re-running npm install

npm update

i've tried removing vue-loader completely

tried adding, removing, and updating @vue/component-compiler-utils

tried changing the version of the above to three different things

tried running composer install and composer update

creating a new temp staging branch from master just in case it was some weird git error and building from that

What am I missing here? Every vue component on my staging site returns this same error. The weirdest thing is that the staging server is a direct clone of our production server, where all of this works completely smoothly and i get zero errors.

The Errors:

```<code>ERROR in ./resources/assets/js/components/component.vue
Module build failed (from ./node_modules/vue-loader/lib/index.js):
TypeError: Cannot read property 'parseComponent' of undefined
    at parse (/var/www/site/node_modules/@vue/component-compiler-utils/dist/parse.js:14:23)
    at Object.module.exports (/var/www/site/node_modules/vue-loader/lib/index.js:67:22)
 @ ./resources/assets/js/app.js 60:29-81
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss
</code>```

I've tried installing these warnings' dependencies as well but still get the same error above, I'm including these because it's what pops up when i run my bash script and run npm install from my staging branch:

```<code>npm WARN eslint-plugin-vue@5.2.3 requires a peer of eslint@^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN vue-eslint-parser@5.0.0 requires a peer of eslint@^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.11 (node_modules/webpack-dev-server/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.11: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
</code>```

package.json dependencies

```<code>"devDependencies": {
    "axios": "^0.19.0",
    "babel-preset-stage-2": "^6.24.1",
    "browser-sync": "^2.26.7",
    "browser-sync-webpack-plugin": "^2.2.2",
    "cross-env": "^5.2.0",
    "eslint": "^6.1.0",
    "eslint-config-standard": "^13.0.1",
    "eslint-loader": "^2.2.1",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-node": "^9.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.0",
    "eslint-plugin-vue": "^5.2.3",
    "exports-loader": "^0.6.4",
    "imports-loader": "^0.7.1",
    "jquery": "^3.3.1",
    "laravel-mix": "^4.1.2",
    "lodash": "^4.17.11",
    "resolve-url-loader": "^3.1.0",
    "sass": "^1.22.10",
    "vue": "^2.6.10"
  },
   "dependencies": {
    "@vue/component-compiler-utils": "^3.1.1",
    "ajv": "^6.10.0",
    "babel-polyfill": "^6.26.0",
    "bootstrap": "^4.3.1",
    "braces": "^2.3.1",
    "es6-promise": "^4.2.6",
    "font-awesome": "^4.7.0",
    "luxon": "^1.12.1",
    "moment": "^2.24.0",
    "popper": "^1.0.1",
    "popper.js": "^1.14.7",
    "sass-loader": "^7.1.0",
    "vue-datetime": "^1.0.0-beta.10",
    "vue-datetime-picker": "^0.2.1",
    "vue-full-calendar": "^2.7.0",
    "vue-loader": "^15.8.3",
    "vue-router": "^3.0.2",
    "vue-template-compiler": "2.6.10",
    "vue-wysiwyg": "^1.7.2",
    "vuex": "^3.1.0",
    "weekstart": "^1.0.0",
    "whatwg-fetch": "^2.0.4",
    "wkhtmltopdf": "^0.3.4"
  }
}

</code>```

I'm thinking it might have something to do with a specific version of a dependency? But nothing i've been trying from other stack overflow threads or google searches has been helping

Let me know if there's any code missing that may help

答:
I had exacly the same problem and just figured it out, I hope this helps someone.
First I changed the vue template compiler to:

"vue-template-compiler": "2.6.11"

and the I also had to change the vue version to the latest realese, in my case:

"vue": "2.6.11"

Body:
So i've tried researching this but none of the solutions are working. I think it's specifically an issue with some of my vue dependencies, potentially vue-loader, but I'm not sure what specifically to do to fix it. I have tried:

deleting node_modules and re-running npm install

npm update

i've tried removing vue-loader completely

tried adding, removing, and updating @vue/component-compiler-utils

tried changing the version of the above to three different things

tried running composer install and composer update

creating a new temp staging branch from master just in case it was some weird git error and building from that

What am I missing here? Every vue component on my staging site returns this same error. The weirdest thing is that the staging server is a direct clone of our production server, where all of this works completely smoothly and i get zero errors.

The Errors:

ERROR in ./resources/assets/js/components/component.vue
Module build failed (from ./node_modules/vue-loader/lib/index.js):
TypeError: Cannot read property 'parseComponent' of undefined
    at parse (/var/www/site/node_modules/@vue/component-compiler-utils/dist/parse.js:14:23)
    at Object.module.exports (/var/www/site/node_modules/vue-loader/lib/index.js:67:22)
 @ ./resources/assets/js/app.js 60:29-81
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss

I've tried installing these warnings' dependencies as well but still get the same error above, I'm including these because it's what pops up when i run my bash script and run npm install from my staging branch:

npm WARN eslint-plugin-vue@5.2.3 requires a peer of eslint@^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN vue-eslint-parser@5.0.0 requires a peer of eslint@^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.11 (node_modules/webpack-dev-server/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.11: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

package.json dependencies

"devDependencies": {
    "axios": "^0.19.0",
    "babel-preset-stage-2": "^6.24.1",
    "browser-sync": "^2.26.7",
    "browser-sync-webpack-plugin": "^2.2.2",
    "cross-env": "^5.2.0",
    "eslint": "^6.1.0",
    "eslint-config-standard": "^13.0.1",
    "eslint-loader": "^2.2.1",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-node": "^9.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.0",
    "eslint-plugin-vue": "^5.2.3",
    "exports-loader": "^0.6.4",
    "imports-loader": "^0.7.1",
    "jquery": "^3.3.1",
    "laravel-mix": "^4.1.2",
    "lodash": "^4.17.11",
    "resolve-url-loader": "^3.1.0",
    "sass": "^1.22.10",
    "vue": "^2.6.10"
  },
   "dependencies": {
    "@vue/component-compiler-utils": "^3.1.1",
    "ajv": "^6.10.0",
    "babel-polyfill": "^6.26.0",
    "bootstrap": "^4.3.1",
    "braces": "^2.3.1",
    "es6-promise": "^4.2.6",
    "font-awesome": "^4.7.0",
    "luxon": "^1.12.1",
    "moment": "^2.24.0",
    "popper": "^1.0.1",
    "popper.js": "^1.14.7",
    "sass-loader": "^7.1.0",
    "vue-datetime": "^1.0.0-beta.10",
    "vue-datetime-picker": "^0.2.1",
    "vue-full-calendar": "^2.7.0",
    "vue-loader": "^15.8.3",
    "vue-router": "^3.0.2",
    "vue-template-compiler": "2.6.10",
    "vue-wysiwyg": "^1.7.2",
    "vuex": "^3.1.0",
    "weekstart": "^1.0.0",
    "whatwg-fetch": "^2.0.4",
    "wkhtmltopdf": "^0.3.4"
  }
}

I'm thinking it might have something to do with a specific version of a dependency? But nothing i've been trying from other stack overflow threads or google searches has been helping

Let me know if there's any code missing that may help


问:
Copying and Paste multiple rows into next empty Row on another sheet
I have the following script:

```<code>function onEdit(event) {
  // assumes source data in sheet named Needed
  // target sheet of move to named Acquired
  // test column with yes/no is col 5 or E
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange();
  if(s.getName() == "IN" && r.getColumn() == 7 && r.getValue() == "Y") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("ORDERS");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).copyTo(target);

  }
}
</code>```

This is the original post where i found the script:
https://support.google.com/docs/forum/AAAABuH1jm0hR40qh02UWE/?hl=en&gpf=%23!topic%2Fdocs%2FhR40qh02UWE

I want to make a few small adjustments to the code, but don't know where to start.

Presently, it copies the whole row when a "Y" is entered into column G and places the row contents on lastrow of ORDERS!.

What i want it to do is:

1) only copy columns B,C and E on lastrow of ORDERS!
2) delete values in E and F on IN! after code has run for that specific row (don't want it deleting rows that I haven't put a "Y" against)
3) Is there a way to have a button instead, that when the button is clicked it copies all the rows with "Y" at once?

Here's a link to my sheet if you want to have a play:
https://docs.google.com/spreadsheets/d/1Peo5_5QmkxVyL7j5bmgtMs9BL16cvsGhhOSuRV_TsAo/edit?usp=sharing

Best regards
manc

答:
I believe your goal as follows.

When the column "G" is Y, you want to copy the values of the columns "B", "C" and "E" to the last row of the sheet ORDERS.

You want to copy all rows that the column "G" is Y when the script is run.

You want to delete the content of columns "E" and "F" of the copied rows in the sheet of IN, when the script is run.

You want to run the script by clicking a button on the sheet.

For this, how about this answer?

Modification points:

In your script,

When the script is run by clicking a button on the sheet, the event object cannot be used.

Your script copies one row of the active range.

The columns "E" and "F" of the copied rows are not deleted.

It is required to modify above modification points. When above points are reflected to the script, it becomes as follows.

Modified script:

Please copy and paste the following script to the script editor. And please prepare a button which is drawing and/or image, and assign the function run to the button. By this, when the button is clicked, the script is run. And the columns "B", "C" and "E" of all rows that the column "G" is Y are copied from the sheet "IN" to the last row of the sheet "ORDERS".

```<code>function run() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = ss.getSheetByName("IN");
  var dstSheet = ss.getSheetByName("ORDERS");

  // 1. Retrieve the values from "A2:G" of sheet "IN".
  var srcValues = srcSheet.getRange("A2:G" + srcSheet.getLastRow()).getValues();

  // 2. Create an object for putting values and deleting the contents of the columns "E" and "F".
  var obj = srcValues.reduce((o, [,b,c,,e,,g], i) => {
    if (g == "Y") {
      o.values.push([b, c, e]);
      o.ranges.push(`E${i + 2}:F${i + 2}`);
    }
    return o;
  }, {values: [], ranges: []});

  // 3. Copy the values to the sheet "ORDERS".
  dstSheet.getRange(dstSheet.getLastRow() + 1, 1, obj.values.length, obj.values[0].length).setValues(obj.values);

  // 4. Delete the contents of the columns "E" and "F" of sheet "IN".
  srcSheet.getRangeList(obj.ranges).clearContent();
}
</code>```

Note:

About the button for running the Google Apps Script, I think that this site is useful. Ref In your case, please create a button on the sheet "IN" and assign the function run to the button. By this, when the button is clicked, the script works.

Please use this script with V8.

References:

setValues(values)

clearContent()

reduce()

Body:
I have the following script:

function onEdit(event) {
  // assumes source data in sheet named Needed
  // target sheet of move to named Acquired
  // test column with yes/no is col 5 or E
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange();
  if(s.getName() == "IN" && r.getColumn() == 7 && r.getValue() == "Y") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("ORDERS");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).copyTo(target);

  }
}

This is the original post where i found the script:
https://support.google.com/docs/forum/AAAABuH1jm0hR40qh02UWE/?hl=en&gpf=%23!topic%2Fdocs%2FhR40qh02UWE

I want to make a few small adjustments to the code, but don't know where to start.

Presently, it copies the whole row when a "Y" is entered into column G and places the row contents on lastrow of ORDERS!.

What i want it to do is:

1) only copy columns B,C and E on lastrow of ORDERS!
2) delete values in E and F on IN! after code has run for that specific row (don't want it deleting rows that I haven't put a "Y" against)
3) Is there a way to have a button instead, that when the button is clicked it copies all the rows with "Y" at once?

Here's a link to my sheet if you want to have a play:
https://docs.google.com/spreadsheets/d/1Peo5_5QmkxVyL7j5bmgtMs9BL16cvsGhhOSuRV_TsAo/edit?usp=sharing

Best regards
manc

Body:
I believe your goal as follows.

When the column "G" is Y, you want to copy the values of the columns "B", "C" and "E" to the last row of the sheet ORDERS.

You want to copy all rows that the column "G" is Y when the script is run.

You want to delete the content of columns "E" and "F" of the copied rows in the sheet of IN, when the script is run.

You want to run the script by clicking a button on the sheet.

For this, how about this answer?

Modification points:

In your script,

When the script is run by clicking a button on the sheet, the event object cannot be used.

Your script copies one row of the active range.

The columns "E" and "F" of the copied rows are not deleted.

It is required to modify above modification points. When above points are reflected to the script, it becomes as follows.

Modified script:

Please copy and paste the following script to the script editor. And please prepare a button which is drawing and/or image, and assign the function run to the button. By this, when the button is clicked, the script is run. And the columns "B", "C" and "E" of all rows that the column "G" is Y are copied from the sheet "IN" to the last row of the sheet "ORDERS".

function run() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = ss.getSheetByName("IN");
  var dstSheet = ss.getSheetByName("ORDERS");

  // 1. Retrieve the values from "A2:G" of sheet "IN".
  var srcValues = srcSheet.getRange("A2:G" + srcSheet.getLastRow()).getValues();

  // 2. Create an object for putting values and deleting the contents of the columns "E" and "F".
  var obj = srcValues.reduce((o, [,b,c,,e,,g], i) => {
    if (g == "Y") {
      o.values.push([b, c, e]);
      o.ranges.push(`E${i + 2}:F${i + 2}`);
    }
    return o;
  }, {values: [], ranges: []});

  // 3. Copy the values to the sheet "ORDERS".
  dstSheet.getRange(dstSheet.getLastRow() + 1, 1, obj.values.length, obj.values[0].length).setValues(obj.values);

  // 4. Delete the contents of the columns "E" and "F" of sheet "IN".
  srcSheet.getRangeList(obj.ranges).clearContent();
}

Note:

About the button for running the Google Apps Script, I think that this site is useful. Ref In your case, please create a button on the sheet "IN" and assign the function run to the button. By this, when the button is clicked, the script works.

Please use this script with V8.

References:

setValues(values)

clearContent()

reduce()


问:
Determine which UpdatePanel causes the partial (asynchronous) PostBack?
In a page contains two UpdatePanels, How can I know which UpdatePanel causes the partial PostBack ?

I mean in the Page_Load event handler.

This is my code:

```<code> <asp:ScriptManager ID="ScriptManager1" runat="server">
 </asp:ScriptManager>
 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"
     onprerender="UpdatePanel1_PreRender">
     <ContentTemplate>
         <A:u1 ID="u1" runat="server" />
     </ContentTemplate>
 </asp:UpdatePanel>
 <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional"
     onprerender="UpdatePanel2_PreRender">
     <ContentTemplate>
         <A:u2 ID="u2" runat="server" />
     </ContentTemplate>
 </asp:UpdatePanel>
</code>```

I tried this code, but it isn't worked alost!

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
    {
        if (UpdatePanel1.IsInPartialRendering)
        {
            // never enter to here
        }
        if (UpdatePanel2.IsInPartialRendering)
        {
            // neither here
        }
    }
}
</code>```

Any help!

答:
If you don't want to extend the original UpdatePanel class, you can also use this workaround:

```<code>string id = ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;
</code>```

Thus, you can examine the resulting id and add some conditional clauses to determine which code should execute.  This id should be equal to the first parameter that was passed through the javascript function __doPostBack('someid', '').

For example, I have a user control in my Update Panel: this control contains a bunch of link buttons that trigger the UpdatePanel.)  I also can manually update this panel from some external links (using something like __doPostBack('myUpdatePanelClientId', '');

That is, in my case, I see three different ways for loading my UpdatePanel:

First page load;

Link button (or any other type of button) clicked inside my UpdatePanel;

PostBack triggered outside the UpdatePanel.

Every scenario gives me a different id.  The first one gives me an empty string (since this is the first page load, there hasn't been yet any postback triggered with the __doPostBack function.)

The second one gives me the UniqueId of the button that was pushed inside the user control (this is the original and expected ASP.NET behavior.)

The third one gives me exactly what I passed as the first argument when I coded the method (ie: the ClientId of the UpdatePanel.)

Here's how I succeeded to implement my UpdatePanel use case (assuming I'm using the partial rendering mode.)  This is not perfect but it works as intended.

```<code>protected void myUpdatePanel_Load(object sender, EventArgs e)
{
    string id = ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;

    bool firstLoad = (String.IsNullOrEmpty(id));
    bool triggerFromUpdatePanel = !firstLoad && (id.Contains(userControlInsideMyUpdatePanel.UniqueID));
    bool triggerFromExternalControl = !firstLoad && (id == myUpdatePanel.ClientID);

    // case 1, 2, 3.
    if ((firstLoad)  || (triggerFromUpdatePanel)  || (triggerFromExternalControl ))
    {
        // do something
    }
    else
    {
        // do nothing!
    }

}
</code>```

Body:
In a page contains two UpdatePanels, How can I know which UpdatePanel causes the partial PostBack ?

I mean in the Page_Load event handler.

This is my code:

 <asp:ScriptManager ID="ScriptManager1" runat="server">
 </asp:ScriptManager>
 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"
     onprerender="UpdatePanel1_PreRender">
     <ContentTemplate>

     </ContentTemplate>
 </asp:UpdatePanel>
 <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional"
     onprerender="UpdatePanel2_PreRender">
     <ContentTemplate>

     </ContentTemplate>
 </asp:UpdatePanel>

I tried this code, but it isn't worked alost!

protected void Page_Load(object sender, EventArgs e)
{
    if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
    {
        if (UpdatePanel1.IsInPartialRendering)
        {
            // never enter to here
        }
        if (UpdatePanel2.IsInPartialRendering)
        {
            // neither here
        }
    }
}

Any help!

Body:
If you don't want to extend the original UpdatePanel class, you can also use this workaround:

string id = ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;

Thus, you can examine the resulting id and add some conditional clauses to determine which code should execute.  This id should be equal to the first parameter that was passed through the javascript function __doPostBack('someid', '').

For example, I have a user control in my Update Panel: this control contains a bunch of link buttons that trigger the UpdatePanel.)  I also can manually update this panel from some external links (using something like __doPostBack('myUpdatePanelClientId', '');

That is, in my case, I see three different ways for loading my UpdatePanel:

First page load;

Link button (or any other type of button) clicked inside my UpdatePanel;

PostBack triggered outside the UpdatePanel.

Every scenario gives me a different id.  The first one gives me an empty string (since this is the first page load, there hasn't been yet any postback triggered with the __doPostBack function.)

The second one gives me the UniqueId of the button that was pushed inside the user control (this is the original and expected ASP.NET behavior.)

The third one gives me exactly what I passed as the first argument when I coded the method (ie: the ClientId of the UpdatePanel.)

Here's how I succeeded to implement my UpdatePanel use case (assuming I'm using the partial rendering mode.)  This is not perfect but it works as intended.

protected void myUpdatePanel_Load(object sender, EventArgs e)
{
    string id = ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;

    bool firstLoad = (String.IsNullOrEmpty(id));
    bool triggerFromUpdatePanel = !firstLoad && (id.Contains(userControlInsideMyUpdatePanel.UniqueID));
    bool triggerFromExternalControl = !firstLoad && (id == myUpdatePanel.ClientID);

    // case 1, 2, 3.
    if ((firstLoad)  || (triggerFromUpdatePanel)  || (triggerFromExternalControl ))
    {
        // do something
    }
    else
    {
        // do nothing!
    }

}


问:
Multiple Docker host machine communication
Suppose, I want to connect a container with another container, where both docker containers are running on a different machine. How do I do that? Hopefully, the attached picture will help to understand what I need. thanks.

答:
This works exactly the same way as if neither process was running in Docker: connect to the other system's IP address and the port you published when you launched the container.

machine02$ docker run --name m2-c1 -p 12345:80 image1
```

<pre class="lang-none prettyprint-override"><code>machine01$ docker run --name m1-c5 \
>            -e CONTAINER_1_URL=http://192.168.1.102:12345 \
>            image5
</code>```

If you find yourself doing this often, a clustered setup like Kubernetes or Docker Swarm is built for this sort of environment.  They have a piece called an overlay network that would allow all 10 containers to share a single "network", so you can directly call c1 as a host name and reach either copy of it.  A non-Docker service discovery system, like Hashicorp's Consul, can also help remember what service is running on which node.

Body:
This works exactly the same way as if neither process was running in Docker: connect to the other system's IP address and the port you published when you launched the container.

machine02$ docker run --name m2-c1 -p 12345:80 image1

machine01$ docker run --name m1-c5 \
>            -e CONTAINER_1_URL=http://192.168.1.102:12345 \
>            image5

If you find yourself doing this often, a clustered setup like Kubernetes or Docker Swarm is built for this sort of environment.  They have a piece called an overlay network that would allow all 10 containers to share a single "network", so you can directly call c1 as a host name and reach either copy of it.  A non-Docker service discovery system, like Hashicorp's Consul, can also help remember what service is running on which node.


问:
Get distinct values of two columns and merge into rows
I have a table named dbo.WebsiteIP having two columns IPAddress, SiteName, and I am doing a bulk insert the values to the this table which look like below

```<code>IPAddress       SiteName
192.168.30.6    website1.domain.com
192.168.30.6    website2.domain.com
192.168.30.7    website3.domain.com
192.168.30.7    website4.domain.com
192.168.30.7    website5.domain.com
192.168.30.7    website6.domain.com
192.168.30.7    website7.domain.com
192.168.30.8    website8.domain.com
192.168.30.8    website9.domain.com
192.168.30.8    website10.domain.com
192.168.30.8    website11.domain.com
192.168.30.9    website12.domain.com
192.168.30.8    website13.domain.com
192.168.30.8    website14.domain.com
192.168.30.24   website15.domain.com
192.168.30.8    website16.domain.com
192.168.30.8    website17.domain.com
</code>```

I want to do a distinct query for the IP Address and combine the SiteName like below

```<code>IPAddress       WebsiteName
192.168.30.6    website1, website2,
192.168.30.7    website3, website4, website5, website6, website7
192.168.30.8    website8, website9, website10, website11, website13, website14
192.168.30.9    website12
192.168.30.24   website15
</code>```

I can able to combine the IPAddress using the below query but how to combine the appropriate Sitename to the IP Address.

```<code>Update Table1
Set IP= (Select IPAddress + ',' + ' '
From dbo.WebsiteIP
GROUP BY IPAddress FOR XML PATH(''))
GO
</code>```

答:
The right answer to this is fixing your data modal.

To get the desired result, you can do

```<code>SELECT T.IpAddress,
       STUFF(
              (
                SELECT ',' + LEFT(WebsiteName, CHARINDEX('.', WebsiteName)-1)
                FROM Data TT
                WHERE TT.IpAddress = T.IpAddress
                FOR XML PATH('')
              )
              , 1, 1, ''
            ) Result
FROM Data T
GROUP BY T.IpAddress;
</code>```

Online Demo

Body:
I have a table named dbo.WebsiteIP having two columns IPAddress, SiteName, and I am doing a bulk insert the values to the this table which look like below

IPAddress       SiteName
192.168.30.6    website1.domain.com
192.168.30.6    website2.domain.com
192.168.30.7    website3.domain.com
192.168.30.7    website4.domain.com
192.168.30.7    website5.domain.com
192.168.30.7    website6.domain.com
192.168.30.7    website7.domain.com
192.168.30.8    website8.domain.com
192.168.30.8    website9.domain.com
192.168.30.8    website10.domain.com
192.168.30.8    website11.domain.com
192.168.30.9    website12.domain.com
192.168.30.8    website13.domain.com
192.168.30.8    website14.domain.com
192.168.30.24   website15.domain.com
192.168.30.8    website16.domain.com
192.168.30.8    website17.domain.com

I want to do a distinct query for the IP Address and combine the SiteName like below

IPAddress       WebsiteName
192.168.30.6    website1, website2,
192.168.30.7    website3, website4, website5, website6, website7
192.168.30.8    website8, website9, website10, website11, website13, website14
192.168.30.9    website12
192.168.30.24   website15

I can able to combine the IPAddress using the below query but how to combine the appropriate Sitename to the IP Address.

Update Table1
Set IP= (Select IPAddress + ',' + ' '
From dbo.WebsiteIP
GROUP BY IPAddress FOR XML PATH(''))
GO

Body:
The right answer to this is fixing your data modal.

To get the desired result, you can do

SELECT T.IpAddress,
       STUFF(
              (
                SELECT ',' + LEFT(WebsiteName, CHARINDEX('.', WebsiteName)-1)
                FROM Data TT
                WHERE TT.IpAddress = T.IpAddress
                FOR XML PATH('')
              )
              , 1, 1, ''
            ) Result
FROM Data T
GROUP BY T.IpAddress;

Online Demo


问:
Is it possible to display only one array key from a react component returning an array?
I’m very new to react and still experimenting to see how I’m going to transition to this new architecture.

Right now, I have a simple component, that I’m returning an array of elements (just for testing purposes):

```<code>class FrontendCategoriesListing extends Component
{
    render()
    {
        return(
            [
                <h1>
                    First information
                </h1>,
                <h2>
                    Second information
                </h2>,
                < >
                    Third information
                </ >,
                <div>
                    Fourth information
                </div>
            ]
        );
    }
}

export default FrontendCategoriesListing;

</code>```

In my project, right now I’m able to display all elements fine, wherever I want to. But my goal is to display just one element, if I want to. For example: in some cases, I want only to display:

```<code><div>
    Fourth information
</div>
</code>```

The problem is that where I’m using this component, it only displays all elements. I’ve tried to use an array like syntax to display, like [0] or [2], but then it displays nothing. Is there a way to do this using this architecture? Or is there another architecture I should use. It’s very important that I use only one component to pass as many element I want to.

Thanks,

答:
Here's good info about Heroku filesystem

In a nutshell you can't rely on it.

As a alternative you can use AWS S3, Azure Blob Storage, Google Storage.

Another idea would be converting image to dataUrl and put it (with all relevant information about file) in free tier database like MongoDB Atlas. Unfortunately that requires additional implementation

Body:
I’m very new to react and still experimenting to see how I’m going to transition to this new architecture.

Right now, I have a simple component, that I’m returning an array of elements (just for testing purposes):

class FrontendCategoriesListing extends Component
{
    render()
    {
        return(
            [

                    First information

,

                    Second information

,
                < >
                    Third information
                </ >,

                    Fourth information

            ]
        );
    }
}

export default FrontendCategoriesListing;

In my project, right now I’m able to display all elements fine, wherever I want to. But my goal is to display just one element, if I want to. For example: in some cases, I want only to display:

    Fourth information

The problem is that where I’m using this component, it only displays all elements. I’ve tried to use an array like syntax to display, like [0] or [2], but then it displays nothing. Is there a way to do this using this architecture? Or is there another architecture I should use. It’s very important that I use only one component to pass as many element I want to.

Thanks,


答:
Try this one:

```<code>onPressBuyNow = () => {
  this.addToCart(); // function one
  navigation.navigate(homeTabs.cart); // function two
}
</code>```

The answer would be either this or create a wrapper function like other folks suggest.

Edit

Modified the answer after Michael Mishin's comment.

Title: How call two function under onPress in react

Body:
Try this one:

onPressBuyNow = () => {
  this.addToCart(); // function one
  navigation.navigate(homeTabs.cart); // function two
}

The answer would be either this or create a wrapper function like other folks suggest.

Edit

Modified the answer after Michael Mishin's comment.


问:
Repository insert with navigation property throws 'FOREIGN KEY constraint failed'
I'm using EF Core and sqlite. Given following 1-to-1 entities:

```<code>  public class Entity1:FullAuditedEntity<int>
  {
    public Entity2 Entity2 { get; set; }

    public string Name { get; set; }

  }

  public class Entity2: FullAuditedEntity<int>
  {

    public string Name { get; set; }

    [ForeignKey("Entity1Id")]
    public Entity1 Entity1{ get; set; }
    public int Entity1Id { get; set; }
  }
</code>```

and following insert logic:

```<code>    entity1.Entity2 = new Entity2();
    entity1= await entity1Repository.InsertAsync(entity1);//entity1Repository is of type IRepository<Entity1>
</code>```

Code above throws:

Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
---- Microsoft.Data.Sqlite.SqliteException : SQLite Error 19: 'FOREIGN KEY constraint failed'.
   at  ...

This approach doesn't work either, throws the same:

```<code>    var entity2 = new Entity2();
    entity1.Entity2 = entity2;
    entity2.Entity1 = entity1;
    entity1= await entity1Repository.InsertAsync(entity1);//entity1Repository
</code>```

What I'm doing wrong, what I'm missing? What is the correct way to create Entity1 and Entity2 with  Entity2 property being set? Is it possible to create with Entity1 repo only?

Thanks in advance.

Update: Problem solved. In actual code entity2 has it's own reference on entity3, which is obvoiusly was throwing. It was the cause.

答: See update in my post -- there was other entity which violated fk constraints. Thanks everyone for your time.</p>

Body:
I'm using EF Core and sqlite. Given following 1-to-1 entities:

  public class Entity1:FullAuditedEntity<int>
  {
    public Entity2 Entity2 { get; set; }

    public string Name { get; set; }

  }

  public class Entity2: FullAuditedEntity<int>
  {

    public string Name { get; set; }

    [ForeignKey("Entity1Id")]
    public Entity1 Entity1{ get; set; }
    public int Entity1Id { get; set; }
  }

and following insert logic:

    entity1.Entity2 = new Entity2();
    entity1= await entity1Repository.InsertAsync(entity1);//entity1Repository is of type IRepository<Entity1>

Code above throws:

Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
---- Microsoft.Data.Sqlite.SqliteException : SQLite Error 19: 'FOREIGN KEY constraint failed'.
   at  ...

This approach doesn't work either, throws the same:

    var entity2 = new Entity2();
    entity1.Entity2 = entity2;
    entity2.Entity1 = entity1;
    entity1= await entity1Repository.InsertAsync(entity1);//entity1Repository

What I'm doing wrong, what I'm missing? What is the correct way to create Entity1 and Entity2 with  Entity2 property being set? Is it possible to create with Entity1 repo only?

Thanks in advance.

Update: Problem solved. In actual code entity2 has it's own reference on entity3, which is obvoiusly was throwing. It was the cause.


问:
Append pandas dataframe with dictionary using for loop
I have the following dictionary and I want to add these in to a pandas dataframe:

```<code>crimes1 = {'SOUTHERN': 28445,
 'NORTHERN': 20100,
 'MISSION': 19503}
</code>```

I create the blank dataframe with the column names I want:

```<code>column_names = ['Neighborhood', 'Count']
crimes2 = pd.DataFrame(columns=column_names)
</code>```

Next I want to append the dataframe with my dictionary containing the keys and values above using a for loop:

```<code>for i, x in crimes1:
    crimes2 = crimes2.append({'Neighborhood': i}, {'Count': x}, ignore_index=True)
</code>```

The error I get is ValueError: too many values to unpack (expected 2)

I can populate only one column when I do it separately but can't seem to get both in to the one dataframe. Any ideas on how to get this to work using the for loop above?

答:
You are getting ValueError because you are not calling crimes1.items() which is require to iterate over the key, value pairs of dictionary. Simply, Use:

```<code>for i, x in crimes1.items():
    crimes2 = crimes2.append({'Neighborhood': i, 'Count': x}, ignore_index=True)
</code>```

Result:

```<code># print(crimes2)
  Neighborhood  Count
0     SOUTHERN  28445
1     NORTHERN  20100
2      MISSION  19503
</code>```

Body:
I have the following dictionary and I want to add these in to a pandas dataframe:

crimes1 = {'SOUTHERN': 28445,
 'NORTHERN': 20100,
 'MISSION': 19503}

I create the blank dataframe with the column names I want:

column_names = ['Neighborhood', 'Count']
crimes2 = pd.DataFrame(columns=column_names)

Next I want to append the dataframe with my dictionary containing the keys and values above using a for loop:

for i, x in crimes1:
    crimes2 = crimes2.append({'Neighborhood': i}, {'Count': x}, ignore_index=True)

The error I get is ValueError: too many values to unpack (expected 2)

I can populate only one column when I do it separately but can't seem to get both in to the one dataframe. Any ideas on how to get this to work using the for loop above?

Body:
You are getting ValueError because you are not calling crimes1.items() which is require to iterate over the key, value pairs of dictionary. Simply, Use:

for i, x in crimes1.items():
    crimes2 = crimes2.append({'Neighborhood': i, 'Count': x}, ignore_index=True)

Result:

# print(crimes2)
  Neighborhood  Count
0     SOUTHERN  28445
1     NORTHERN  20100
2      MISSION  19503


问:
How to find last element in a collection in MongoDB?
I have a collection name Users in Mongo DB Atlas.

```<code>{"_id":{"$oid":"5ebe6fdc9f17193b6c51063e"},"name":"Harry","country":"India","gender":"male"}
{"_id":{"$oid":"6fbe6fdc9f17193b6c52463e"},"name":"John","country":"Africa","gender":"male"}
{"_id":{"$oid":"7gbe6fdc9f17193b6c58063e"},"name":"Mike","country":"USA","gender":"male"}
{"_id":{"$oid":"8hbe6fdc9f17193b6c53063e"},"name":"Alice","country":"India","gender":"female"}
{"_id":{"$oid":"9ebe6fdc9f17193b6c52063e"},"name":"Katherine","country":"UK","gender":"female"}
</code>```

and its goes on.

What query can be used in node.js and mongoose to find last element in the collection?
How I can get the id of the last element of the collection when the collection keeps on increasing dynamically?

答:
Since you have your _id as ObjectId type, you can sort by _id and the sorting order will be in order of creation.

```<code>items.find().sort([['_id', -1]] ) // get all items desc by created date.
</code>```

And if you want the last created item, you can use the following query:

```<code>items.find().sort( [['_id', -1]]).limit(1) // get last created item
</code>```

In essence, ordering by "_id" will order by creation date.

Body:
I have a collection name Users in Mongo DB Atlas.

{"_id":{"$oid":"5ebe6fdc9f17193b6c51063e"},"name":"Harry","country":"India","gender":"male"}
{"_id":{"$oid":"6fbe6fdc9f17193b6c52463e"},"name":"John","country":"Africa","gender":"male"}
{"_id":{"$oid":"7gbe6fdc9f17193b6c58063e"},"name":"Mike","country":"USA","gender":"male"}
{"_id":{"$oid":"8hbe6fdc9f17193b6c53063e"},"name":"Alice","country":"India","gender":"female"}
{"_id":{"$oid":"9ebe6fdc9f17193b6c52063e"},"name":"Katherine","country":"UK","gender":"female"}

and its goes on.

What query can be used in node.js and mongoose to find last element in the collection?
How I can get the id of the last element of the collection when the collection keeps on increasing dynamically?

Body:
Since you have your _id as ObjectId type, you can sort by _id and the sorting order will be in order of creation.

items.find().sort([['_id', -1]] ) // get all items desc by created date.

And if you want the last created item, you can use the following query:

items.find().sort( [['_id', -1]]).limit(1) // get last created item

In essence, ordering by "_id" will order by creation date.


问:
WebView into SizedBox Flutter
I would like to add a custom webview into a sizedBox in flutter... I've tried to do that but there is an error:

code:

```<code>@override
   Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
    return new Scaffold(
      key: _scaffoldKey,
         floatingActionButton: new Row(
        mainAxisSize: MainAxisSize.min,
            children: <Widget>[
                new GestureDetector(
                  child: new Image.network("http://modernworfare.altervista.org/pause.png", width: 80.0,),
                  onTap: (){stop(); _showSnackBar();},
                ),
                new GestureDetector(
                  child: new Image.network("http://modernworfare.altervista.org/bg.png",width: 80.0,),
                  onTap: (){play(); _showSnackBar2();},
                ),
              ],
         ),
      backgroundColor: Colors.black,
      body: new ListView(
        children: <Widget>[
        new Column(
        children: <Widget>[
          new Image.network("https://scontent-mxp1-1.xx.fbcdn.net/v/t1.0-9/16864236_1836092593321492_1828236030296093399_n.jpg?_nc_cat=0&oh=817190c0ef6ac6e3076582905997f3e9&oe=5B81BFF9"),
          new Divider(),
          new Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              new Container(
              padding: new EdgeInsets.all(8.0),
              child: new Text("  WEBSITE  ", style: new TextStyle(color: Colors.white,)),
              decoration: new BoxDecoration(
                borderRadius: new BorderRadius.circular(10.0),
                border: new Border.all(
                  width: 4.0,
                  color: Colors.white,
                  ),
                ),
              ),
              new Container(
              padding: new EdgeInsets.all(8.0),
              child: new Text("  SOCIAL  ", style: new TextStyle(color: Colors.white,)),
              decoration: new BoxDecoration(
                borderRadius: new BorderRadius.circular(10.0),
                border: new Border.all(
                  width: 4.0,
                  color: Colors.white,
                  ),
                ),
              ),
              new Container(
              padding: new EdgeInsets.all(8.0),
              child: new Text("  SHOP  ", style: new TextStyle(color: Colors.white,)),
              decoration: new BoxDecoration(
               borderRadius: new BorderRadius.circular(10.0),
                border: new Border.all(
                  width: 4.0,
                  color: Colors.white,
                  ),
                ),
              ),
              new Container(
              padding: new EdgeInsets.all(8.0),
              child: new Text("  CONTACT  ", style: new TextStyle(color: Colors.white,)),
              decoration: new BoxDecoration(
               borderRadius: new BorderRadius.circular(10.0),
                border: new Border.all(
                  width: 4.0,
                  color: Colors.white,
                  ),
                ),
              )],
          ),
          new Text("hi",style: new TextStyle(color: Colors.white), ),
          new SizedBox(
            height: 50.0,
            width: 600.0,
            child: webview.launch("url",
            )
          ),
          ],
        )],
      ),
    );
  }
</code>```

error:

The argument type 'Future' can't be assigned to the parameter type 'Widget'.

any suggestions or ideas?
is it possible to do that?
maybe adding a future builder or something like that?

答: Here's webview_flutter_plus an extension of webview_flutter which allows getting the height of Web content which will allow you to use it even in a listview, this also helps to load HTML, CSS and Javascript content even from Assets or Strings. This inherits all features of webview_flutter with minor API changes.</p>

Title: WebView into SizedBox Flutter

Body:
I would like to add a custom webview into a sizedBox in flutter... I've tried to do that but there is an error:

code:

@override
   Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
    return new Scaffold(
      key: _scaffoldKey,
         floatingActionButton: new Row(
        mainAxisSize: MainAxisSize.min,
            children: <Widget>[
                new GestureDetector(
                  child: new Image.network("http://modernworfare.altervista.org/pause.png", width: 80.0,),
                  onTap: (){stop(); _showSnackBar();},
                ),
                new GestureDetector(
                  child: new Image.network("http://modernworfare.altervista.org/bg.png",width: 80.0,),
                  onTap: (){play(); _showSnackBar2();},
                ),
              ],
         ),
      backgroundColor: Colors.black,
      body: new ListView(
        children: <Widget>[
        new Column(
        children: <Widget>[
          new Image.network("https://scontent-mxp1-1.xx.fbcdn.net/v/t1.0-9/16864236_1836092593321492_1828236030296093399_n.jpg?_nc_cat=0&oh=817190c0ef6ac6e3076582905997f3e9&oe=5B81BFF9"),
          new Divider(),
          new Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              new Container(
              padding: new EdgeInsets.all(8.0),
              child: new Text("  WEBSITE  ", style: new TextStyle(color: Colors.white,)),
              decoration: new BoxDecoration(
                borderRadius: new BorderRadius.circular(10.0),
                border: new Border.all(
                  width: 4.0,
                  color: Colors.white,
                  ),
                ),
              ),
              new Container(
              padding: new EdgeInsets.all(8.0),
              child: new Text("  SOCIAL  ", style: new TextStyle(color: Colors.white,)),
              decoration: new BoxDecoration(
                borderRadius: new BorderRadius.circular(10.0),
                border: new Border.all(
                  width: 4.0,
                  color: Colors.white,
                  ),
                ),
              ),
              new Container(
              padding: new EdgeInsets.all(8.0),
              child: new Text("  SHOP  ", style: new TextStyle(color: Colors.white,)),
              decoration: new BoxDecoration(
               borderRadius: new BorderRadius.circular(10.0),
                border: new Border.all(
                  width: 4.0,
                  color: Colors.white,
                  ),
                ),
              ),
              new Container(
              padding: new EdgeInsets.all(8.0),
              child: new Text("  CONTACT  ", style: new TextStyle(color: Colors.white,)),
              decoration: new BoxDecoration(
               borderRadius: new BorderRadius.circular(10.0),
                border: new Border.all(
                  width: 4.0,
                  color: Colors.white,
                  ),
                ),
              )],
          ),
          new Text("hi",style: new TextStyle(color: Colors.white), ),
          new SizedBox(
            height: 50.0,
            width: 600.0,
            child: webview.launch("url",
            )
          ),
          ],
        )],
      ),
    );
  }

error:

The argument type 'Future' can't be assigned to the parameter type 'Widget'.

any suggestions or ideas?
is it possible to do that?
maybe adding a future builder or something like that?


问:
cfn-signal no working in ubuntu stack timeout
```<code>TestInstance:
  Type: AWS::EC2::Instance
  CreationPolicy:
    ResourceSignal:
      Timeout: PT5M
  Properties:
    ImageId: ami-02a599eb01e3b3c5b
    InstanceType: t2.micro
    KeyName: TestKey
    SecurityGroupIds: !Ref sg
    UserData:
      Fn::Base64: |
          #!/bin/bash -x
          apt install -y python-pip
          pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz
          /opt/aws/bin/cfn-signal -e $? --stack teststack --resource TestInstance --region ap-southeast-2
</code>```

答:
Your use of cfn-signal is  incorrect. This is because it has different location on Ubuntu than on Amazon Linux.

Amazon Linux: /opt/aws/bin/cfn-signal

Ubuntu: /usr/local/bin/cfn-signal

Therefore, instead of

```<code>/opt/aws/bin/cfn-signal -e $? --stack teststack --resource TestInstance --region ap-southeast-2
</code>```

you should have :

```<code>/usr/local/bin/cfn-signal -e $? --stack teststack --resource TestInstance --region ap-southeast-2
</code>```

If this won't help, please double check that teststack and ap-southeast-2 are correct. Also make sure the instance has internet access.

Body:
Your use of cfn-signal is  incorrect. This is because it has different location on Ubuntu than on Amazon Linux.

Amazon Linux: /opt/aws/bin/cfn-signal

Ubuntu: /usr/local/bin/cfn-signal

Therefore, instead of

/opt/aws/bin/cfn-signal -e $? --stack teststack --resource TestInstance --region ap-southeast-2

you should have :

/usr/local/bin/cfn-signal -e $? --stack teststack --resource TestInstance --region ap-southeast-2

If this won't help, please double check that teststack and ap-southeast-2 are correct. Also make sure the instance has internet access.


问:
How to get char[] to work with std::map
EDIT after answered:

< should be provided for std::map. For more information about best practice, go for James McNellis's answer.

The code included in this question is poorly written. It is just because I am playing with SPOJ and the input data is strictly valid. The std::string approach is what I chose at first, but it turned out to be not fast enough.

Thank you.

I know I cannot use char[] directly with map, such as map<char[], int>. Thus I put it in a class. But it still can go through compilation. How to deal with that?

```<code>#include <stdio.h>
#include <map>

using namespace std;

class id {
public:
    char v [30];
};

int main () {
    map<id, int> m;
    id a;
    while (gets(a.v)) {
        m[a]++;
    }
    return 0;
}
</code>```

```<code>/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = id]’:
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_map.h:418:   instantiated from ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = id, _Tp = int, _Compare = std::less<id>, _Alloc = std::allocator<std::pair<const id, int> >]’
prog.cpp:15:   instantiated from here
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’
</code>```

It seems it has something to do with comparison, but I am still in the dark.

答:
In order to insert into the map, the map needs to be able to compare id's.  You haven't provided an implementation of operator< that it can use.  You have two options:

Provide one, example given by another answer here.

Use std::string instead.

I think you should use std::string.  You can use the .c_str() method to convert it to a char array when you need to.

Title: How to get char[] to work with std::map

Body:
EDIT after answered:

< should be provided for std::map. For more information about best practice, go for James McNellis's answer.

The code included in this question is poorly written. It is just because I am playing with SPOJ and the input data is strictly valid. The std::string approach is what I chose at first, but it turned out to be not fast enough.

Thank you.

I know I cannot use char[] directly with map, such as map<char[], int>. Thus I put it in a class. But it still can go through compilation. How to deal with that?

#include <stdio.h>
#include <map>

using namespace std;

class id {
public:
    char v [30];
};

int main () {
    map<id, int> m;
    id a;
    while (gets(a.v)) {
        m[a]++;
    }
    return 0;
}

/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = id]’:
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_map.h:418:   instantiated from ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = id, _Tp = int, _Compare = std::less<id>, _Alloc = std::allocator<std::pair<const id, int> >]’
prog.cpp:15:   instantiated from here
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’

It seems it has something to do with comparison, but I am still in the dark.


问:
how to reset element after addEventListener
I have this code for client-side file size check on a file upload form (after which I have server side file size check too):

```

My problem is when I select a file larger than the allowed max size and I get the alert button, after that I cannot select a smaller file (if I do I keep getting the same error alert).
How can I reset the listening event so it recalculates the next time a file is added?

thank you

答:
After further testing I realized the alert() needed to be inside the if statement or it would always trigger, no matter what the image size is, but I also implemented the suggestion above to reset the value of the file input otherwise it would maintain the value of the image that's too big, so the adjusted code is this:

```<code><script type='text/javascript'>
    document.getElementById('file_to_upload').addEventListener('change', checkFile, false);
    function checkFile(e) {
        var file_list = e.target.files;
        for (var i = 0, file; file = file_list[i]; i++) {
            if( file.size > <?php echo $max_file_size; ?> ) {
                var txt = "Your file is too big. Please keep files under " + (<?php echo $max_file_size; ?> / (1024*1024)).toFixed(1) + "Mb. Your file is " + (file.size / (1024*1024)).toFixed(1) + " Mb. \n";
                alert(txt);
                document.getElementById('file_to_upload').value = "";
            }
        }
    }
</script>
</code>```

Body:
I have this code for client-side file size check on a file upload form (after which I have server side file size check too):

My problem is when I select a file larger than the allowed max size and I get the alert button, after that I cannot select a smaller file (if I do I keep getting the same error alert).
How can I reset the listening event so it recalculates the next time a file is added?

thank you

Body:
After further testing I realized the alert() needed to be inside the if statement or it would always trigger, no matter what the image size is, but I also implemented the suggestion above to reset the value of the file input otherwise it would maintain the value of the image that's too big, so the adjusted code is this:

<script type='text/javascript'>
    document.getElementById('file_to_upload').addEventListener('change', checkFile, false);
    function checkFile(e) {
        var file_list = e.target.files;
        for (var i = 0, file; file = file_list[i]; i++) {
            if( file.size > <?php echo $max_file_size; ?> ) {
                var txt = "Your file is too big. Please keep files under " + (<?php echo $max_file_size; ?> / (1024*1024)).toFixed(1) + "Mb. Your file is " + (file.size / (1024*1024)).toFixed(1) + " Mb. \n";
                alert(txt);
                document.getElementById('file_to_upload').value = "";
            }
        }
    }
</script>


问:
maven-scala-plugin error running scala code in a Maven project in IntelliJ
I'm trying to create my first "Hello World" Scala project using Maven as the build tool and IntelliJ as my IDE. I keep getting the following error when running mvn package.

```<code>Failed to execute goal org.scala-tools:maven-scala-plugin:2.15.2:compile
</code>```

Here is the full error:
Failed to execute goal org.scala-tools:maven-scala-plugin:2.15.2:compile (default) on project couchbase-test-3: wrap: org.apache.commons.exec.ExecuteException: Process exited with an error: 1(Exit value: 1)

Here is my pom.xml file.

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>couchbase-test-3</artifactId>
  <version>1.0-SNAPSHOT</version>
  <inceptionYear>2008</inceptionYear>
  <properties>
    <scala.version>2.7.0</scala.version>
  </properties>

  <repositories>
    <repository>
      <id>scala-tools.org</id>
      <name>Scala-Tools Maven2 Repository</name>
      <url>http://scala-tools.org/repo-releases</url>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>scala-tools.org</id>
      <name>Scala-Tools Maven2 Repository</name>
      <url>http://scala-tools.org/repo-releases</url>
    </pluginRepository>
  </pluginRepositories>

  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.specs</groupId>
      <artifactId>specs</artifactId>
      <version>1.2.5</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <testSourceDirectory>src/test/scala</testSourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <version>2.15.2</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <scalaVersion>${scala.version}</scalaVersion>
          <args>
            <arg>-target:jvm-1.5</arg>
          </args>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>2.9</version>
        <configuration>
          <downloadSources>true</downloadSources>
          <buildcommands>
            <buildcommand>ch.epfl.lamp.sdt.core.scalabuilder</buildcommand>
          </buildcommands>
          <additionalProjectnatures>
            <projectnature>ch.epfl.lamp.sdt.core.scalanature</projectnature>
          </additionalProjectnatures>
          <classpathContainers>
            <classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER</classpathContainer>
            <classpathContainer>ch.epfl.lamp.sdt.launching.SCALA_CONTAINER</classpathContainer>
          </classpathContainers>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <version>2.15.2</version>
        <configuration>
          <scalaVersion>${scala.version}</scalaVersion>
        </configuration>
      </plugin>
    </plugins>
  </reporting>
</project>
</code>```

The JDK I'm using is /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home.

The code I'm trying to run is just to print out "Hello World!":

```<code>package org.example

/**
 * Hello world!
 *
 */
object App extends Application {
  println( "Hello World!" )
}
</code>```

Any ideas how to fix this?

答:
I would try to create the Scala project from scratch again, you can follow this link to build a simple Scala project with Maven:

Creating the most basic Scala project with Maven?

Another option would be, when you are creating a Scala project with Maven you can choose an archetype for scala projects, and clean from the pom.xml what you don't need, that worked for me.

On the other hand you could choose SBT to create Scala projects. SBT is very easy and fully integrated with IntelliJ Idea, so you can create a SBT project in IntlliJ and make up the build.sbt file yourself and put in it the scala version you want, compile, package and execute with SBT.

As an example

```<code>name := "my_first_scala_app"

version := "0.1"

scalaVersion := "2.12.8"

libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.0-SNAP3" % Test
</code>```

I hope this helps.

Body:
I'm trying to create my first "Hello World" Scala project using Maven as the build tool and IntelliJ as my IDE. I keep getting the following error when running mvn package.

Failed to execute goal org.scala-tools:maven-scala-plugin:2.15.2:compile

Here is the full error:
Failed to execute goal org.scala-tools:maven-scala-plugin:2.15.2:compile (default) on project couchbase-test-3: wrap: org.apache.commons.exec.ExecuteException: Process exited with an error: 1(Exit value: 1)

Here is my pom.xml file.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>couchbase-test-3</artifactId>
  <version>1.0-SNAPSHOT</version>
  <inceptionYear>2008</inceptionYear>
  <properties>
    <scala.version>2.7.0</scala.version>
  </properties>

  <repositories>
    <repository>
      <id>scala-tools.org</id>
      <name>Scala-Tools Maven2 Repository</name>
      <url>http://scala-tools.org/repo-releases</url>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>scala-tools.org</id>
      <name>Scala-Tools Maven2 Repository</name>
      <url>http://scala-tools.org/repo-releases</url>
    </pluginRepository>
  </pluginRepositories>

  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.specs</groupId>
      <artifactId>specs</artifactId>
      <version>1.2.5</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <testSourceDirectory>src/test/scala</testSourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <version>2.15.2</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <scalaVersion>${scala.version}</scalaVersion>
          <args>
            <arg>-target:jvm-1.5</arg>
          </args>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>2.9</version>
        <configuration>
          <downloadSources>true</downloadSources>
          <buildcommands>
            <buildcommand>ch.epfl.lamp.sdt.core.scalabuilder</buildcommand>
          </buildcommands>
          <additionalProjectnatures>
            <projectnature>ch.epfl.lamp.sdt.core.scalanature</projectnature>
          </additionalProjectnatures>
          <classpathContainers>
            <classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER</classpathContainer>
            <classpathContainer>ch.epfl.lamp.sdt.launching.SCALA_CONTAINER</classpathContainer>
          </classpathContainers>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <version>2.15.2</version>
        <configuration>
          <scalaVersion>${scala.version}</scalaVersion>
        </configuration>
      </plugin>
    </plugins>
  </reporting>
</project>

The JDK I'm using is /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home.

The code I'm trying to run is just to print out "Hello World!":

package org.example

/**
 * Hello world!
 *
 */
object App extends Application {
  println( "Hello World!" )
}

Any ideas how to fix this?

Body:
I would try to create the Scala project from scratch again, you can follow this link to build a simple Scala project with Maven:

Creating the most basic Scala project with Maven?

Another option would be, when you are creating a Scala project with Maven you can choose an archetype for scala projects, and clean from the pom.xml what you don't need, that worked for me.

On the other hand you could choose SBT to create Scala projects. SBT is very easy and fully integrated with IntelliJ Idea, so you can create a SBT project in IntlliJ and make up the build.sbt file yourself and put in it the scala version you want, compile, package and execute with SBT.

As an example

name := "my_first_scala_app"

version := "0.1"

scalaVersion := "2.12.8"

libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.0-SNAP3" % Test

I hope this helps.


问:
Generate openssl password with Ruby
I'd like to use the ruby openssl library to generate the same thing as this openssl command:

```<code>$ openssl passwd -1 mypassword
</code>```

Right now, in my code, I'm doing this:

```<code>mypass = `openssl passwd -1 mypassword`
</code>```

... this works, but it seems silly.  I feel like you should be able to use OpenSSL::Digest to achieve the same result.  However, I can't seem to get it to work.

答:
This is compatible with openssl passwd -1

require 'openssl'

module CryptMD5
  refine String do
    def crypt_md5 salt = OpenSSL::Random.random_bytes(6)
      crypt ['$1$', salt].pack('a3m0').tr(?+, ?.).delete(?=)
    end
  end
end

using CryptMD5
pass = '$1$i7VbAY.b$uy5kgtLn8m2daMxOBEz6p.'
salt = pass[3..10].tr(?., ?+).unpack1 'm0'

puts pass == 'secret'.crypt_md5(salt) # => true
puts pass == 'secret'.crypt_md5(salt + 'ignored extra') # => true
puts 'secret'.crypt_md5 # => $1$bMylNdtr$/fxt7r7gzdossTabWD/xT/
puts 'secret'.crypt_md5 # => $1$y6O7OsY7$bDl3yEKJXM0lhg3DYye6Z1

pass = `openssl passwd -1 secret`.chomp
salt =  pass[3..10].tr(?., ?+).unpack1 'm0'
puts pass == 'secret'.crypt_md5(salt) # => true
```

Calling String#crypt with a string usually only uses the first two characters as salt, but if prefixed with $1$ it will use the next 6 bytes / 8 characters as a salt with a modified base64 alphabet (swapping + and .). Any more bytes / chars are just truncated.

Title: Generate openssl password with Ruby

Body:
I'd like to use the ruby openssl library to generate the same thing as this openssl command:

$ openssl passwd -1 mypassword

Right now, in my code, I'm doing this:

mypass = `openssl passwd -1 mypassword`

... this works, but it seems silly.  I feel like you should be able to use OpenSSL::Digest to achieve the same result.  However, I can't seem to get it to work.

Body:
This is compatible with openssl passwd -1

require 'openssl'

module CryptMD5
  refine String do
    def crypt_md5 salt = OpenSSL::Random.random_bytes(6)
      crypt ['$1$', salt].pack('a3m0').tr(?+, ?.).delete(?=)
    end
  end
end

using CryptMD5
pass = '$1$i7VbAY.b$uy5kgtLn8m2daMxOBEz6p.'
salt = pass[3..10].tr(?., ?+).unpack1 'm0'

puts pass == 'secret'.crypt_md5(salt) # => true
puts pass == 'secret'.crypt_md5(salt + 'ignored extra') # => true
puts 'secret'.crypt_md5 # => $1$bMylNdtr$/fxt7r7gzdossTabWD/xT/
puts 'secret'.crypt_md5 # => $1$y6O7OsY7$bDl3yEKJXM0lhg3DYye6Z1

pass = `openssl passwd -1 secret`.chomp
salt =  pass[3..10].tr(?., ?+).unpack1 'm0'
puts pass == 'secret'.crypt_md5(salt) # => true

Calling String#crypt with a string usually only uses the first two characters as salt, but if prefixed with $1$ it will use the next 6 bytes / 8 characters as a salt with a modified base64 alphabet (swapping + and .). Any more bytes / chars are just truncated.


问:
How to set a variable and check it for null both in the "case when" conditions SQL
I have problem with this piece of code.

I need to do something like this:

```<code>DECLARE @UserID INT
...
    CASE
        WHEN (@UserID = (SELECT TOP 1 UserPk FROM Users WHERE Name= 'JoeDoe')) IS NULL
        THEN 0
        ELSE 1
    END
</code>```

I need set @UserID for some other next steps and at the same time need to check (SELECT TOP 1 UserPk FROM Users WHERE Name = 'JoeDoe') for null.

Thanks for help.

答:
Just use below:</p>

```<code>DECLARE @UserID INT
SET @UserID = ISNULL((SELECT TOP(1) 1 FROM Users WHERE Name= 'JoeDoe'), 0)

Print @UserID
</code>```

Body:
I have problem with this piece of code.

I need to do something like this:

DECLARE @UserID INT
...
    CASE
        WHEN (@UserID = (SELECT TOP 1 UserPk FROM Users WHERE Name= 'JoeDoe')) IS NULL
        THEN 0
        ELSE 1
    END

I need set @UserID for some other next steps and at the same time need to check (SELECT TOP 1 UserPk FROM Users WHERE Name = 'JoeDoe') for null.

Thanks for help.

Body:
Just use below:

DECLARE @UserID INT
SET @UserID = ISNULL((SELECT TOP(1) 1 FROM Users WHERE Name= 'JoeDoe'), 0)

Print @UserID