问:
Django and read-only database connections
Assume a Django application which is supposed to use two MySQL databases:

default - for storing data represented by models A and B (read-write access)

support - for importing data represented by models C and D (read-only access)

The support database is a part of an external application and cannot be modified.

Since the Django application uses the built-in ORM for models A and B I figured it should use the very same ORM for models C and D, even though they map to tables in an external database (support.)

In order to achieve that I defined the models C and D as follows:

from django.db import models

class ExternalModel(models.Model):
    class Meta:
        managed = False
        abstract = True

class ModelC(ExternalModel):
    some_field = models.TextField(db_column='some_field')

    class Meta(ExternalModel.Meta):
        db_table = 'some_table_c'

class ModelD(ExternalModel):
    some_other_field = models.TextField(db_column='some_other_field')

    class Meta(ExternalModel.Meta):
        db_table = 'some_table_d'
```

<p>Then I defined a database router:</p>

<pre class="lang-python prettyprint-override"><code>from myapp.myapp.models import ExternalModel

class DatabaseRouter(object):
    def db_for_read(self, model, **hints):
        if issubclass(model, ExternalModel):
            return 'support'

        return 'default'

    def db_for_write(self, model, **hints):
        if issubclass(model, ExternalModel):
            return None

        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        return (isinstance(obj1, ExternalModel) == isinstance(obj2, ExternalModel))

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return (db == 'default')
</code>```

And finally adjusted settings.py:

# (...)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': os.path.join(BASE_DIR, 'resources', 'default.cnf'),
        },
    },
    'support': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': os.path.join(BASE_DIR, 'resources', 'support.cnf'),
        },
    },
}

DATABASE_ROUTERS = ['myapp.database_router.DatabaseRouter']

# (...)
```

<p>The user specified in <code>support.conf</code> for the <code>support</code> database has been assigned read-only privileges.</p>

<p>But when I run <code>python manage.py makemigrations</code> it fails with the following output:</p>

<pre class="lang-none prettyprint-override"><code>    Traceback (most recent call last):
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 112, in execute
    return self.cursor.execute(query, args)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 226, in execute
    self.errorhandler(self, exc, value)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 217, in execute
    res = self._query(query)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 378, in _query
    rowcount = self._do_query(q)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 341, in _do_query
    db.query(q)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1142, "CREATE command denied to user 'somedbuser'@'somehost' for table 'django_migrations'")

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

Traceback (most recent call last):
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 57, in ensure_schema
    editor.create_model(self.Migration)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 295, in create_model
    self.execute(sql, params or None)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 112, in execute
    cursor.execute(sql, params)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 112, in execute
    return self.cursor.execute(query, args)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 226, in execute
    self.errorhandler(self, exc, value)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 217, in execute
    res = self._query(query)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 378, in _query
    rowcount = self._do_query(q)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 341, in _do_query
    db.query(q)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
django.db.utils.OperationalError: (1142, "CREATE command denied to user 'somedbuser'@'somehost' for table 'django_migrations'")

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute
    output = self.handle(*args, **options)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 100, in handle
    loader.check_consistent_history(connection)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/loader.py", line 276, in check_consistent_history
    applied = recorder.applied_migrations()
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
    self.ensure_schema()
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 59, in ensure_schema
    raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc)
django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1142, "CREATE command denied to user 'somedbuser'@'somehost' for table 'django_migrations'"))
</code>```

It appears that Django tries to create the django_migrations table in the read-only database support nevertheless.

Is there any clean way to prevent the migrations mechanism from attempting that? Or do I have to employ another ORM library for this read-only access to the support database?

答:
It seems around the Django 1.10.1 timeframe, Tim Graham (the primary Django maintainer), accepted a patch that suppressed this specific exception but later withdrew the patch in favor of (roughly) the following method to work around this issue and to support read-only databases using the Django ORM.

Define a database router as described in the Django documentation
on routers I've attached an example router below that routes to a
different database based on an 'app' flag in the model meta.

In your routers allow_migrations method, return False for any db argument
that corresponds to a read-only database. This prevents the migration of
the model tables regardless of where they would be routed to.

This next part is a little weird but where the rubber hits the road and
actually answers the original question. To keep makemigrations from
attempting to create the django_migrations table in your read-only
database, the database traffic should not be routed. In the example
router, that means 'read_only' is not in DATABASE_APPS_MAPPING.

So, instead, Read-only databases are accessed explicitly with "using" (e.g. MyReadOnlyModel.objects.using('read_only').all()

Django database apps router

Body:
Assume a Django application which is supposed to use two MySQL databases:

default - for storing data represented by models A and B (read-write access)

support - for importing data represented by models C and D (read-only access)

The support database is a part of an external application and cannot be modified.

Since the Django application uses the built-in ORM for models A and B I figured it should use the very same ORM for models C and D, even though they map to tables in an external database (support.)

In order to achieve that I defined the models C and D as follows:

from django.db import models

class ExternalModel(models.Model):
    class Meta:
        managed = False
        abstract = True

class ModelC(ExternalModel):
    some_field = models.TextField(db_column='some_field')

    class Meta(ExternalModel.Meta):
        db_table = 'some_table_c'

class ModelD(ExternalModel):
    some_other_field = models.TextField(db_column='some_other_field')

    class Meta(ExternalModel.Meta):
        db_table = 'some_table_d'

Then I defined a database router:

from myapp.myapp.models import ExternalModel

class DatabaseRouter(object):
    def db_for_read(self, model, **hints):
        if issubclass(model, ExternalModel):
            return 'support'

        return 'default'

    def db_for_write(self, model, **hints):
        if issubclass(model, ExternalModel):
            return None

        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        return (isinstance(obj1, ExternalModel) == isinstance(obj2, ExternalModel))

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return (db == 'default')

And finally adjusted settings.py:

# (...)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': os.path.join(BASE_DIR, 'resources', 'default.cnf'),
        },
    },
    'support': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': os.path.join(BASE_DIR, 'resources', 'support.cnf'),
        },
    },
}

DATABASE_ROUTERS = ['myapp.database_router.DatabaseRouter']

# (...)

The user specified in support.conf for the support database has been assigned read-only privileges.

But when I run python manage.py makemigrations it fails with the following output:

    Traceback (most recent call last):
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 112, in execute
    return self.cursor.execute(query, args)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 226, in execute
    self.errorhandler(self, exc, value)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 217, in execute
    res = self._query(query)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 378, in _query
    rowcount = self._do_query(q)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 341, in _do_query
    db.query(q)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1142, "CREATE command denied to user 'somedbuser'@'somehost' for table 'django_migrations'")

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

Traceback (most recent call last):
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 57, in ensure_schema
    editor.create_model(self.Migration)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 295, in create_model
    self.execute(sql, params or None)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 112, in execute
    cursor.execute(sql, params)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 112, in execute
    return self.cursor.execute(query, args)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 226, in execute
    self.errorhandler(self, exc, value)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 217, in execute
    res = self._query(query)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 378, in _query
    rowcount = self._do_query(q)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 341, in _do_query
    db.query(q)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
django.db.utils.OperationalError: (1142, "CREATE command denied to user 'somedbuser'@'somehost' for table 'django_migrations'")

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute
    output = self.handle(*args, **options)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 100, in handle
    loader.check_consistent_history(connection)
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/loader.py", line 276, in check_consistent_history
    applied = recorder.applied_migrations()
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
    self.ensure_schema()
  File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 59, in ensure_schema
    raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc)
django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1142, "CREATE command denied to user 'somedbuser'@'somehost' for table 'django_migrations'"))

It appears that Django tries to create the django_migrations table in the read-only database support nevertheless.

Is there any clean way to prevent the migrations mechanism from attempting that? Or do I have to employ another ORM library for this read-only access to the support database?


来源: stackexchange

问:
printToPDF renders in tab size instead of actual window size
My electron app has a print facility, which directly prints the content of my window. It uses Bootstrap for layouts. The electron window is rendered as expected, but while I print the content using printToPDF the generated PDF looks a screenshot of tab size. Have attached images for better understanding.

Code Snippet:

```<code>win.webContents.printToPDF({pageSize:"A4",printBackground: true}, (error, data) => {

    if (error) throw error

    fs.writeFile('print.pdf', data, (error) => {

        if (error) throw error

        console.log('Write PDF successfully.');
    });
});
</code>```

In alternate, I have also tried for window.print() and it produces the same issue.

I need to print the screen as it was displayed in window.

Expected (screenshot of electron window):

Actual (screenshot of generated PDF):

答:
Printing the entire window by getting access to it has worked for me.</p>

```<code>  var childWindow = getWindow("My-Window-Name");

  childWindow.webContents.printToPDF({
     landscape: true
     }, function(err, data) {
     var dist = "";
     var dir = "";
     if (process.platform !== 'darwin') {
     dir = "C:\\store\\" + serialNumber;

     if (!fs.existsSync(dir)){
       fs.mkdirSync(dir);
     }
       dist = dir +  '\\' + serialNumber + '.pdf'
     } else {
       dir = __dirname + '/' + serialNumber;

     if (!fs.existsSync(dir)){
       fs.mkdirSync(dir);
     }
       dist = dir +  '/' + serialNumber + '.pdf'
     }

     fs.writeFile(dist, data, function(err) {
       if(err) console.log('genearte pdf error', err)
     })
     })

// code to get reference to window
   function getWindow(windowName) {
     var windowArray = BrowserWindow.getAllWindows();
     console.log(windowArray[0].getTitle());
     for (var i = 0; i < windowArray.length; i++) {
       if (windowArray[i].getTitle() == windowName) {
         return windowArray[i];
       }
     }
   return null;
   }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My electron app has a print facility, which directly prints the content of my window. It uses Bootstrap for layouts. The electron window is rendered as expected, but while I print the content using printToPDF the generated PDF looks a screenshot of tab size. Have attached images for better understanding.

Code Snippet:

win.webContents.printToPDF({pageSize:"A4",printBackground: true}, (error, data) => {

    if (error) throw error

    fs.writeFile('print.pdf', data, (error) => {

        if (error) throw error

        console.log('Write PDF successfully.');
    });
});

In alternate, I have also tried for window.print() and it produces the same issue.

I need to print the screen as it was displayed in window.

Expected (screenshot of electron window):

Actual (screenshot of generated PDF):

Body:
Printing the entire window by getting access to it has worked for me.

  var childWindow = getWindow("My-Window-Name");

  childWindow.webContents.printToPDF({
     landscape: true
     }, function(err, data) {
     var dist = "";
     var dir = "";
     if (process.platform !== 'darwin') {
     dir = "C:\\store\\" + serialNumber;

     if (!fs.existsSync(dir)){
       fs.mkdirSync(dir);
     }
       dist = dir +  '\\' + serialNumber + '.pdf'
     } else {
       dir = __dirname + '/' + serialNumber;

     if (!fs.existsSync(dir)){
       fs.mkdirSync(dir);
     }
       dist = dir +  '/' + serialNumber + '.pdf'
     }

     fs.writeFile(dist, data, function(err) {
       if(err) console.log('genearte pdf error', err)
     })
     })

// code to get reference to window
   function getWindow(windowName) {
     var windowArray = BrowserWindow.getAllWindows();
     console.log(windowArray[0].getTitle());
     for (var i = 0; i < windowArray.length; i++) {
       if (windowArray[i].getTitle() == windowName) {
         return windowArray[i];
       }
     }
   return null;
   }


问:
Multichoice fields with dynamic linq
I'm making a SP2010 page where user can filter items by their phase (It's a multichoice field). For performance reasons and the nature of the filters I had to resort to System.Linq.Dynamic to make this query.

I've tried the following (this is not real code but exemplifies what I'm doing):

```<code>var lstObjects = new List<object>();
var query = "Phase = @0 ";
lstObjects.Add(Phase.Value);

context.myList.Where(query,lstObjects.ToArray());
</code>```

This works if the item has only one phase and is the one being filtered. If the item has multiple phases (like Phase 1 and 2) and I filter by Phase 1, it must show. How can I filter the multichoice fields?

EDIT: Forgot to mention, the type of the object "Phase.Value" is a flag enum that was generated using SPMetal.

答:
Try context.myList.Where(m=>lstObjects.Contains(m.Phase))  or something in that context.
If this isn't the solution you are looking for please provide with more information on what you mean with "Multi Phases"

a.e, does the user get to select multiple phases or does the object have mutliple phases, or both?

[edit]

I'm not real familiar with dynamic linq but I assume this could be a solution:

```<code>var lstObjects = new List<object>();
var query = "Phase == {0}";
lstObjects.Add(Phase.Value);
for (int i = 1; i < Phase.Count; i++)
{
    query += string.Format(" || Phase == {0}", i);
}

context.myList.Where(query,lstObjects.ToList());
</code>```

or

```<code>for (int i = 0; i < Phase.Count; i++)
{
    if (i > 0) { query+= " || "; }
    query += string.Format("Phase == {0}", lstObjects[i].Value);
}
context.MyList.Where(query);
</code>```

Let me know if this works.

[/edit]

ContentLicense: CC BY-SA 2.5

Title: Multichoice fields with dynamic linq

Body:
I'm making a SP2010 page where user can filter items by their phase (It's a multichoice field). For performance reasons and the nature of the filters I had to resort to System.Linq.Dynamic to make this query.

I've tried the following (this is not real code but exemplifies what I'm doing):

var lstObjects = new List<object>();
var query = "Phase = @0 ";
lstObjects.Add(Phase.Value);

context.myList.Where(query,lstObjects.ToArray());

This works if the item has only one phase and is the one being filtered. If the item has multiple phases (like Phase 1 and 2) and I filter by Phase 1, it must show. How can I filter the multichoice fields?

EDIT: Forgot to mention, the type of the object "Phase.Value" is a flag enum that was generated using SPMetal.

Body:
Try context.myList.Where(m=>lstObjects.Contains(m.Phase))  or something in that context.
If this isn't the solution you are looking for please provide with more information on what you mean with "Multi Phases"

a.e, does the user get to select multiple phases or does the object have mutliple phases, or both?

[edit]

I'm not real familiar with dynamic linq but I assume this could be a solution:

var lstObjects = new List<object>();
var query = "Phase == {0}";
lstObjects.Add(Phase.Value);
for (int i = 1; i < Phase.Count; i++)
{
    query += string.Format(" || Phase == {0}", i);
}

context.myList.Where(query,lstObjects.ToList());

or

for (int i = 0; i < Phase.Count; i++)
{
    if (i > 0) { query+= " || "; }
    query += string.Format("Phase == {0}", lstObjects[i].Value);
}
context.MyList.Where(query);

Let me know if this works.

[/edit]


问:
How to increment a number within a variable name in jQuery
I have this javascript for loop:

```<code>for (var i=1; i <= 2; i++) {
   $(".afterglowplayer"+i).click(function () {$.afterglowplayer+i.toggle(this); return false;});
}
</code>```

I need to increment the number at the end of a jQuery variable name so that I get this:

```<code>$.afterglowplayer1.toggle(this);
$.afterglowplayer2.toggle(this);
</code>```

I have tried using

```<code>$.afterglowplayer+i.toggle(this);
</code>```

and

```<code>$.afterglowplayer+"+i+".toggle(this);
</code>```

But it is not correct way... is it possible to increment the number at the end of a jQuery variable name?

答:
Read up on JavaScript closures.

for (var i=1; i <= 2; i++) {
  (function(n) {
    $('.afterglowplayer'+n).click(function () {
      $('.afterglowplayer'+n).toggle(this); return false;
    });
  })(i);
}
```

Body:
I have this javascript for loop:

for (var i=1; i <= 2; i++) {
   $(".afterglowplayer"+i).click(function () {$.afterglowplayer+i.toggle(this); return false;});
}

I need to increment the number at the end of a jQuery variable name so that I get this:

$.afterglowplayer1.toggle(this);
$.afterglowplayer2.toggle(this);

I have tried using

$.afterglowplayer+i.toggle(this);

and

$.afterglowplayer+"+i+".toggle(this);

But it is not correct way... is it possible to increment the number at the end of a jQuery variable name?


问:
Ghostscript command for finding the number of colors used for each page in pdf file
I'm new to GhostScript. Can you let me know the Ghostscript command for finding the number of colors used for each page in pdf file. I need to parse the results of this command from java program</p>

答:
There is no such Ghostscript command or device. It would also be difficult to figure out; so much depends on what you mean. Do you intend to count the colour of each pixel in every image for example ? Which colour spaces are you interested in ? What about ICCBased colour spaces, do you want the component values, or the CIE values ?

[edit]

Yeah there's no Ghostscript equivalent, I did say that.

You wuold have to intercept every call to the colour operators, examine the components being supplied and see if they were no black and white. For example, if you set a CMYK colour with C=M=Y=0 and K!=0 then its still black and white. Similar arguments apply for RGB, CIE and ICC colour spaces.

Now I bet ImageMagick doesn't do that, I suspect it simply uses Ghostscript to render a bitmap (probably RGB) and then counts the number of pixels of each colour in the output. Image manipulation tools pretty much all have to have a way to do that counting already, so its a low cost for them.

Its also wrong.

It doesn't tell you anything about the original colour. If you render a colour object to a colour space that is different to the one it was specified in, then the rendering engine has to convert it from the colour space it was in, to the expected one. This often leads to colour shifts, especially when converting from RGB to CMYK but any conversion will potentially have this problem.

So if this is what ImageMagick is doing, its inaccurate at best. It is possible to write PostScript to do this accurately, with some effort, but exactly what counts as 'colour' and 'black and white' is still a problem. You haven't said why you want to know if an input file is 'black and white' (you also haven't said if gray counts as black and white, its not the same thing)

I'm guessing you intend to either charge more for colour printing, or need to divert colour input to a different printer. In which case you do need to know if the PDF uses (eg) R=G=B=1 for black, because that often will not result in C=M=Y=0 K=1 when rendered to the printer. Not only that, but the exact colour produced may not even be the same from one printer to another (colour conversion is device-dependent), so just because Ghostscript produced pure black doesn't mean that another printer would.

This is not a simple subject.


问:
Swashbuckle.AspNetCore only generating models with fields of type string
So I have a group model like this:

```<code>public class GroupDTO {
    [Required]
    public Guid? Id { get; set; }

    [Required(AllowEmptyStrings = false)]
    [StringLength(maximumLength: 50)]
    public string Name { get; set; }
}
</code>```

But the generated model by swagger looks like this:

```<code>[
  {
    "id": "string",
    "name": "string"
  }
]
</code>```

It should look something like this:

```<code>[
  {
    "id": "00000000-0000-0000-0000-000000000000",
    "name": "string"
  }
]
</code>```

Anyone got an idea?

答: You can use https://github.com/mattfrear/Swashbuckle.Examples to add examples to your swagger calls that have valid values.</p>

Body:
So I have a group model like this:

public class GroupDTO {
    [Required]
    public Guid? Id { get; set; }

    [Required(AllowEmptyStrings = false)]
    [StringLength(maximumLength: 50)]
    public string Name { get; set; }
}

But the generated model by swagger looks like this:

[
  {
    "id": "string",
    "name": "string"
  }
]

It should look something like this:

[
  {
    "id": "00000000-0000-0000-0000-000000000000",
    "name": "string"
  }
]

Anyone got an idea?


问:
django inline formset inside a modal - delete field
I am creating an edit view inside a modal. My view consists of a regular django form and inline formset. I have used django-dynamic-formsets for adding and deleting new formsets and this is where I have a problem. When formset is displayed inside a modal, the "remove" field is blank and I cannot delete a formset.  For a quick example I'm using Daniel Chen's "Django Inline formsets example: mybook".

my html:

```<code><button id="myBtn">Open Modal</button>
<div id="myModal" class="modal">

<div class="modal-content">
    <span class="close">×</span>
    <div class="col-md-4">
        <form action="" method="post">{% csrf_token %}
            {{ form.as_p }}
            <table class="table">
                {{ familymembers.management_form }}

                <thead>
                    <th>One</th>
                    <th>Two</th>
                    <th>Three</th>
                    <th></th>
                    <th><i class="glyphicon glyphicon-remove"></i></th>
                </thead>
                <tbody>
                    {% for form in familymembers.forms %}
                    <tr class="{% cycle row1 row2 %} formset_row">
                        {% for field in form.visible_fields %}
                        <td>
                            {% if forloop.first %}
                                {% for hidden in form.hidden_fields %}
                                    {{ hidden }}
                                {% endfor %}
                            {% endif %}
                            {{ field.errors.as_ul }}
                            {{ field }}
                        </td>
                        {% endfor %}
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
            <input type="submit" value="Save"/> <a href="{% url 'profile-list' %}">back to the list</a>
        </form>
    </div>
</div>
</div>
</code>```

my js:

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script>
    $('.formset_row').formset({
        addText: 'add formset',
        prefix: 'familymember_set'
    });
    var modal = document.getElementById('myModal');
    var btn = document.getElementById("myBtn");
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks on the button, open the modal
    btn.onclick = function() {
        modal.style.display = "block";
    }
    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }

    $('.myModal').click(function() {
        $('body').css('overflow', 'hidden');
    });
</script>
</code>```

答:
I have the same issue, and what works for me was modified a little bit the jquery.formset.js javascript file, on the line 139, just pass the call to insertDeleteLink(row) outside of the if sentence, like this</p>

```<code> insertDeleteLink(row);
 if (row.is(':visible')) {
    applyExtraClasses(row, i);
 }
</code>```

Body:
I am creating an edit view inside a modal. My view consists of a regular django form and inline formset. I have used django-dynamic-formsets for adding and deleting new formsets and this is where I have a problem. When formset is displayed inside a modal, the "remove" field is blank and I cannot delete a formset.  For a quick example I'm using Daniel Chen's "Django Inline formsets example: mybook".

my html:

<button id="myBtn">Open Modal</button>

    ×

        <form action="" method="post">{% csrf_token %}
            {{ form.as_p }}

                {{ familymembers.management_form }}

                    One
                    Two
                    Three

                    {% for form in familymembers.forms %}

                        {% for field in form.visible_fields %}

                            {% if forloop.first %}
                                {% for hidden in form.hidden_fields %}
                                    {{ hidden }}
                                {% endfor %}
                            {% endif %}
                            {{ field.errors.as_ul }}
                            {{ field }}

                        {% endfor %}

                    {% endfor %}

            <input type="submit" value="Save"/> back to the list
        </form>

my js:

Body:
I have the same issue, and what works for me was modified a little bit the jquery.formset.js javascript file, on the line 139, just pass the call to insertDeleteLink(row) outside of the if sentence, like this

 insertDeleteLink(row);
 if (row.is(':visible')) {
    applyExtraClasses(row, i);
 }


问:
Update SQL query in SQL Server
I have an issue where I need to update a field in a number of SQL Server tables.  The customer Order ID needs to be updated on all records that do not follow the standard format "C000001" (a letter followed by numbers). There are approximately 300 records that need changed (carry over records from a previous database version), as well as the corresponding linked tables.

I am a bit rusty on my SQL, so would like to verify the commands.

My proposed commands

```<code>UPDATE Customer_Order
SET ID = CONCAT('X', ID)
WHERE ID not like 'c%';

UPDATE Customer_Order_Line
SET Cust_Order_ID = CONCAT('X', Cust_Order_ID)
WHERE Cust_Order_ID not like 'c%';

UPDATE Quote_Order
SET Cust_Order_ID = CONCAT('X', Cust_Order_ID)
WHERE Cust_Order_ID not like 'c%';
</code>```

etc... (I have approx 12 additional tables to update same as above)

Assistance is appreciated, thanks in advance.

答:
More of a formatted comment here..

Any time you want to do this, just make your update a select to verify your update:

```<code>SELECT ID, CONCAT('X', ID) as NewID
FROM Customer_Order
WHERE ID not like 'c%'
</code>```

Make sure the NewID column is what you want to replace ID with.

Title: Update SQL query in SQL Server

Body:
I have an issue where I need to update a field in a number of SQL Server tables.  The customer Order ID needs to be updated on all records that do not follow the standard format "C000001" (a letter followed by numbers). There are approximately 300 records that need changed (carry over records from a previous database version), as well as the corresponding linked tables.

I am a bit rusty on my SQL, so would like to verify the commands.

My proposed commands

UPDATE Customer_Order
SET ID = CONCAT('X', ID)
WHERE ID not like 'c%';

UPDATE Customer_Order_Line
SET Cust_Order_ID = CONCAT('X', Cust_Order_ID)
WHERE Cust_Order_ID not like 'c%';

UPDATE Quote_Order
SET Cust_Order_ID = CONCAT('X', Cust_Order_ID)
WHERE Cust_Order_ID not like 'c%';

etc... (I have approx 12 additional tables to update same as above)

Assistance is appreciated, thanks in advance.

Body:
More of a formatted comment here..

Any time you want to do this, just make your update a select to verify your update:

SELECT ID, CONCAT('X', ID) as NewID
FROM Customer_Order
WHERE ID not like 'c%'

Make sure the NewID column is what you want to replace ID with.


问:
opening URLConnection with a particular web resource
I am not able to open a URLConnection with a particular web resource . I am getting

" java.net.ConnectException: Connection timed out:"  .  Is it because of that domain is blocking the direct URL connection ? If so how they are blocking this ?  below is the code snippet i wrote .

Code snippet:

import java.io.;
import java.net.;

public class TestFileRead{

```<code>public static void main(String args[]){

    try{

        String serviceUrl = "http://xyz.com/examples.zip";
        HttpURLConnection serviceConnection = (HttpURLConnection) new URL(serviceUrl).openConnection();
        System.out.println(serviceConnection);
        serviceConnection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)");

        DataInputStream din=new DataInputStream(serviceConnection.getInputStream());
        FileOutputStream fout=new FileOutputStream("downloaded");
        DataOutputStream dout=new DataOutputStream(fout);
        int bytes;
        while(din.available()>0){
            bytes=din.readByte();
            dout.write(bytes);
        }
    }catch(Exception ex){
        ex.printStackTrace();
    }

}
</code>```

}

答:
Try this, it works fine for me, returning the index page.</p>

```<code>String serviceUrl = "http://yahoo.com";
HttpURLConnection serviceConnection = (HttpURLConnection) new URL(serviceUrl).openConnection();
serviceConnection.addRequestProperty("User-Agent", "blah"); //some sites deny access to some pages when User-Agent is Java
BufferedReader in = new BufferedReader(new InputStreamReader(serviceConnection.getInputStream()));
</code>```

Body:
I am not able to open a URLConnection with a particular web resource . I am getting

" java.net.ConnectException: Connection timed out:"  .  Is it because of that domain is blocking the direct URL connection ? If so how they are blocking this ?  below is the code snippet i wrote .

Code snippet:

import java.io.;
import java.net.;

public class TestFileRead{

public static void main(String args[]){

    try{

        String serviceUrl = "http://xyz.com/examples.zip";
        HttpURLConnection serviceConnection = (HttpURLConnection) new URL(serviceUrl).openConnection();
        System.out.println(serviceConnection);
        serviceConnection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)");

        DataInputStream din=new DataInputStream(serviceConnection.getInputStream());
        FileOutputStream fout=new FileOutputStream("downloaded");
        DataOutputStream dout=new DataOutputStream(fout);
        int bytes;
        while(din.available()>0){
            bytes=din.readByte();
            dout.write(bytes);
        }
    }catch(Exception ex){
        ex.printStackTrace();
    }

}

}

Body:
Try this, it works fine for me, returning the index page.

String serviceUrl = "http://yahoo.com";
HttpURLConnection serviceConnection = (HttpURLConnection) new URL(serviceUrl).openConnection();
serviceConnection.addRequestProperty("User-Agent", "blah"); //some sites deny access to some pages when User-Agent is Java
BufferedReader in = new BufferedReader(new InputStreamReader(serviceConnection.getInputStream()));


问:
numpy linear algebra on diagonal arrays without explicit duplication
I have an array w (shape (3000, 100, 100)) which I want to multiply with another array e (shape (5, 3000)) such that the result k has shape (5, 5, 100, 100) and

```<code>k[:, :, i, j] = e @ np.diag(w[:, i, j]) @ e.T
</code>```

Since w is so large, it's not practical to make some super_w array with shape (3000, 3000, 100, 100) and explicitly populate the main diagonal. It is also not terribly efficient to loop over i and j. Is there a memory-efficient way to do this, other than breaking up w into chunks?

答:
With np.einsum -

```<code>k = np.einsum('li,ijk,mi->lmjk',e,w,e)
</code>```

Body:
I have an array w (shape (3000, 100, 100)) which I want to multiply with another array e (shape (5, 3000)) such that the result k has shape (5, 5, 100, 100) and

k[:, :, i, j] = e @ np.diag(w[:, i, j]) @ e.T

Since w is so large, it's not practical to make some super_w array with shape (3000, 3000, 100, 100) and explicitly populate the main diagonal. It is also not terribly efficient to loop over i and j. Is there a memory-efficient way to do this, other than breaking up w into chunks?

Body:
With np.einsum -

k = np.einsum('li,ijk,mi->lmjk',e,w,e)


问:
Combine rows and remove NA's
I have a data frame like this:

```<code>idx  type  val1 val2 val3 val4 val5 val6
1    a     0.2   NA   NA   NA   NA   NA
2    a     0.3   NA   NA   NA   NA   NA
3    a     0.2   NA   NA   NA   NA   NA
4    a     NA    0.3  NA   NA   NA   NA
5    a     NA    0.5  NA   NA   NA   NA
6    a     NA    0.2  NA   NA   NA   NA
7    a     NA    NA   0.2  NA   NA   NA
8    a     NA    NA   0.5  NA   NA   NA
9    a     NA    NA   0.4  NA   NA   NA
10   a     NA    NA   NA   0.4  NA   NA
11   a     NA    NA   NA   0.6  NA   NA
12   a     NA    NA   NA   0.6  NA   NA
.
.
.
34   b     NA    NA   NA   NA   NA   0.6
35   b     NA    NA   NA   NA   NA   0.4
36   b     NA    NA   NA   NA   NA   0.3
</code>```

I want to combine the rows and remove the NA's. So this is what I want to achieve:

```<code>idx  type  val1 val2 val3 val4 val5 val6
1    a     0.2  0.3  0.2  0.4  0.3  0.2
2    a     0.3  0.5  0.5  0.6  0.4  0.5
3    a     0.2  0.2  0.4  0.6  0.5  0.6
4    b     0.4  0.2  0.2  0.5  0.4  0.6
5    b     0.3  0.5  0.6  0.3  0.6  0.4
6    b     0.3  0.4  0.3  0.6  0.5  0.3
</code>```

答:
You might just want to apply a function to each of the columns of interest and then cbind it to the category column filtered:</p>

```<code>test.df = data.frame(cat = rep(c('a','b'), each=3),x1=c(1,NA,NA,5.5,NA,NA),
                     x2=c(NA,2,NA,NA,4.5,NA),
                     x3=c(NA,NA,3.,NA,NA,3.5))

collapse_column <- function(data, col){
  data[!is.na(data[,col]),col]
}

main_vals = sapply(2:4,collapse_column, data=test.df)

cat_vals = test.df[!is.na(test.df[,2]),'cat']

new_df = as.data.frame(cbind(cat_vals, main_vals))
names(new_df) = names(test.df)
</code>```

Title: Combine rows and remove NA's

Body:
I have a data frame like this:

idx  type  val1 val2 val3 val4 val5 val6
1    a     0.2   NA   NA   NA   NA   NA
2    a     0.3   NA   NA   NA   NA   NA
3    a     0.2   NA   NA   NA   NA   NA
4    a     NA    0.3  NA   NA   NA   NA
5    a     NA    0.5  NA   NA   NA   NA
6    a     NA    0.2  NA   NA   NA   NA
7    a     NA    NA   0.2  NA   NA   NA
8    a     NA    NA   0.5  NA   NA   NA
9    a     NA    NA   0.4  NA   NA   NA
10   a     NA    NA   NA   0.4  NA   NA
11   a     NA    NA   NA   0.6  NA   NA
12   a     NA    NA   NA   0.6  NA   NA
.
.
.
34   b     NA    NA   NA   NA   NA   0.6
35   b     NA    NA   NA   NA   NA   0.4
36   b     NA    NA   NA   NA   NA   0.3

I want to combine the rows and remove the NA's. So this is what I want to achieve:

idx  type  val1 val2 val3 val4 val5 val6
1    a     0.2  0.3  0.2  0.4  0.3  0.2
2    a     0.3  0.5  0.5  0.6  0.4  0.5
3    a     0.2  0.2  0.4  0.6  0.5  0.6
4    b     0.4  0.2  0.2  0.5  0.4  0.6
5    b     0.3  0.5  0.6  0.3  0.6  0.4
6    b     0.3  0.4  0.3  0.6  0.5  0.3

Body:
You might just want to apply a function to each of the columns of interest and then cbind it to the category column filtered:

test.df = data.frame(cat = rep(c('a','b'), each=3),x1=c(1,NA,NA,5.5,NA,NA),
                     x2=c(NA,2,NA,NA,4.5,NA),
                     x3=c(NA,NA,3.,NA,NA,3.5))

collapse_column <- function(data, col){
  data[!is.na(data[,col]),col]
}

main_vals = sapply(2:4,collapse_column, data=test.df)

cat_vals = test.df[!is.na(test.df[,2]),'cat']

new_df = as.data.frame(cbind(cat_vals, main_vals))
names(new_df) = names(test.df)


问:
How to create Three-Line Listview Items?
I have three-line items on my Listview ( like this one ), but I want to change it like this other. What I want to do is to have this "--" divider between the subheader (the black one) and the complementary text (the grayish one), and I want the complementary text to be in the second and third line.

This is the code I'm using for my items (doesn't include avatar's code)

```<code><TextView
        android:id="@+id/txtNombrePDV"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="La bendición"
        android:textColor="@color/colorPrimaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_primary_text" />

    <TextView
        android:id="@+id/txtNombreMunicipio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stack Overflow"
        android:textColor="@color/colorPrimaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_secondary_text"
        />

    <TextView
        android:id="@+id/txtDireccion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit"
        android:textColor="@color/colorSecondaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_secondary_text"
        />
</LinearLayout>
</code>```

答:
your layout should go like this.

```<code><RelativeLayout
        android:padding="8dp"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_weight="1"
            android:textSize="18dp"
            android:textColor="@color/subHead"
            android:layout_marginRight="8dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"/>

        <TextView
            android:layout_below="@+id/tvTitle"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Subhead"
            android:textSize="20sp"
            android:layout_marginTop="8dp"
            android:id="@+id/subHeader"
            android:textColor="@color/colorText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </RelativeLayout>
</code>```

and java code should look like below.

```<code> @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    int color = ContextCompat.getColor(this,R.color.subHead);
    String title = "Brunch this weekend?";
    String name = "Ali Connors";
    String message = "I will be in weekends so get set ready. Will meet you yesterday";
    String subTitle = name+" - "+message;
    SpannableString spannableString = new SpannableString(subTitle);
    spannableString.setSpan(new ForegroundColorSpan(color),0,name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    TextView subTitleTextView = findViewById(R.id.subHeader);
    TextView titleTextView = findViewById(R.id.tvTitle);
    subTitleTextView.setText(spannableString);
    titleTextView.setText(title);
}
</code>```

colors

```<code>  <color name="subHead">#252525</color>
    <color name="colorText">#797979</color>
</code>```

Body:
I have three-line items on my Listview ( like this one ), but I want to change it like this other. What I want to do is to have this "--" divider between the subheader (the black one) and the complementary text (the grayish one), and I want the complementary text to be in the second and third line.

This is the code I'm using for my items (doesn't include avatar's code)

<TextView
        android:id="@+id/txtNombrePDV"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="La bendición"
        android:textColor="@color/colorPrimaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_primary_text" />

    <TextView
        android:id="@+id/txtNombreMunicipio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stack Overflow"
        android:textColor="@color/colorPrimaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_secondary_text"
        />

    <TextView
        android:id="@+id/txtDireccion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit"
        android:textColor="@color/colorSecondaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_secondary_text"
        />
</LinearLayout>

Body:
your layout should go like this.

<RelativeLayout
        android:padding="8dp"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_weight="1"
            android:textSize="18dp"
            android:textColor="@color/subHead"
            android:layout_marginRight="8dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"/>

        <TextView
            android:layout_below="@+id/tvTitle"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Subhead"
            android:textSize="20sp"
            android:layout_marginTop="8dp"
            android:id="@+id/subHeader"
            android:textColor="@color/colorText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </RelativeLayout>

and java code should look like below.

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    int color = ContextCompat.getColor(this,R.color.subHead);
    String title = "Brunch this weekend?";
    String name = "Ali Connors";
    String message = "I will be in weekends so get set ready. Will meet you yesterday";
    String subTitle = name+" - "+message;
    SpannableString spannableString = new SpannableString(subTitle);
    spannableString.setSpan(new ForegroundColorSpan(color),0,name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    TextView subTitleTextView = findViewById(R.id.subHeader);
    TextView titleTextView = findViewById(R.id.tvTitle);
    subTitleTextView.setText(spannableString);
    titleTextView.setText(title);
}

colors

  <color name="subHead">#252525</color>
    <color name="colorText">#797979</color>


问:
Add border to each page when printing without any border breaks
I have a project, which I will need to print a multi page exam.

I want to have border on each page, but at the bottom and at the top, when page breaks, the border will break too!

SCREENSHOT OF AN EXAMPLE

I am using @media print to style the print page

Code Structure of the page is:

```<code>header
main-content{
--- div for each question
}
</code>```

each question has a border bottom, and the main-content has a full border

So any Idea on who can I achieve this goal?

Note: I am aware of the break-after or break-before properties, and they're no use in this case

答:
Not sure why you would want that space below a page on a print.  When you print a page, it is going to look really bad if you have a grey border at the bottom of each printed page. It would make sense to put the border on screen and when you print remove the borders.

I Would say you can just make the bottom border thicker.

```<code>@media print{
  .main-content{
     border-bottom 5px solid grey;
  }
}
</code>```

Either that, or make the background color grey like on the picture and add margin below the main-content div to space the pages from each other.

Keep in mind that Background color and border color does not always show up on print.  It depends on the browser and the printer settings.

Body:
I have a project, which I will need to print a multi page exam.

I want to have border on each page, but at the bottom and at the top, when page breaks, the border will break too!

SCREENSHOT OF AN EXAMPLE

I am using @media print to style the print page

Code Structure of the page is:

header
main-content{
--- div for each question
}

each question has a border bottom, and the main-content has a full border

So any Idea on who can I achieve this goal?

Note: I am aware of the break-after or break-before properties, and they're no use in this case

Body:
Not sure why you would want that space below a page on a print.  When you print a page, it is going to look really bad if you have a grey border at the bottom of each printed page. It would make sense to put the border on screen and when you print remove the borders.

I Would say you can just make the bottom border thicker.

@media print{
  .main-content{
     border-bottom 5px solid grey;
  }
}

Either that, or make the background color grey like on the picture and add margin below the main-content div to space the pages from each other.

Keep in mind that Background color and border color does not always show up on print.  It depends on the browser and the printer settings.


问:
Convert integers inside a list into strings and then a date in python 3.x
i've just started studying python in college and i have a problem with this exercise:
basically i have to take a list of integers, like for example [10,2,2013,11,2,2014,5,23,2015], turn the necessary elements to form a date into a string, like ['1022013',1122014,5232015] and then put a / between the strings so i have this ['10/2/2013', '11/22/2014','05/23/2015']. It needs to be a function, and the length of the list is assumed to be a multiple of 3. How do i go about doing this?
I wrote this code to start:

```<code>def convert(lst):
     ...:     for element in lst:
     ...:      result = str(element)
     ...:      return result
     ...:
</code>```

but from a list [1,2,3] only returns me '1'.

答:
Something like this would work:

```<code>def convert(lst):
    string = ''
    new_lst = []
    for x in lst:
        if len(str(x)) < 4:
            string += str(x)+'/'
        else:
            string += str(x)
            new_lst.append(string)
            string = ''
    return(new_lst)

lst = [10,2,2013,11,2,2014,5,23,2015]

lst = convert(lst)

print(lst)

#output
['10/2/2013', '11/2/2014', '5/23/2015']
</code>```

So create a placeholder string and a new list. Then loop through each element in your list. If the element is not a year, then add it to the string with a '/'. If it is a year, add the string to the new list and clear the string.

Body:
i've just started studying python in college and i have a problem with this exercise:
basically i have to take a list of integers, like for example [10,2,2013,11,2,2014,5,23,2015], turn the necessary elements to form a date into a string, like ['1022013',1122014,5232015] and then put a / between the strings so i have this ['10/2/2013', '11/22/2014','05/23/2015']. It needs to be a function, and the length of the list is assumed to be a multiple of 3. How do i go about doing this?
I wrote this code to start:

def convert(lst):
     ...:     for element in lst:
     ...:      result = str(element)
     ...:      return result
     ...:

but from a list [1,2,3] only returns me '1'.

Body:
Something like this would work:

def convert(lst):
    string = ''
    new_lst = []
    for x in lst:
        if len(str(x)) < 4:
            string += str(x)+'/'
        else:
            string += str(x)
            new_lst.append(string)
            string = ''
    return(new_lst)

lst = [10,2,2013,11,2,2014,5,23,2015]

lst = convert(lst)

print(lst)

#output
['10/2/2013', '11/2/2014', '5/23/2015']

So create a placeholder string and a new list. Then loop through each element in your list. If the element is not a year, then add it to the string with a '/'. If it is a year, add the string to the new list and clear the string.


问:
Decorators and globals
The application has a module, A, which contains a decorator which adds functions to a list which is a module-level global in A.  The list of functions is used in other functions within the module.

A.py

```<code>import functools

things = []

def register(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        things.append(func)
        return func
    return inner

@register
def foo():pass

@register
def bar():pass

foo()
bar()

print(things)
</code>```

This pattern has been copied in other parts of the application, so a number of modules contain the register function and the module level list.

I want to reduce the amount of duplication by having A.register implemented in a single location, but modules that import need to have their own local list of functions.

I tried importing A and creating a providing a list:

B.py

```<code>import A

things = []

@A.register
def baz():pass

@A.register
def quux():pass

baz()
quux()

print(things)
</code>```

But all the functions are registered in A.things:

```<code>>>> import A
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>]
>>> import B
[]
>>> print A.things
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>, <function baz at 0x7f3ecdf46410>, <function quux at 0x7f3ecdf469b0>]
</code>```

Is there a way to have single implementation of A.register, but to have it populate a list in the modules in which it's imported?  That is

```<code>>>> print A.things
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>]

>>> print B.things
[<function baz at 0x7f3ecdf46410>, <function quux at 0x7f3ecdf469b0>]
</code>```

答:
You do have a single implementation of register() function in module A.

You do not have variable things in module B, it [variable] belongs to module A only.

Even if you use decorator in module B, it is the variable things in module A that will be appended.

Another very important point to remember is that variable things will get appended every time functions are called.

If you can not change algorithm declare variable things in every module and create a decorator like this:

(code from ryachza)

```<code>def register(things=things):
    def _register(func):
        @functools.wraps(func)
        def inner(*args, **kwargs):
            things.append(func)
            return func

        return inner

    return _register
</code>```

However, that is not the way to use decorators.

You can create a variable things in every module and append it like this. You do not have to use decorators for this.

```<code>things = []

def foo():
    pass

things.append(foo)

def bar():
    pass

things.append(bar)

foo()
bar()

print(things)
</code>```

Title: Decorators and globals

Body:
The application has a module, A, which contains a decorator which adds functions to a list which is a module-level global in A.  The list of functions is used in other functions within the module.

A.py

import functools

things = []

def register(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        things.append(func)
        return func
    return inner

@register
def foo():pass

@register
def bar():pass

foo()
bar()

print(things)

This pattern has been copied in other parts of the application, so a number of modules contain the register function and the module level list.

I want to reduce the amount of duplication by having A.register implemented in a single location, but modules that import need to have their own local list of functions.

I tried importing A and creating a providing a list:

B.py

import A

things = []

@A.register
def baz():pass

@A.register
def quux():pass

baz()
quux()

print(things)

But all the functions are registered in A.things:

>>> import A
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>]
>>> import B
[]
>>> print A.things
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>, <function baz at 0x7f3ecdf46410>, <function quux at 0x7f3ecdf469b0>]

Is there a way to have single implementation of A.register, but to have it populate a list in the modules in which it's imported?  That is

>>> print A.things
[<function foo at 0x7f3ecdf466e0>, <function bar at 0x7f3ecdf467d0>]

>>> print B.things
[<function baz at 0x7f3ecdf46410>, <function quux at 0x7f3ecdf469b0>]

Body:
You do have a single implementation of register() function in module A.

You do not have variable things in module B, it [variable] belongs to module A only.

Even if you use decorator in module B, it is the variable things in module A that will be appended.

Another very important point to remember is that variable things will get appended every time functions are called.

If you can not change algorithm declare variable things in every module and create a decorator like this:

(code from ryachza)

def register(things=things):
    def _register(func):
        @functools.wraps(func)
        def inner(*args, **kwargs):
            things.append(func)
            return func

        return inner

    return _register

However, that is not the way to use decorators.

You can create a variable things in every module and append it like this. You do not have to use decorators for this.

things = []

def foo():
    pass

things.append(foo)

def bar():
    pass

things.append(bar)

foo()
bar()

print(things)


问:
Little explanation about an using of ?? to assign values to a dictionary
Currently I'm following the nice book App Development with Swift and so far everything is explained awesome. Nevertheless following the exercises I found certain piece of code that I'd love to understand much better. I've already tried to look information everywhere but I don't even know what's the name or how to find it. So with no more to say, it's the following:

I have a dictionary:

```<code>var frequencyOfAnswers: [AnimalType: Int] = [:]
</code>```

AnymalType is simply an enum with four cases. Then they perform a mapping on frequencyOfAnswers:

```<code>let responseTypes = responses.map { $0.type }
</code>```

An so far everything is good. But in the following iteration:

```<code>for response in responseTypes {
    frequencyOfAnswers[response] = (frequencyOfAnswers[response]
    ?? 0) + 1
}
</code>```

I cannot comprehend totally the use of ??. I know that here the point is that if the new element is not already into the dictionary, then is gonna be added and it'll have a value of 1. And if it already exists, then its correspondent integer values is gonna increase by 1.

I'd like to have little more information about this syntax. If anyone of you guys could provide me with a good text, web page or explanation I'd be really thankful.

Thank you in advance.

答:
?? is the Nil-Coalescing Operator.

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

The nil-coalescing operator is shorthand for the code below:

```<code>a != nil ? a! : b
</code>```

It is used to define a default value for an Optional type that has no value. It is being used in your example to set the frequencyOfAnswers dictionary value to 0 for cases where the frequencyOfAnswers dictionary has no value for a given response type key.

Read more in the Nil-Coalescing Operator section of https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html

ContentLicense: CC BY-SA 4.0

Body:
Currently I'm following the nice book App Development with Swift and so far everything is explained awesome. Nevertheless following the exercises I found certain piece of code that I'd love to understand much better. I've already tried to look information everywhere but I don't even know what's the name or how to find it. So with no more to say, it's the following:

I have a dictionary:

var frequencyOfAnswers: [AnimalType: Int] = [:]

AnymalType is simply an enum with four cases. Then they perform a mapping on frequencyOfAnswers:

let responseTypes = responses.map { $0.type }

An so far everything is good. But in the following iteration:

for response in responseTypes {
    frequencyOfAnswers[response] = (frequencyOfAnswers[response]
    ?? 0) + 1
}

I cannot comprehend totally the use of ??. I know that here the point is that if the new element is not already into the dictionary, then is gonna be added and it'll have a value of 1. And if it already exists, then its correspondent integer values is gonna increase by 1.

I'd like to have little more information about this syntax. If anyone of you guys could provide me with a good text, web page or explanation I'd be really thankful.

Thank you in advance.

Body:
?? is the Nil-Coalescing Operator.

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

The nil-coalescing operator is shorthand for the code below:

a != nil ? a! : b

It is used to define a default value for an Optional type that has no value. It is being used in your example to set the frequencyOfAnswers dictionary value to 0 for cases where the frequencyOfAnswers dictionary has no value for a given response type key.

Read more in the Nil-Coalescing Operator section of https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html


问:
How to tokenize documents in R and list tokens by original document title?
I have data frame D containing a document title and the text as in the following example:

```<code>document   content
Doc 1      "This is an example of a document"
Doc 2      "And another one"
</code>```

I need to use the tokenize function from quanteda package in order to tokenize every document and then return the tokens listed by its original document title as in this example:

```<code>document   content
    Doc 1      "This"
    Doc 1      "This is"
    Doc 1      "This is an"
    Doc 1      "This is an example"
</code>```

This is my current process to obtain a data frame with tokens from a list of documents:

```<code>require(textreadr)
D<-textreadr::read_dir("myDir")
D<-paste(D$content,collapse=" ")
strlist<-paste0(c(":","\\)",":","'",";","!","+","&","<",">","\\(","\\[","\\]","-","#",","),collapse = "|")
D<-gsub(strlist, "", D)
library(quanteda)
require(quanteda)
t<-tokenize(D, what = c("word","sentence", "character","fastestword", "fasterword"),
            remove_numbers = FALSE, remove_punct = FALSE,
            remove_symbols = FALSE, remove_separators = TRUE,
            remove_twitter = FALSE, remove_hyphens = FALSE, remove_url = FALSE,
            ngrams = 1:10, concatenator = " ", hash = TRUE,
            verbose = quanteda_options("verbose"))
t<-unlist(t, use.names=FALSE)
t1<-data.frame(t)
</code>```

However, I can't find an easy way to keep the document names after the tokenization process and list the tokens accordingly. Could anyone help with this?

答:
R's list objects can take string indices like so:

```<code>my_list = list()

document_title = 'asdf.txt'
my_data = tokenize( etc... )
my_list[[document_title]] = my_data
</code>```

Use your existing code, but assign your final data frame to a list like:

```<code>my_list[[document_title]] = data.frame(t)
</code>```

Body:
I have data frame D containing a document title and the text as in the following example:

document   content
Doc 1      "This is an example of a document"
Doc 2      "And another one"

I need to use the tokenize function from quanteda package in order to tokenize every document and then return the tokens listed by its original document title as in this example:

document   content
    Doc 1      "This"
    Doc 1      "This is"
    Doc 1      "This is an"
    Doc 1      "This is an example"

This is my current process to obtain a data frame with tokens from a list of documents:

require(textreadr)
D<-textreadr::read_dir("myDir")
D<-paste(D$content,collapse=" ")
strlist<-paste0(c(":","\\)",":","'",";","!","+","&","<",">","\\(","\\[","\\]","-","#",","),collapse = "|")
D<-gsub(strlist, "", D)
library(quanteda)
require(quanteda)
t<-tokenize(D, what = c("word","sentence", "character","fastestword", "fasterword"),
            remove_numbers = FALSE, remove_punct = FALSE,
            remove_symbols = FALSE, remove_separators = TRUE,
            remove_twitter = FALSE, remove_hyphens = FALSE, remove_url = FALSE,
            ngrams = 1:10, concatenator = " ", hash = TRUE,
            verbose = quanteda_options("verbose"))
t<-unlist(t, use.names=FALSE)
t1<-data.frame(t)

However, I can't find an easy way to keep the document names after the tokenization process and list the tokens accordingly. Could anyone help with this?

Body:
R's list objects can take string indices like so:

my_list = list()

document_title = 'asdf.txt'
my_data = tokenize( etc... )
my_list[[document_title]] = my_data

Use your existing code, but assign your final data frame to a list like:

my_list[[document_title]] = data.frame(t)


问:
How to protect web client ID in GCP source code
My GAE app publishes some APIs in GCP and uses the following structure:

```<code># Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '????????????.apps.googleusercontent.com'

ALLOWED_CLIENT_IDS = [WEB_CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID]
SCOPES = [endpoints.EMAIL_SCOPE]

@endpoints.api(name=API_NAME,
               version=API_VERSION,
               description='An API to manage languages',
               allowed_client_ids=ALLOWED_CLIENT_IDS,
               scopes=SCOPES)
</code>```

My doubt is if someone picks this source code from my machine or GitHub project. He or she can access the APIs using the discovered web client id.

What’s the best practice in this case?

I acknowledge that the client can expose the ID and someone have access to it. But I believe that is another matter.

答: There are many ways you can do this. One way is to always check in a default value for the client ID, so that when people check out your code, they have to modify it to deploy it. You can also move the client ID to its own module and not check it in at all, and make the expectation that they create their own module with their own client ID. This avoids having a modified state for a checked in file all of the time.</p>

Body:
My GAE app publishes some APIs in GCP and uses the following structure:

# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '????????????.apps.googleusercontent.com'

ALLOWED_CLIENT_IDS = [WEB_CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID]
SCOPES = [endpoints.EMAIL_SCOPE]

@endpoints.api(name=API_NAME,
               version=API_VERSION,
               description='An API to manage languages',
               allowed_client_ids=ALLOWED_CLIENT_IDS,
               scopes=SCOPES)

My doubt is if someone picks this source code from my machine or GitHub project. He or she can access the APIs using the discovered web client id.

What’s the best practice in this case?

I acknowledge that the client can expose the ID and someone have access to it. But I believe that is another matter.


答:
Not identical but perhaps satisfactory, you could define register like:

```<code>def register(things=things):
  def _register(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
      things.append(func)
      return func
    return inner
  return _register
</code>```

Used in A like:

```<code>@register()
def foo():pass

@register()
def bar():pass
</code>```

And in B like:

```<code>@A.register(things)
def baz():pass

@A.register(things)
def quux():pass
</code>```

And if needed, even something like:

```<code>@A.register(A.things)
def whatever():pass
</code>```

Title: Decorators and globals

Body:
Not identical but perhaps satisfactory, you could define register like:

def register(things=things):
  def _register(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
      things.append(func)
      return func
    return inner
  return _register

Used in A like:

@register()
def foo():pass

@register()
def bar():pass

And in B like:

@A.register(things)
def baz():pass

@A.register(things)
def quux():pass

And if needed, even something like:

@A.register(A.things)
def whatever():pass


问:
Vertically align an input placeholder with CSS (or set line-height)
Is it possible to vertically align a placeholder independently of the parent input? There seems to be no way to have the placeholder in the code below appear in the vertical center of the input field. I've tried all css properties and workarounds I can think of or find online but the different font sizes on the input and the placeholder seem to make it impossible in webkit browsers at least.

Edit: Left is the issue, right is the desired look:

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  font-size: 9px;
  text-transform: uppercase;
  color: #AAA;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type='text' placeholder='enter some text' /></code>```

答:
The best solution out there might be to simply add a translate3d transform to the placeholder CSS rule as follows:

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  font-size: 9px;
  text-transform: uppercase;
  color: #AAA;
  transform:translate3d(0,-4px,0)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type='text' placeholder='enter some text' /></code>```

Body:
Is it possible to vertically align a placeholder independently of the parent input? There seems to be no way to have the placeholder in the code below appear in the vertical center of the input field. I've tried all css properties and workarounds I can think of or find online but the different font sizes on the input and the placeholder seem to make it impossible in webkit browsers at least.

Edit: Left is the issue, right is the desired look:

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  font-size: 9px;
  text-transform: uppercase;
  color: #AAA;
}

<input type='text' placeholder='enter some text' />

Body:
The best solution out there might be to simply add a translate3d transform to the placeholder CSS rule as follows:

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  font-size: 9px;
  text-transform: uppercase;
  color: #AAA;
  transform:translate3d(0,-4px,0)
}

<input type='text' placeholder='enter some text' />


问:
Onclick event on dynamically inserted elements doesn't trigger
When I insert the following code by JavaScript into my HTML then the onclick event doesn't work (load_menu doesn't run). But when I insert this code manually it works.

```<code><li class="dropdown">
    <a href="#" onclick="load_menu('dropdown-menu',10001)" data-toggle="dropdown">رباتیک<i class="icon-arrow open"></i></a>
    <ul class="dropdown-menu show" id="10001">
    </ul>
</li>
</code>```

Javascript code:

```<code>function load_menu(m,id) {
    var t = 1000;
    if (m == 'dropdown') {
        if ($('div.container ul li[class="dropdown"]').length == 0) {
            loadXMLDoc("GET", "ContainerMenu.aspx?m=" + m + "&id=" + id, function (result) {
                document.getElementById(id).innerHTML = result;

                toggle_menu();
            });

        }
    }
    if (m == 'dropdown-menu') {
        if ($('div.container ul li ul[class="dropdown-menu"]').length == 0) {
            loadXMLDoc("GET", "ContainerMenu.aspx?m=" + m + "&id=" + id, function (result) {
                document.getElementById(id).innerHTML = result;

                toggle_menu();
            });

        }
    }
}
</code>```

Why does this happen and how can I fix it?

答:
I faced this issue when the onclick on html elements created in code would not trigger. In the below sample code the button created in code shows up but nothing happens when it is clicked

```<code><html>
<head>
<script language="javascript">
   alert("page is loading");
   function createbuttonincode() {
      var div=document.getElementById("testdiv");
      var button = document.createElement("button");
      var buttononclickstring = "javacript:testbuttonclick()";
      button.setAttribute ("onclick",  buttononclickstring);
      button.innerHTML = "button created by code";
      div.appendChild(button);
   }
   function testbuttonclick()
   {
       alert("button click event fired");
   }
</script>
</head>
<body>
<form>
   <input type=button onclick="javascript:createbuttonincode()"  value="Create new button"/>
<div id="testdiv"></div>
</form>
</body>
</code>```

But if I add this meta tag

```<code><meta http-equiv="X-UA-Compatible" content="IE=edge">
</code>```

in the head then the click event on the dynamically created event fires and I see the alert.

Seems like this is not an issue for Edge browser

Body:
When I insert the following code by JavaScript into my HTML then the onclick event doesn't work (load_menu doesn't run). But when I insert this code manually it works.

    رباتیک

Javascript code:

function load_menu(m,id) {
    var t = 1000;
    if (m == 'dropdown') {
        if ($('div.container ul li[class="dropdown"]').length == 0) {
            loadXMLDoc("GET", "ContainerMenu.aspx?m=" + m + "&id=" + id, function (result) {
                document.getElementById(id).innerHTML = result;

                toggle_menu();
            });

        }
    }
    if (m == 'dropdown-menu') {
        if ($('div.container ul li ul[class="dropdown-menu"]').length == 0) {
            loadXMLDoc("GET", "ContainerMenu.aspx?m=" + m + "&id=" + id, function (result) {
                document.getElementById(id).innerHTML = result;

                toggle_menu();
            });

        }
    }
}

Why does this happen and how can I fix it?

Body:
I faced this issue when the onclick on html elements created in code would not trigger. In the below sample code the button created in code shows up but nothing happens when it is clicked

<html>
<head>
<script language="javascript">
   alert("page is loading");
   function createbuttonincode() {
      var div=document.getElementById("testdiv");
      var button = document.createElement("button");
      var buttononclickstring = "javacript:testbuttonclick()";
      button.setAttribute ("onclick",  buttononclickstring);
      button.innerHTML = "button created by code";
      div.appendChild(button);
   }
   function testbuttonclick()
   {
       alert("button click event fired");
   }
</script>
</head>
<body>
<form>
   <input type=button onclick="javascript:createbuttonincode()"  value="Create new button"/>
<div id="testdiv"></div>
</form>
</body>

But if I add this meta tag

<meta http-equiv="X-UA-Compatible" content="IE=edge">

in the head then the click event on the dynamically created event fires and I see the alert.

Seems like this is not an issue for Edge browser


问:
Undefined local variable or method error Ruby
I just started coding bootcamp and I am getting this error in my lab. I have tried setting the value with "" but to no avail I am still getting this error
"undefined method `breed=' for # (NoMethodError)

So after defining correctly with "end" I am still getting this error.

I currently have:

```<code>class Dog
  def name=(fido)
    @name= fido
  end

  def name
    @name
  end

  def breed=(beagle)
    @breed= beagle
  end

  def breed
    @breed
  end
end

fido = Dog.new
fido.name = fido
fido.breed = beagle
</code>```

答:
Some explanations. With

```<code>fido = Dog.new
fido.name = fido
puts "fido.name=#{fido.name}  fido.name.class=#{fido.name.class}"
fido.breed = self.beagle
</code>```

you are using the local variable fido just created, and sending the method beagle to self, the default receiver when there is no explicit receiver, which in this case (outside any class) is the special object main provided by the Ruby interpreter :

```<code>$ ruby -w fido_op.rb
fido.name=#<Dog:0x007ffdc2a5d620>  fido.name.class=Dog
fido_op.rb:22:in `<main>': undefined method `beagle' for main:Object (NoMethodError)
</code>```

The class Dog could be simplified :

```<code>class Dog
  attr_reader   :name
  attr_accessor :breed

  def initialize(name)
    @name = name
  end
end

fido = Dog.new('fido')
puts "fido.name=#{fido.name}  fido.name.class=#{fido.name.class}"
fido.breed = 'beagle'
puts "fido.breed=#{fido.breed}"
</code>```

Execution :

```<code>$ ruby -w fido.rb
fido.name=fido  fido.name.class=String
fido.breed=beagle
</code>```

Body:
I just started coding bootcamp and I am getting this error in my lab. I have tried setting the value with "" but to no avail I am still getting this error
"undefined method `breed=' for # (NoMethodError)

So after defining correctly with "end" I am still getting this error.

I currently have:

class Dog
  def name=(fido)
    @name= fido
  end

  def name
    @name
  end

  def breed=(beagle)
    @breed= beagle
  end

  def breed
    @breed
  end
end

fido = Dog.new
fido.name = fido
fido.breed = beagle

Body:
Some explanations. With

fido = Dog.new
fido.name = fido
puts "fido.name=#{fido.name}  fido.name.class=#{fido.name.class}"
fido.breed = self.beagle

you are using the local variable fido just created, and sending the method beagle to self, the default receiver when there is no explicit receiver, which in this case (outside any class) is the special object main provided by the Ruby interpreter :

$ ruby -w fido_op.rb
fido.name=#<Dog:0x007ffdc2a5d620>  fido.name.class=Dog
fido_op.rb:22:in `<main>': undefined method `beagle' for main:Object (NoMethodError)

The class Dog could be simplified :

class Dog
  attr_reader   :name
  attr_accessor :breed

  def initialize(name)
    @name = name
  end
end

fido = Dog.new('fido')
puts "fido.name=#{fido.name}  fido.name.class=#{fido.name.class}"
fido.breed = 'beagle'
puts "fido.breed=#{fido.breed}"

Execution :

$ ruby -w fido.rb
fido.name=fido  fido.name.class=String
fido.breed=beagle


答:
```<code>testList = [10,2,2013,11,2,2014,5,23,2015]

def convert(inputList):
    tempList = []
    for i in range (0, len(inputList), 3): #Repeats every 3 elements
        newDate = str(inputList[i])+"/"+str(inputList[i+1])+"/"+str(inputList[i+2]) #Joins everything together
        tempList.append(newDate)
    return tempList

print(convert(testList))
</code>```

Saswata sux

Title: Convert integers inside a list into strings and then a date in python 3.x

Body:
testList = [10,2,2013,11,2,2014,5,23,2015]

def convert(inputList):
    tempList = []
    for i in range (0, len(inputList), 3): #Repeats every 3 elements
        newDate = str(inputList[i])+"/"+str(inputList[i+1])+"/"+str(inputList[i+2]) #Joins everything together
        tempList.append(newDate)
    return tempList

print(convert(testList))

Saswata sux


问:
Lock DbContext for operation completion in EF6
I have some code in my business logic layer which consume some repositories which in turn use a DbContext (in the data layer). Most of the code is async. At some point in my business logic, I call several async method of the repositories at once (Task.WhenAll...))
And I ran into an error A second operation started on this context before a previous asynchronous operation completed

My point of view is, the business logic should not care/be aware on how the repositories do their job, so it should be able to use parallelism on async Task if "it pleases so".

So I would like to be able to lock in an async/await friendly way the critical moment where A second operation should wait until the previous asynchronous operation complete.

How can this be done?

Current work-arround: forget Task.WhenAll use await like TPL don't even exist

```<code>        var postsResult = await _IUserLogic.GetActivePostsAsync();
        var usersResult = await _IUserLogic.SearchUsersWithPostAsync(viewModel.Name, viewModel.PostId);
</code>```

Code To-be

```<code>        var postsTask = _IUserLogic.GetActivePostsAsync();
        var usersTask = _IUserLogic.SearchUsersWithPostAsync(viewModel.Name, viewModel.PostId);
        await Ask.WhenAll(postsTask , usersTask );
        var postsResult = postsTask.Result;
        var usersResult = usersTask.Result;
</code>```

答:
Each thread needs its own DbContext because DbContext is not thread safe.  However, there are a few work-arounds here.

Each repository gets their own, new DbContext.  That way, each has their own instance on their own thread.  If you need this to be a single transaction, you can use Transaction Scope (newest version allows async calls).

The business layer passes the dbcontext into each repository and will call save changes once at the end.  Each repository simply adds their data to the DbSets and you have a single call at the end.

(Worst) Override SaveChanges on DbContext in your instance and create your own lock() so all go through there.  However, his pretty much defeats the purpose of Task.WhenAll since you can only save one at a time, anyway.

Do what you did and call them individually.

Body:
I have some code in my business logic layer which consume some repositories which in turn use a DbContext (in the data layer). Most of the code is async. At some point in my business logic, I call several async method of the repositories at once (Task.WhenAll...))
And I ran into an error A second operation started on this context before a previous asynchronous operation completed

My point of view is, the business logic should not care/be aware on how the repositories do their job, so it should be able to use parallelism on async Task if "it pleases so".

So I would like to be able to lock in an async/await friendly way the critical moment where A second operation should wait until the previous asynchronous operation complete.

How can this be done?

Current work-arround: forget Task.WhenAll use await like TPL don't even exist

        var postsResult = await _IUserLogic.GetActivePostsAsync();
        var usersResult = await _IUserLogic.SearchUsersWithPostAsync(viewModel.Name, viewModel.PostId);

Code To-be

        var postsTask = _IUserLogic.GetActivePostsAsync();
        var usersTask = _IUserLogic.SearchUsersWithPostAsync(viewModel.Name, viewModel.PostId);
        await Ask.WhenAll(postsTask , usersTask );
        var postsResult = postsTask.Result;
        var usersResult = usersTask.Result;


问:
Error converting java.lang.String to JSONObject
I access a web service from the andriod emulator and am able to but the output i get is something like this as shown below :

```<code><?xml version="1.0" encoding="utf-8" ?>  <ArrayOfQuestionnaire xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">  <Questionnaire>   <QuestionnaireId>0</QuestionnaireId>   <QuestionnaireName>Microsoft 0</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>1</QuestionnaireId>   <QuestionnaireName>Microsoft 1</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>2</QuestionnaireId>   <QuestionnaireName>Microsoft 2</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>3</QuestionnaireId>   <QuestionnaireName>Microsoft 3</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>4</QuestionnaireId>   <QuestionnaireName>Microsoft 4</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>5</QuestionnaireId>   <QuestionnaireName>Microsoft 5</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>6</QuestionnaireId>   <QuestionnaireName>Microsoft 6</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>7</QuestionnaireId>   <QuestionnaireName>Microsoft 7</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>8</QuestionnaireId>   <QuestionnaireName>Microsoft 8</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>9</QuestionnaireId>   <QuestionnaireName>Microsoft 9</QuestionnaireName>    </Questionnaire> </ArrayOfQuestionnaire>
</code>```

I want to be able to parse data to the JSON format . Isnt it suppose to send data in the JSON format ?

When i try to access with the code

JSONObject JResponse = new
  JSONObject(content);    String
  sMessage =
  JResponse.getString("QuestionnaireName");
     int success =
  JResponse.getInt("QuestionnaireId");

Anyways i get the error saying

```<code>   Value <?xml of type java.lang.String cannot be converted to JSONObject ????
</code>```

Any idea on how to go about this ?

Regards

答: Your data is XML not JSON. There is no point converting XML to JSON on the client and then parse JSON. You need to use Java's XML parser or simply return JSON from the server.</p>

Body:
I access a web service from the andriod emulator and am able to but the output i get is something like this as shown below :

<?xml version="1.0" encoding="utf-8" ?>  <ArrayOfQuestionnaire xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">  <Questionnaire>   <QuestionnaireId>0</QuestionnaireId>   <QuestionnaireName>Microsoft 0</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>1</QuestionnaireId>   <QuestionnaireName>Microsoft 1</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>2</QuestionnaireId>   <QuestionnaireName>Microsoft 2</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>3</QuestionnaireId>   <QuestionnaireName>Microsoft 3</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>4</QuestionnaireId>   <QuestionnaireName>Microsoft 4</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>5</QuestionnaireId>   <QuestionnaireName>Microsoft 5</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>6</QuestionnaireId>   <QuestionnaireName>Microsoft 6</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>7</QuestionnaireId>   <QuestionnaireName>Microsoft 7</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>8</QuestionnaireId>   <QuestionnaireName>Microsoft 8</QuestionnaireName>    </Questionnaire>  <Questionnaire>   <QuestionnaireId>9</QuestionnaireId>   <QuestionnaireName>Microsoft 9</QuestionnaireName>    </Questionnaire> </ArrayOfQuestionnaire>

I want to be able to parse data to the JSON format . Isnt it suppose to send data in the JSON format ?

When i try to access with the code

JSONObject JResponse = new
  JSONObject(content);    String
  sMessage =
  JResponse.getString("QuestionnaireName");
     int success =
  JResponse.getInt("QuestionnaireId");

Anyways i get the error saying

   Value <?xml of type java.lang.String cannot be converted to JSONObject ????

Any idea on how to go about this ?

Regards