问:
ProgrammingError (Error during template rendering)

I am getting this Exception in my browser, I have seen upto 20 posts related to this error but I could not have found any solution.I am using Postgre database (pgAdmin 4). I am new to Django, Please help me, Thanks in advance.

I have made a project from djangogirls tutorial http://tutorial.djangogirls.org/en/#django-girls-tutorial. Then I changed my database to postgre and prject was running as expected. then I made a copy of this project and stored somewhere in my PC. Then I made some changes to my original project with same database settings.

when I run my copy of previous project I found this Error :-

projectname/urls.py

```<code>   urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('blog.urls')),
]
</code>```

My views.py

```<code>def blog_list(request):
posts = Blog.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/blog_list.html', {'posts': posts})
</code>```

blog_list.html

```<code>{% for post in posts %}
    <div class="post">
        <div class="date">
            {{ post.published_date }}
        </div>
        <h1><a href="{% url 'blog_detail' pk=post.pk %}">{{ post.title }}</a></h1>
        <p>{{ post.short_description|linebreaksbr }}</p>
    </div>
{% endfor %}
</code>```

my models.py

```<code>    class Blog(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    sub_title = models.CharField(max_length=100, null = True)
    short_description = models.CharField(max_length=100, null = True)
    long_description = models.TextField(null = True)
    #text = models.TextField()
    published_date = models.DateTimeField(blank=True, null=True)
    created_date = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class DeletedPost(models.Model):
    post_title = models.CharField(max_length=200, null=True)
    deleted = models.DateTimeField(default = timezone.now)
</code>```

my appname/urls.py

```<code>   urlpatterns = [
    url(r'^$', views.blog_list, name='blog_list'),
    url(r'^blog/(?P<pk>\d+)/$', views.blog_detail, name='blog_detail'),
    url(r'^blog/new/$', views.blog_new, name='blog_new'),
    url(r'^blog/(?P<pk>\d+)/edit/$', views.blog_edit, name='blog_edit'),
    url(r'^blog/(?P<pk>\d+)/delete/$', views.post_delete, name='post_delete'),
]
</code>```

Error in Browser :

Traceback:

```<code>Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 1.10
Python Version: 3.4.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template D:\mysite\blog\templates\blog\blog_list.html, error at line 4
   relation "blog_blog" does not exist
LINE 1: ..."."created_date", "blog_blog"."last_updated" FROM "blog_blog...
                                                             ^
   1 : {% extends 'blog/base.html' %}
   2 :
   3 : {% block content %}
   4 :      {% for post in posts %}
   5 :         <div class="post">
   6 :             <div class="date">
   7 :                 {{ post.published_date }}
   8 :             </div>
   9 :             <h1><a href="{% url 'blog_detail' pk=post.pk %}">{{ post.title }}</a></h1>
   10 :             <p>{{ post.short_description|linebreaksbr }}</p>
   11 :         </div>
   12 :     {% endfor %}
   13 : {% endblock %}

Traceback:

File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

The above exception (relation "blog_blog" does not exist
LINE 1: ..."."created_date", "blog_blog"."last_updated" FROM "blog_blog...
                                                             ^
) was the direct cause of the following exception:

File "C:\Python34\lib\site-packages\django\core\handlers\exception.py" in inner
  39.             response = get_response(request)

File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "D:\mysite\blog\views.py" in blog_list
  10.     return render(request, 'blog/blog_list.html', {'posts': posts})

File "C:\Python34\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Python34\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Python34\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render
  208.                     return self._render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render
  994.                 bit = node.render_annotated(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render_annotated
  961.             return self.render(context)

File "C:\Python34\lib\site-packages\django\template\loader_tags.py" in render
  174.         return compiled_parent._render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render
  994.                 bit = node.render_annotated(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render_annotated
  961.             return self.render(context)

File "C:\Python34\lib\site-packages\django\template\loader_tags.py" in render
  70.                 result = block.nodelist.render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render
  994.                 bit = node.render_annotated(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render_annotated
  961.             return self.render(context)

File "C:\Python34\lib\site-packages\django\template\defaulttags.py" in render
  166.             len_values = len(values)

File "C:\Python34\lib\site-packages\django\db\models\query.py" in __len__
  238.         self._fetch_all()

File "C:\Python34\lib\site-packages\django\db\models\query.py" in _fetch_all
  1085.             self._result_cache = list(self.iterator())

File "C:\Python34\lib\site-packages\django\db\models\query.py" in __iter__
  54.         results = compiler.execute_sql()

File "C:\Python34\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  835.             cursor.execute(sql, params)

File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)

File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "C:\Python34\lib\site-packages\django\db\utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "C:\Python34\lib\site-packages\django\utils\six.py" in reraise
  685.             raise value.with_traceback(tb)

File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /
Exception Value: relation "blog_blog" does not exist
LINE 1: ..."."created_date", "blog_blog"."last_updated" FROM "blog_blog...
                                                         ^
</code>```

答:
after migrating look at your installed apps in settings.py, you missed a comma after your app name
Installed Applications:
[
blog,
]
It's because of that comma it cannot detect your app name.</p>

Body:
I am getting this Exception in my browser, I have seen upto 20 posts related to this error but I could not have found any solution.I am using Postgre database (pgAdmin 4). I am new to Django, Please help me, Thanks in advance.

I have made a project from djangogirls tutorial http://tutorial.djangogirls.org/en/#django-girls-tutorial. Then I changed my database to postgre and prject was running as expected. then I made a copy of this project and stored somewhere in my PC. Then I made some changes to my original project with same database settings.

when I run my copy of previous project I found this Error :-

projectname/urls.py

   urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('blog.urls')),
]

My views.py

def blog_list(request):
posts = Blog.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/blog_list.html', {'posts': posts})

blog_list.html

{% for post in posts %}

            {{ post.published_date }}

{{ post.title }}

{{ post.short_description|linebreaksbr }}

{% endfor %}

my models.py

    class Blog(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    sub_title = models.CharField(max_length=100, null = True)
    short_description = models.CharField(max_length=100, null = True)
    long_description = models.TextField(null = True)
    #text = models.TextField()
    published_date = models.DateTimeField(blank=True, null=True)
    created_date = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class DeletedPost(models.Model):
    post_title = models.CharField(max_length=200, null=True)
    deleted = models.DateTimeField(default = timezone.now)

my appname/urls.py

   urlpatterns = [
    url(r'^$', views.blog_list, name='blog_list'),
    url(r'^blog/(?P<pk>\d+)/$', views.blog_detail, name='blog_detail'),
    url(r'^blog/new/$', views.blog_new, name='blog_new'),
    url(r'^blog/(?P<pk>\d+)/edit/$', views.blog_edit, name='blog_edit'),
    url(r'^blog/(?P<pk>\d+)/delete/$', views.post_delete, name='post_delete'),
]

Error in Browser :

Traceback:

Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 1.10
Python Version: 3.4.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template D:\mysite\blog\templates\blog\blog_list.html, error at line 4
   relation "blog_blog" does not exist
LINE 1: ..."."created_date", "blog_blog"."last_updated" FROM "blog_blog...
                                                             ^
   1 : {% extends 'blog/base.html' %}
   2 :
   3 : {% block content %}
   4 :      {% for post in posts %}
   5 :

   6 :

   7 :                 {{ post.published_date }}
   8 :

   9 :
{{ post.title }}

   10 :
{{ post.short_description|linebreaksbr }}

   11 :

   12 :     {% endfor %}
   13 : {% endblock %}

Traceback:

File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

The above exception (relation "blog_blog" does not exist
LINE 1: ..."."created_date", "blog_blog"."last_updated" FROM "blog_blog...
                                                             ^
) was the direct cause of the following exception:

File "C:\Python34\lib\site-packages\django\core\handlers\exception.py" in inner
  39.             response = get_response(request)

File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "D:\mysite\blog\views.py" in blog_list
  10.     return render(request, 'blog/blog_list.html', {'posts': posts})

File "C:\Python34\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Python34\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Python34\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render
  208.                     return self._render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render
  994.                 bit = node.render_annotated(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render_annotated
  961.             return self.render(context)

File "C:\Python34\lib\site-packages\django\template\loader_tags.py" in render
  174.         return compiled_parent._render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render
  994.                 bit = node.render_annotated(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render_annotated
  961.             return self.render(context)

File "C:\Python34\lib\site-packages\django\template\loader_tags.py" in render
  70.                 result = block.nodelist.render(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render
  994.                 bit = node.render_annotated(context)

File "C:\Python34\lib\site-packages\django\template\base.py" in render_annotated
  961.             return self.render(context)

File "C:\Python34\lib\site-packages\django\template\defaulttags.py" in render
  166.             len_values = len(values)

File "C:\Python34\lib\site-packages\django\db\models\query.py" in __len__
  238.         self._fetch_all()

File "C:\Python34\lib\site-packages\django\db\models\query.py" in _fetch_all
  1085.             self._result_cache = list(self.iterator())

File "C:\Python34\lib\site-packages\django\db\models\query.py" in __iter__
  54.         results = compiler.execute_sql()

File "C:\Python34\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  835.             cursor.execute(sql, params)

File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)

File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "C:\Python34\lib\site-packages\django\db\utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "C:\Python34\lib\site-packages\django\utils\six.py" in reraise
  685.             raise value.with_traceback(tb)

File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /
Exception Value: relation "blog_blog" does not exist
LINE 1: ..."."created_date", "blog_blog"."last_updated" FROM "blog_blog...
                                                         ^


来源: stackexchange

问:
Cannot get DOM events on component in host component
I have a Vue component that contains a list of objects named lines.  I build a table from those lines using different components based on the line type.  This works perfectly.  Here's a stripped down version of the component:

```<code><template>
  <table>
    <tr v-for="line in lines"
        :key="line.key"
        :is="componentForType[line.eventType] || 'LogLine'"
        v-bind="line"
    />
  </table>
</template>

<script>
  export default {
    name: 'DebugLog',
    components: {
      LogLine,
      FormattedLogLine,
      UserDebug,
      Limits
    },
    data () {
      return {
        lines: [],
        selectedKey: null,
        componentForType: {
          'USER_DEBUG' : 'UserDebug',
          'LIMIT_USAGE_FOR_NS' : 'Limits',
          'EXCEPTION_THROWN' : 'FormattedLogLine',
          'FATAL_ERROR' : 'FormattedLogLine'
        }

      }
    },
    mounted() {
      // code that loads this.lines
    }
  }
</script>
</code>```

Now I want to be able to click any row of the table, and have the row become "selected", meaning that I want store line.key in this.selectedKey and use CSS to render that line differently.  But I can't get the events working.  Here's the updated <template>; nothing else is changed:

```<code><template>
  <table>
    <tr v-for="line in lines"
        :key="line.key"
        :is="componentForType[line.eventType] || 'LogLine'"
        v-bind="line"
        :class="{selected: line.key == selectedKey}"
        @click.capture="selectedKey = line.key"
    />
  </table>
</template>
</code>```

I've added the last 2 properties on the tr element - a dynamic class binding and a click event handler to set this.selectedKey to the active line's key.  But it isn't working.  I replaced the @click handler code with console.log(line.key) and nothing is logged, which tells me that my @click handler is never firing.  I originally wrote it with out the .capture modifier, but tried adding the modifier when the original didn't work.

Is vue.js stopping propagation from the child component to the parent?  Can I not bind the click event on the tr since it :is another vue component?  Or is there something else going on?  The examples I've found in the docs are much simpler and I'm not sure they correspond to my situation.  The various child components are not binding any click events.  I'd prefer to handle the event entirely in the parent as shown, since I will have a number of types of child component, and I don't want to have to implement click handlers in each.

Update: Looking at my child components, I note that each contains a tr tag that must effectively replace the tr in the parent template.  For example, my most basic component is LogLine, shown here:

```<code><template>
  <tr>
    <td>{{timeStamp}}</td>
    <td>{{eventType}}</td>
    <td>{{lineNumber}}</td>
    <td>{{lineData}}</td>
  </tr>
</template>

<script>
  export default {
    name: 'LogLine',
    props: ['timeStamp', 'eventType', 'lineData', 'lineNumber'],
    data: function () {
      return {}
    }
  }
</script>
</code>```

So I'm guessing that the binding in the parent isn't actually binding on the tr in the DOM; it's just binding on the Vue component, listening for a click event to be sent from the child with $emit; and that each child component will need to bind @click on its tr and emit it to the parent.  Assuming I'm right, is there any shortcut I can use from the parent template to have vue forward the DOM events?  Any other option I'm missing besides binding click in every child component?

答:
Since you are using an :is prop, it's considered a dynamic Vue component, not a DOM element.

Events listener on a Vue component won't be passed down to its DOM element by default. You have to do it manually by going into the component template and add v-on="$listeners".

demo: https://jsfiddle.net/jacobgoh101/am59ojwx/7/

e.g.
 ...

ContentLicense: CC BY-SA 4.0

Body:
I have a Vue component that contains a list of objects named lines.  I build a table from those lines using different components based on the line type.  This works perfectly.  Here's a stripped down version of the component:

<template>

</template>

Now I want to be able to click any row of the table, and have the row become "selected", meaning that I want store line.key in this.selectedKey and use CSS to render that line differently.  But I can't get the events working.  Here's the updated <template>; nothing else is changed:

<template>

</template>

I've added the last 2 properties on the tr element - a dynamic class binding and a click event handler to set this.selectedKey to the active line's key.  But it isn't working.  I replaced the @click handler code with console.log(line.key) and nothing is logged, which tells me that my @click handler is never firing.  I originally wrote it with out the .capture modifier, but tried adding the modifier when the original didn't work.

Is vue.js stopping propagation from the child component to the parent?  Can I not bind the click event on the tr since it :is another vue component?  Or is there something else going on?  The examples I've found in the docs are much simpler and I'm not sure they correspond to my situation.  The various child components are not binding any click events.  I'd prefer to handle the event entirely in the parent as shown, since I will have a number of types of child component, and I don't want to have to implement click handlers in each.

Update: Looking at my child components, I note that each contains a tr tag that must effectively replace the tr in the parent template.  For example, my most basic component is LogLine, shown here:

<template>

    {{timeStamp}}
    {{eventType}}
    {{lineNumber}}
    {{lineData}}

</template>

So I'm guessing that the binding in the parent isn't actually binding on the tr in the DOM; it's just binding on the Vue component, listening for a click event to be sent from the child with $emit; and that each child component will need to bind @click on its tr and emit it to the parent.  Assuming I'm right, is there any shortcut I can use from the parent template to have vue forward the DOM events?  Any other option I'm missing besides binding click in every child component?

Body:
Since you are using an :is prop, it's considered a dynamic Vue component, not a DOM element.

Events listener on a Vue component won't be passed down to its DOM element by default. You have to do it manually by going into the component template and add v-on="$listeners".

demo: https://jsfiddle.net/jacobgoh101/am59ojwx/7/

e.g. <div v-on="$listeners"> ... </div>


问:
Async await sqlite in javascript
I'm looking at this tutorial, which has a library called aa-sqlite in order to replace Promises() syntax with async-await.

I'm not seeing aa-sqlite on npm.  Is there another, updated syntax for async await sqlite?

Here is what I'm trying with the standard sqlite library:

```<code>const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database("tmp.db")

async function myfunc(db) {
  let sql = "SELECT id id FROM TABLE LIMIT 2"
  let res1 = await db.run(sql)
  console.log(res1)
  for (row of res1) {
    console.log(row);
  }
</code>```

But this yields

```<code>TypeError: res1 is not iterable
</code>```

I am not expecting res1 to be an object, but instead an iterator of results.  How can I async/await the results of a db.run query in ES7/ES8?

答: Try the sqlite package, rather than the sqlite3 used in the demo. It has better support for async await.</p>

Title: Async await sqlite in javascript

Body:
I'm looking at this tutorial, which has a library called aa-sqlite in order to replace Promises() syntax with async-await.

I'm not seeing aa-sqlite on npm.  Is there another, updated syntax for async await sqlite?

Here is what I'm trying with the standard sqlite library:

const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database("tmp.db")

async function myfunc(db) {
  let sql = "SELECT id id FROM TABLE LIMIT 2"
  let res1 = await db.run(sql)
  console.log(res1)
  for (row of res1) {
    console.log(row);
  }

But this yields

TypeError: res1 is not iterable

I am not expecting res1 to be an object, but instead an iterator of results.  How can I async/await the results of a db.run query in ES7/ES8?


问:
How to group timelines by hrs
Lets say I have array of JSON data with timeStarted and timeEnded values in Date format. I am struggling to group timeSpent by hours.
For example,

```<code>[{timeStarted: '00:10:30', timeEnded: '00:14:02'},
{timeStarted: '00:48:08', timeEnded: '02:33:33'}, ...]
</code>```

I am trying to group them so I get array like

```<code>[{hrs: '0', timeSpent: '16'},
{hrs: '1', timeSpent: '60'},
{hrs: '2', timeSpent: '34'}, ...]
</code>```

I have tried like billion times to group them but I cant figure out how: I always get values like 95 mins in hour. At least I need a right way to think. Thanks.

答:
Based on the values you have for timeSpent and your first array, it sounds like you want to get an array representing how much of each clock hour (e.g. from 9:00 to 10:00 or 14:00 to 15:00) was "spent".

If that's so, you can do this by getting the hours and minutes (or even seconds, if you want to go that granular) of each interval and tallying up how many minutes have been added to each individual hour.

For a simple case where the interval is within a single clock hour, you can do this by subtracting the end time from the start time. In a multi-hour interval it's a little more complicated. See the code below for one way you could handle this. There are probably better ways, and the code only goes down to the minute, but it's a start.

The keys of the hours array below correspond to each clock hour.

```<code>const timesElapsed = [
  {timeStarted: '00:10:30', timeEnded: '00:14:02'},
  {timeStarted: '00:48:08', timeEnded: '02:33:33'}
]

// Initialize hours array: each key of the array represents a specific clock hour
let hours = []
for (let interval of timesElapsed) {
  // Get the pertinent data as Numbers
  const startHour = (Number)(interval.timeStarted.split(':')[0])
  const startMinute = (Number)(interval.timeStarted.split(':')[1])
  const endHour = (Number)(interval.timeEnded.split(':')[0])
  const endMinute = (Number)(interval.timeEnded.split(':')[1])

  // Initialize elements in Hour array if need be
  if (hours[startHour] === undefined) hours[startHour] = 0
  if (hours[endHour] === undefined) hours[endHour] = 0

  // An interval within an hour
  if (startHour === endHour) {
    hours[startHour] += (endMinute - startMinute)
  } else {
    // The first hour of a multi-hour interval
    hours[startHour] += 60 - startMinute

    // The middle hours, if any
    for (let i = startHour + 1; i < endHour; i++)
      hours[i] = 60

    // The final hour
    hours[endHour] += endMinute
  }
}

// console.log(hours)
// [16, 60, 33]
</code>```

Title: How to group timelines by hrs

Body:
Lets say I have array of JSON data with timeStarted and timeEnded values in Date format. I am struggling to group timeSpent by hours.
For example,

[{timeStarted: '00:10:30', timeEnded: '00:14:02'},
{timeStarted: '00:48:08', timeEnded: '02:33:33'}, ...]

I am trying to group them so I get array like

[{hrs: '0', timeSpent: '16'},
{hrs: '1', timeSpent: '60'},
{hrs: '2', timeSpent: '34'}, ...]

I have tried like billion times to group them but I cant figure out how: I always get values like 95 mins in hour. At least I need a right way to think. Thanks.

Body:
Based on the values you have for timeSpent and your first array, it sounds like you want to get an array representing how much of each clock hour (e.g. from 9:00 to 10:00 or 14:00 to 15:00) was "spent".

If that's so, you can do this by getting the hours and minutes (or even seconds, if you want to go that granular) of each interval and tallying up how many minutes have been added to each individual hour.

For a simple case where the interval is within a single clock hour, you can do this by subtracting the end time from the start time. In a multi-hour interval it's a little more complicated. See the code below for one way you could handle this. There are probably better ways, and the code only goes down to the minute, but it's a start.

The keys of the hours array below correspond to each clock hour.

const timesElapsed = [
  {timeStarted: '00:10:30', timeEnded: '00:14:02'},
  {timeStarted: '00:48:08', timeEnded: '02:33:33'}
]

// Initialize hours array: each key of the array represents a specific clock hour
let hours = []
for (let interval of timesElapsed) {
  // Get the pertinent data as Numbers
  const startHour = (Number)(interval.timeStarted.split(':')[0])
  const startMinute = (Number)(interval.timeStarted.split(':')[1])
  const endHour = (Number)(interval.timeEnded.split(':')[0])
  const endMinute = (Number)(interval.timeEnded.split(':')[1])

  // Initialize elements in Hour array if need be
  if (hours[startHour] === undefined) hours[startHour] = 0
  if (hours[endHour] === undefined) hours[endHour] = 0

  // An interval within an hour
  if (startHour === endHour) {
    hours[startHour] += (endMinute - startMinute)
  } else {
    // The first hour of a multi-hour interval
    hours[startHour] += 60 - startMinute

    // The middle hours, if any
    for (let i = startHour + 1; i < endHour; i++)
      hours[i] = 60

    // The final hour
    hours[endHour] += endMinute
  }
}

// console.log(hours)
// [16, 60, 33]


问:
Qt linking error when running OpenCV python application in Ubuntu
I am running 4.1.0 with python 3.7.3. I installed opencv using conda:

```<code>conda install -c conda-forge opencv
</code>```

I don't have any experience using Qt. I am simply trying to show an image or a video using the OpenCV imshow method:

cv.imshow('Result (Press any key to exit)', img)
cv.waitKey(0)
cv.destroyAllWindows()
```

<p>But when I run the program, I get this error:</p>

```xkbcommon: ERROR: failed to add default include path
Qt: Failed to create XKB context!
Use QT_XKB_CONFIG_ROOT environmental variable to provide an additional search path, add ':' as separator to provide several search paths and/or make sure that XKB configuration data directory contains recent enough contents, to update please see http://cgit.freedesktop.org/xkeyboard-config/ .
```

The program continues to run just fine. However cv.waitKey(0) is not working. I read up about setting the environment variable, but I plan to bundle this program using pyinstaller, so I can't rely on this fix forever.

Is there a permanent fix?

答:
Issue is referenced here: https://github.com/conda-forge/qt-feedstock/issues/104. Fixes have been merged into master.

For Ubuntu, you can update Qt to fix this issue:

conda install -c conda-forge qt

qt  5.9.7-h52cfd70_1 --> 5.9.7-h52cfd70_2

Body:
I am running 4.1.0 with python 3.7.3. I installed opencv using conda:

conda install -c conda-forge opencv

I don't have any experience using Qt. I am simply trying to show an image or a video using the OpenCV imshow method:

cv.imshow('Result (Press any key to exit)', img)
cv.waitKey(0)
cv.destroyAllWindows()

But when I run the program, I get this error:

xkbcommon: ERROR: failed to add default include path
Qt: Failed to create XKB context!
Use QT_XKB_CONFIG_ROOT environmental variable to provide an additional search path, add ':' as separator to provide several search paths and/or make sure that XKB configuration data directory contains recent enough contents, to update please see http://cgit.freedesktop.org/xkeyboard-config/ .

The program continues to run just fine. However cv.waitKey(0) is not working. I read up about setting the environment variable, but I plan to bundle this program using pyinstaller, so I can't rely on this fix forever.

Is there a permanent fix?


问:
Can I append/push values of html elements to each row of an array generated from a html table within the form?
I'm doing a html form for online requests by users. The form has text input fields for user contact details (e.g. user name, department, email, etc) at the top, followed by a table with multiple rows for different items requested.

I want to have the form data appended into Google Sheets, where each table row (item requested) is appended as a separate row in Sheets, with the user contact details added to each row, i.e. the contact details have to repeat for the same user.
Link to Sheet

Tried Google Forms -- it's good for single item requests -- one Google Form for one item. But for multiple item requests by the same user, the user has to key in contact details repeatedly. Branching to repeat sections in Forms didn't work, since additional items are added as new columns and not as a new row. Thus I tried a rudimentary html form.

FormTableDialog

Code.gs:

```<code>function addRows(valuesAll) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  sheet.getRange(sheet.getLastRow()+1,1,valuesAll.length,valuesAll[0].length).setValues(valuesAll);
}
</code>```

Html:

```<code><!DOCTYPE html>
<html>
  <head>
    <?!= include('CSS_Table'); ?>
  </head>
  <body>
  Name: <input type="text" id="Name"><br>
  Phone: <input type="text" id="Phone"><br>
  Email: <input type="email" id="Email"><br>
  Department: <input type="text" id="Dept"><br>

    <table id="tableRows">
      <thead>
        <tr>
          <th>Item</th>
          <th>Description</th>
          <th>Quantity</th>
          <th>Location</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
        </tr>
        <tr>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
        </tr>
        <tr>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
        </tr>
        <tr>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
        </tr>
        <tr>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
          <td><input class="inputCell" type="text"></td>
        </tr>
      <tbody>
    </table>
    <div class="buttonBar">
      <input class="inputButton" type="button" value="Submit" onclick="buttonClick(this)">
      <input class="inputButton" type="button" value="Cancel" onclick="buttonClick(this)">
    </div>
    <?!= include('JS_Table'); ?>
  </body>

</code>```

JS_Table.html:

```<code><script>
  function buttonClick(button) {
    if( button.value === "Submit" ) {
      var values = [];
      var table = document.getElementById("tableRows");
      for( var i=1; i<table.rows.length; i++ ) {
        values.push([]);
        var row = table.rows[i];
        for( var j=0; j<row.cells.length; j++ ) {
          var cell = row.cells[j].firstChild.value;
          values[i-1].push(cell)

       var user = ["Name","Phone","Email","Dept"];
       var valuesAll =  values.concat(user)
        }
      }
      google.script.run.addRows(valuesAll);
      google.script.host.close();
    }
    else {
      if( confirm("Exit without saving?") ) google.script.host.close();
    }
  }
</script>
</code>```

Tried to simply concat the id's of the user details, with the table array. But the google script didn't work. Appreciate any suggestions for this newbie.

The Execution Transcript:

```<code>[19-05-25 19:42:15:580 PDT] Starting execution
[19-05-25 19:42:15:587 PDT] SpreadsheetApp.getActiveSpreadsheet() [0 seconds
[19-05-25 19:42:15:672 PDT] Spreadsheet.getSheetByName([Sheet1]) [0.084 seconds]
[19-05-25 19:42:15:772 PDT] Sheet.getLastRow() [0.099 seconds]
[19-05-25 19:42:15:772 PDT] Sheet.getRange([2, 1, 9, 4]) [0 seconds]
[19-05-25 19:42:15:779 PDT] Execution failed: Cannot convert Array to Object[][]. (line 17, file "Code") [0.189 seconds total runtime]
</code>```

答:
There are two problems with the OPs code.

1 - output is not adjusted for Google's two-dimensional range.
2 - the Name, phone, email and department are not collected.

The following answer is written to work in the sidebar (not essential) and also tests whether the form data is complete - that is: whether there is complete data for  the Item, Description, Quantity and Location in each row . The OP can easily remove this test.

56302393_04_gs.gs

```<code>function showSidebar04() {
  var htmlOutput = HtmlService.createHtmlOutputFromFile("56302393_04_html");
  htmlOutput.setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle("56302393_04 Form");
  var ui = SpreadsheetApp.getUi();
  ui.showSidebar(htmlOutput);
}

function addRows04(valuesAll) {
  //Logger.log("DEBUG: valuesall = "+valuesAll);
  var testdata = [];
  var testdata = valuesAll.slice(0);
  // Logger.log("DEBUG: testdata = "+testdata);

  // remove the name fields
  testdata.splice(0, 4);
  // get the number of fields
  var testdatalength = (testdata.length);
  // Logger.log("DEBUG: testdata length = "+testdatalength);
  // get the number of empty fields - were looking for rows that are inclonplete
  var newempties = testdatalength - testdata.filter(String).length;
  var adjustedlength = testdatalength-newempties;
  //Logger.log("DEBUG: newempties = "+newempties+", so adjusted length = "+adjustedlength);

  // calculate the number of rows
  var netrows = adjustedlength/4;
  // Logger.log("DEBUG: adjusted length divided by 4 = "+netrows);
  // is the result an integers - get the mod
  var netrowMod = adjustedlength % 4;
  // Logger.log("DEBUG: residual = "+netrowMod);
  // test whether newrows is an integer by testing whether mode = 0
  if(netrowMod !== 0){
    // Logger.log("DEBUG: netrows: "+netrows+" is not an integer");
    Browser.msgBox("The data rows were not completed evenly. Code aborted");
    return;
  }

  // setup the spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetname = "Sheet1";
  var sheet = ss.getSheetByName("Sheet1");
  var lastrow = sheet.getLastRow();

  // get the name data
  var name = valuesAll[0];
  var phone = valuesAll[1];
  var email = valuesAll[2];
  var dept = valuesAll[3];

  // set the range
  var outputRange = sheet.getRange(lastrow+1,1,netrows,8);
  // Logger.log("DEBUG Output range = "+range.getA1Notation());

  var datastart = 4;
  var alldata = [];

  for (var i = 0; i<netrows;i++){
    var datarow = [];

    // get the row information
    var item = valuesAll[(i*datastart)+4];
    var desc = valuesAll[(i*datastart)+5]
    var qty = valuesAll[(i*datastart)+6];
    var locn = valuesAll[(i*datastart)+7];
    // Logger.log("DEBUG: i="+i+", values = "+item+" "+desc+" "+qty+" "+locn);
    // build the row fields
    datarow.push(item);
    datarow.push(desc);
    datarow.push(qty);
    datarow.push(locn);
    datarow.push(name);
    datarow.push(phone);
    datarow.push(email);
    datarow.push(dept);

    // accumulate the rows
    alldata.push(datarow);
    //Logger.log("DEBUG: datarow = "+datarow)
    //Logger.log("DEBUG: alldata = "+alldata)
  }
  // update the values of the outputrange
  outputRange.setValues(alldata);
}
</code>```

56302393_04_html.html

```<code><!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
  <table id="tableName">
  <tbody>
  <tr><td>Name:</td><td> <input type="text" name="name" value="Fred"></td></tr>
  <tr><td>Phone: </td><td><input type="text" name="phone" value="0412987654"></td></tr>
  <tr><td>Email: </td><td><input type="email" name="email" value="fred@example.com"></td></tr>
  <tr><td>Department: </td><td><input type="text" name="dept" value="Sydney"></td></tr>
  </tbody>
  </table>
<style>
  .inputCell { float: right; width: 40%; }
  .inputCell { float: left; width: 80%; }
  .inputButton { float: left; width: 50%; }
</style>
    <table id="tableRows">
      <thead>
        <tr>
          <th>Item</th>
          <th>Description</th>
          <th>Quantity</th>
          <th>Location</th>
        </tr>
      </thead>
      <tbody>
     <tr>
       <td><input class="inputCell" type="text" value="1"></td>
       <td><input class="inputCell" type="text" value="amd"></td>
       <td><input class="inputCell" type="text" value="11"></td>
       <td><input class="inputCell" type="text" value="B12"></td>
     </tr>
     <tr>
       <td><input class="inputCell" type="text" value="2"></td>
       <td><input class="inputCell" type="text" value="ibm"></td>
       <td><input class="inputCell" type="text" value="22"></td>
       <td><input class="inputCell" type="text" value="Z23"></td>
     </tr>
     <tr>
       <td><input class="inputCell" type="text" value="3"></td>
       <td><input class="inputCell" type="text" value="digital"></td>
       <td><input class="inputCell" type="text" value="33"></td>
       <td><input class="inputCell" type="text" value="A49"></td>
     </tr>
     <tr>
       <td><input class="inputCell" type="text" value="4"></td>
       <td><input class="inputCell" type="text" value="apple"></td>
       <td><input class="inputCell" type="text" value="44"></td>
       <td><input class="inputCell" type="text" value="K12"></td>
     </tr>
     <tr>
       <td><input class="inputCell" type="text" value="5"></td>
       <td><input class="inputCell" type="text" value="rex"></td>
       <td><input class="inputCell" type="text" value="55"></td>
       <td><input class="inputCell" type="text" value="ascot"></td>
     </tr>
      <tbody>
    </table>
    <div class="buttonBar">
      <input class="inputButton" type="button" value="Submit" onclick="buttonClick(this)">
      <input class="inputButton" type="button" value="Cancel" onclick="buttonClick(this)">
    </div>
<script>
  function buttonClick(button) {
    if( button.value === "Submit" ) {

      var valuesAll = [];

      // Collect name details
      var tablename = document.getElementById("tableName");
      var myname = tablename.rows[0].cells[1].children[0].value
      var myphone = tablename.rows[1].cells[1].children[0].value
      var myemail = tablename.rows[2].cells[1].children[0].value
      var mydept = tablename.rows[3].cells[1].children[0].value

      valuesAll.push(myname);
      valuesAll.push(myphone);
      valuesAll.push(myemail);
      valuesAll.push(mydept);

      // collect row details
      var table = document.getElementById("tableRows");

      for( var i=1; i<table.rows.length; i++ ) {
        var row = table.rows[i];
        for( var j=0; j<row.cells.length; j++ ) {
          var cell = row.cells[j].firstChild.value;
          valuesAll.push(cell);
        }
      }
      google.script.run.addRows04(valuesAll);
      google.script.host.close();
    }
    else {
      if( confirm("Exit without saving?") ) google.script.host.close();
    }
  }
</script>
  </body>
</code>```

Output screenshot

Body:
I'm doing a html form for online requests by users. The form has text input fields for user contact details (e.g. user name, department, email, etc) at the top, followed by a table with multiple rows for different items requested.

I want to have the form data appended into Google Sheets, where each table row (item requested) is appended as a separate row in Sheets, with the user contact details added to each row, i.e. the contact details have to repeat for the same user.
Link to Sheet

Tried Google Forms -- it's good for single item requests -- one Google Form for one item. But for multiple item requests by the same user, the user has to key in contact details repeatedly. Branching to repeat sections in Forms didn't work, since additional items are added as new columns and not as a new row. Thus I tried a rudimentary html form.

FormTableDialog

Code.gs:

function addRows(valuesAll) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  sheet.getRange(sheet.getLastRow()+1,1,valuesAll.length,valuesAll[0].length).setValues(valuesAll);
}

Html:

<!DOCTYPE html>

    <?!= include('CSS_Table'); ?>

  Name: <input type="text" id="Name">

  Phone: <input type="text" id="Phone">

  Email: <input type="email" id="Email">

  Department: <input type="text" id="Dept">

          Item
          Description
          Quantity
          Location

          <input class="inputCell" type="text">
          <input class="inputCell" type="text">
          <input class="inputCell" type="text">
          <input class="inputCell" type="text">

          <input class="inputCell" type="text">
          <input class="inputCell" type="text">
          <input class="inputCell" type="text">
          <input class="inputCell" type="text">

          <input class="inputCell" type="text">
          <input class="inputCell" type="text">
          <input class="inputCell" type="text">
          <input class="inputCell" type="text">

          <input class="inputCell" type="text">
          <input class="inputCell" type="text">
          <input class="inputCell" type="text">
          <input class="inputCell" type="text">

          <input class="inputCell" type="text">
          <input class="inputCell" type="text">
          <input class="inputCell" type="text">
          <input class="inputCell" type="text">

      <input class="inputButton" type="button" value="Submit" onclick="buttonClick(this)">
      <input class="inputButton" type="button" value="Cancel" onclick="buttonClick(this)">

    <?!= include('JS_Table'); ?>

JS_Table.html:

Tried to simply concat the id's of the user details, with the table array. But the google script didn't work. Appreciate any suggestions for this newbie.

The Execution Transcript:

[19-05-25 19:42:15:580 PDT] Starting execution
[19-05-25 19:42:15:587 PDT] SpreadsheetApp.getActiveSpreadsheet() [0 seconds
[19-05-25 19:42:15:672 PDT] Spreadsheet.getSheetByName([Sheet1]) [0.084 seconds]
[19-05-25 19:42:15:772 PDT] Sheet.getLastRow() [0.099 seconds]
[19-05-25 19:42:15:772 PDT] Sheet.getRange([2, 1, 9, 4]) [0 seconds]
[19-05-25 19:42:15:779 PDT] Execution failed: Cannot convert Array to Object[][]. (line 17, file "Code") [0.189 seconds total runtime]

Body:
There are two problems with the OPs code.

1 - output is not adjusted for Google's two-dimensional range.
2 - the Name, phone, email and department are not collected.

The following answer is written to work in the sidebar (not essential) and also tests whether the form data is complete - that is: whether there is complete data for  the Item, Description, Quantity and Location in each row . The OP can easily remove this test.

56302393_04_gs.gs

function showSidebar04() {
  var htmlOutput = HtmlService.createHtmlOutputFromFile("56302393_04_html");
  htmlOutput.setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle("56302393_04 Form");
  var ui = SpreadsheetApp.getUi();
  ui.showSidebar(htmlOutput);
}

function addRows04(valuesAll) {
  //Logger.log("DEBUG: valuesall = "+valuesAll);
  var testdata = [];
  var testdata = valuesAll.slice(0);
  // Logger.log("DEBUG: testdata = "+testdata);

  // remove the name fields
  testdata.splice(0, 4);
  // get the number of fields
  var testdatalength = (testdata.length);
  // Logger.log("DEBUG: testdata length = "+testdatalength);
  // get the number of empty fields - were looking for rows that are inclonplete
  var newempties = testdatalength - testdata.filter(String).length;
  var adjustedlength = testdatalength-newempties;
  //Logger.log("DEBUG: newempties = "+newempties+", so adjusted length = "+adjustedlength);

  // calculate the number of rows
  var netrows = adjustedlength/4;
  // Logger.log("DEBUG: adjusted length divided by 4 = "+netrows);
  // is the result an integers - get the mod
  var netrowMod = adjustedlength % 4;
  // Logger.log("DEBUG: residual = "+netrowMod);
  // test whether newrows is an integer by testing whether mode = 0
  if(netrowMod !== 0){
    // Logger.log("DEBUG: netrows: "+netrows+" is not an integer");
    Browser.msgBox("The data rows were not completed evenly. Code aborted");
    return;
  }

  // setup the spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetname = "Sheet1";
  var sheet = ss.getSheetByName("Sheet1");
  var lastrow = sheet.getLastRow();

  // get the name data
  var name = valuesAll[0];
  var phone = valuesAll[1];
  var email = valuesAll[2];
  var dept = valuesAll[3];

  // set the range
  var outputRange = sheet.getRange(lastrow+1,1,netrows,8);
  // Logger.log("DEBUG Output range = "+range.getA1Notation());

  var datastart = 4;
  var alldata = [];

  for (var i = 0; i<netrows;i++){
    var datarow = [];

    // get the row information
    var item = valuesAll[(i*datastart)+4];
    var desc = valuesAll[(i*datastart)+5]
    var qty = valuesAll[(i*datastart)+6];
    var locn = valuesAll[(i*datastart)+7];
    // Logger.log("DEBUG: i="+i+", values = "+item+" "+desc+" "+qty+" "+locn);
    // build the row fields
    datarow.push(item);
    datarow.push(desc);
    datarow.push(qty);
    datarow.push(locn);
    datarow.push(name);
    datarow.push(phone);
    datarow.push(email);
    datarow.push(dept);

    // accumulate the rows
    alldata.push(datarow);
    //Logger.log("DEBUG: datarow = "+datarow)
    //Logger.log("DEBUG: alldata = "+alldata)
  }
  // update the values of the outputrange
  outputRange.setValues(alldata);
}

56302393_04_html.html

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
  <table id="tableName">
  <tbody>
  <tr><td>Name:</td><td> <input type="text" name="name" value="Fred"></td></tr>
  <tr><td>Phone: </td><td><input type="text" name="phone" value="0412987654"></td></tr>
  <tr><td>Email: </td><td><input type="email" name="email" value="fred@example.com"></td></tr>
  <tr><td>Department: </td><td><input type="text" name="dept" value="Sydney"></td></tr>
  </tbody>
  </table>
<style>
  .inputCell { float: right; width: 40%; }
  .inputCell { float: left; width: 80%; }
  .inputButton { float: left; width: 50%; }
</style>
    <table id="tableRows">
      <thead>
        <tr>
          <th>Item</th>
          <th>Description</th>
          <th>Quantity</th>
          <th>Location</th>
        </tr>
      </thead>
      <tbody>
     <tr>
       <td><input class="inputCell" type="text" value="1"></td>
       <td><input class="inputCell" type="text" value="amd"></td>
       <td><input class="inputCell" type="text" value="11"></td>
       <td><input class="inputCell" type="text" value="B12"></td>
     </tr>
     <tr>
       <td><input class="inputCell" type="text" value="2"></td>
       <td><input class="inputCell" type="text" value="ibm"></td>
       <td><input class="inputCell" type="text" value="22"></td>
       <td><input class="inputCell" type="text" value="Z23"></td>
     </tr>
     <tr>
       <td><input class="inputCell" type="text" value="3"></td>
       <td><input class="inputCell" type="text" value="digital"></td>
       <td><input class="inputCell" type="text" value="33"></td>
       <td><input class="inputCell" type="text" value="A49"></td>
     </tr>
     <tr>
       <td><input class="inputCell" type="text" value="4"></td>
       <td><input class="inputCell" type="text" value="apple"></td>
       <td><input class="inputCell" type="text" value="44"></td>
       <td><input class="inputCell" type="text" value="K12"></td>
     </tr>
     <tr>
       <td><input class="inputCell" type="text" value="5"></td>
       <td><input class="inputCell" type="text" value="rex"></td>
       <td><input class="inputCell" type="text" value="55"></td>
       <td><input class="inputCell" type="text" value="ascot"></td>
     </tr>
      <tbody>
    </table>
    <div class="buttonBar">
      <input class="inputButton" type="button" value="Submit" onclick="buttonClick(this)">
      <input class="inputButton" type="button" value="Cancel" onclick="buttonClick(this)">
    </div>
<script>
  function buttonClick(button) {
    if( button.value === "Submit" ) {

      var valuesAll = [];

      // Collect name details
      var tablename = document.getElementById("tableName");
      var myname = tablename.rows[0].cells[1].children[0].value
      var myphone = tablename.rows[1].cells[1].children[0].value
      var myemail = tablename.rows[2].cells[1].children[0].value
      var mydept = tablename.rows[3].cells[1].children[0].value

      valuesAll.push(myname);
      valuesAll.push(myphone);
      valuesAll.push(myemail);
      valuesAll.push(mydept);

      // collect row details
      var table = document.getElementById("tableRows");

      for( var i=1; i<table.rows.length; i++ ) {
        var row = table.rows[i];
        for( var j=0; j<row.cells.length; j++ ) {
          var cell = row.cells[j].firstChild.value;
          valuesAll.push(cell);
        }
      }
      google.script.run.addRows04(valuesAll);
      google.script.host.close();
    }
    else {
      if( confirm("Exit without saving?") ) google.script.host.close();
    }
  }
</script>
  </body>

Output screenshot


问:
Who brings up lvm volumes and how when booting?
I know the logical volumes info is saved in the lvm metadata, and the tools from lvm2 can be used to scan them out and setup the kernel DM by ioctl. I am curious that who does this work during booting so we can mount lv as rootfs, systemd?</p>

答:
I just found the answer by myself.
http://www.system-rescue-cd.org/lvm-guide-en/Booting-linux-from-LVM-volumes/

Quote the content from above link.

Here are the important steps involved in booting from LVM:

1.The BIOS executes the boot loader which is very often Grub

2.The boot loader has its own code for reading partitions and filesystems. So it knows how to read files from the /boot partition
  which contains the linux kernel image (vmlinuz-x.y.z) and the
  initramfs (initrd-x.y.z.gz). It first loads these two files into
  memory. Then it executes the kernel image and it tells the kernel
  where the initramfs is located in memory. The boot command line is
  also passed to the kernel. This command line contains the important
  parameters for the kernel such as root=/dev/volgroup/lvroot.

3.The linux kernel starts and executes its initialization code. Then it reads the initramfs from the memory. The contents is uncompressed
  into a new location in the memory.

4.The contents of the initramfs is now available. The program/script called init is now executed. This script which is specific to each
  linux distribution is responsible for finding the root filesystem.

5.If the LVM Physical Volumes are stored on the top of a RAID disk, the init program will first execute dmraid/mdadm to make this raid
  disk available.

6.Then the init script will run programs such as pvscan/vgscan/lvscan to detect the LVM volumes located on the disks The LVM volumes are not
  usable yet. They have to be activated first. This is done by vgchange
  --available y or vgchange -ay.

7.The init script reads the virtual file called /proc/cmdline to see what is the name of the root filesystem specified on the boot command
  line.

8.The root filesystem is mounted in a temporary directory such as /rootfs and other things such as /rootfs/proc and /rootfs/dev may also
  be mounted.

9.The initscript executes a chroot to /rootfs. This means that this directory becomes the new root for the processes which will be
  executed. When a process reads /bin/something it will read
  /rootfs/bin/something in reality.

10.The secondary init program, the one which is stored on the root filesystem is now executed and it finishes the initialization with an
  access to the real root filesystem.


问:
Python app to make a random prime number between 10^300 and 10^301
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

```<code>
import random , math
check_prime = 0</p>

<p>print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1<br>
    return True</p>

<p>while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break
```

答:
First things first:  Don't use math.pow(), as it is just a wrapper for the C floating-point function, and your numbers are WAY too big to be accurately represented as floats.  Use Python's exponentiation operator, which is **.

Second:  If you are on a platform which has a version of gmpy, use that for your primality testing.

Third:  As eumiro notes, you might be dealing with too big of a problem space for there to be any truly fast solution.

ContentLicense: CC BY-SA 3.0

Body:
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

import random , math
check_prime = 0

print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1

    return True

while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break


问:
node uri regex not capturing capture groups
I know there are a billion regex questions on stackoverflow, but I can't understand why my uri matcher isn't working in node.

I have the following:

```<code>var uri = "file:tmp.db?mode=ro"

function parseuri2db(uri){
    var regex = new RegExp("(?:file:)(.*)(?:\\?.*)");
    let dbname = uri.match(regex)
    return dbname
}
</code>```

I'm trying to identify only the database name, which I expect to be:

After an uncaptured file: group

Before an optional ? + parameters to end of string.

While I'm using:

```<code>var regex1 = new RegExp("(?:file:)(.*)(?:\\?.*)");
</code>```

I thought the answer was actually more like:

```<code>var regex2 = new RegExp("(?:file:)(.*)(?:\\??.*)");
</code>```

With a 0 or 1 ? quantifier on the \\? literal.  But the latter fails.

Anyway, my result is:

```<code>console.log(parseuri2db(conf.db_in.filename))

[ 'file:tmp.db?mode=ro',
  'tmp.db',
  index: 0,
  input: 'file:tmp.db?mode=ro' ]
</code>```

Which seems to be capturing the whole string in the first argument, rather than just the single capture group I asked for.

My questions are:

What am I doing wrong that I'm getting multiple captures?

How can I rephrase this to capture my capture groups with names?

I expected something like the following to work for (2):

```<code>function parseuri2db(uri){
  // var regex = new RegExp("(?:file:)(.*)(?:\\?.*)");
  // let dbname = uri.match(regex)
  var regex = new RegExp("(?<protocol>file:)(?<fname>.*)(<params>\\?.*)");
  let [, protocol, fname, params] = uri.match(regex)
  return dbname
  }
  console.log(parseuri2db(conf.db_in.filename))
</code>```

But:

```<code>  SyntaxError: Invalid regular expression: /(?<protocol>file:)(?<fname>.*)(<params>\?.*)/: Invalid group
</code>```

Update 1

Answer to my first question is that I needed to not capture the ? literal in the second capture group:

```<code>"(?:file:)([^?]*)(?:\\??.*)"
</code>```

答: That particular node regex library does not support groups.</p>

Body:
I know there are a billion regex questions on stackoverflow, but I can't understand why my uri matcher isn't working in node.

I have the following:

var uri = "file:tmp.db?mode=ro"

function parseuri2db(uri){
    var regex = new RegExp("(?:file:)(.*)(?:\\?.*)");
    let dbname = uri.match(regex)
    return dbname
}

I'm trying to identify only the database name, which I expect to be:

After an uncaptured file: group

Before an optional ? + parameters to end of string.

While I'm using:

var regex1 = new RegExp("(?:file:)(.*)(?:\\?.*)");

I thought the answer was actually more like:

var regex2 = new RegExp("(?:file:)(.*)(?:\\??.*)");

With a 0 or 1 ? quantifier on the \\? literal.  But the latter fails.

Anyway, my result is:

console.log(parseuri2db(conf.db_in.filename))

[ 'file:tmp.db?mode=ro',
  'tmp.db',
  index: 0,
  input: 'file:tmp.db?mode=ro' ]

Which seems to be capturing the whole string in the first argument, rather than just the single capture group I asked for.

My questions are:

What am I doing wrong that I'm getting multiple captures?

How can I rephrase this to capture my capture groups with names?

I expected something like the following to work for (2):

function parseuri2db(uri){
  // var regex = new RegExp("(?:file:)(.*)(?:\\?.*)");
  // let dbname = uri.match(regex)
  var regex = new RegExp("(?<protocol>file:)(?<fname>.*)(<params>\\?.*)");
  let [, protocol, fname, params] = uri.match(regex)
  return dbname
  }
  console.log(parseuri2db(conf.db_in.filename))

But:

  SyntaxError: Invalid regular expression: /(?<protocol>file:)(?<fname>.*)(<params>\?.*)/: Invalid group

Update 1

Answer to my first question is that I needed to not capture the ? literal in the second capture group:

"(?:file:)([^?]*)(?:\\??.*)"


问:
In-App Update API showing UPDATE_NOT_AVAILABLE while testing on debugging device
I am trying to integrate the new In-App Update API but I cannot able to test it's implementation. Seems like my code is fine therefore I read the Troubleshoots and am not able to understand 2 points in this document

Make sure that the app that you are testing is signed with the same signing key as the one available from Google Play.

How can I sign with same signing key in debug mode while installing Apk on Connected device?.

If the app you are testing doesn’t appear with an available update,
  check that you’ve properly set up your testing tracks.

Is it compulsory to release App in internal testing tracks to test implementation?

Anyway I just want to test on my device and I decremented the version code from the play store version but its showing always UPDATE_NOT_AVAILABLE.

Here is code:-

```<code>val appUpdateInfo: Task<AppUpdateInfo> = appUpdateManager.appUpdateInfo
appUpdateInfo.addOnSuccessListener {
    if (it.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE && it.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
        appUpdateManager.startUpdateFlowForResult(it, AppUpdateType.FLEXIBLE, this, 2);
    }else{
        toast("Not Available")
    }
}
</code>```

答:
First, you'd have to publish your app to Google Play. Make sure that:

The version code you published is higher than the one you're going to test the updates with, because if not, then it wouldn't recognize it as an update. Then let the Google Play refresh its cache for quite some time (in my case, I've waited for 12 hours before I was able to make it work for the first time).

You've signed both apks with the same signature.

If you want to have a working demo app, I've uploaded a git repository with a lower version code than the one that I've published in Google Play.

Body:
I am trying to integrate the new In-App Update API but I cannot able to test it's implementation. Seems like my code is fine therefore I read the Troubleshoots and am not able to understand 2 points in this document

Make sure that the app that you are testing is signed with the same signing key as the one available from Google Play.

How can I sign with same signing key in debug mode while installing Apk on Connected device?.

If the app you are testing doesn’t appear with an available update,
  check that you’ve properly set up your testing tracks.

Is it compulsory to release App in internal testing tracks to test implementation?

Anyway I just want to test on my device and I decremented the version code from the play store version but its showing always UPDATE_NOT_AVAILABLE.

Here is code:-

val appUpdateInfo: Task<AppUpdateInfo> = appUpdateManager.appUpdateInfo
appUpdateInfo.addOnSuccessListener {
    if (it.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE && it.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
        appUpdateManager.startUpdateFlowForResult(it, AppUpdateType.FLEXIBLE, this, 2);
    }else{
        toast("Not Available")
    }
}


问:
SVG as a CSS Background - Is there ANY way to repeat-x with NO space in between?
In Webkit and Blink-based browsers, SVGs do not tile correctly. There is a space between the images at various zoom levels. There are a number of topics on StackOverflow addressing this, all marked as solved, but those people must not have tested their solutions thoroughly enough.

My SVGs are a perfectly even number of pixels (130 x 24).
They have background-size set to 130px 24px.
They are set to preserveAspectRatio="none".
There is absolutely zero empty space on the edges of the SVG.

Yet, while it looks fine at 100%, there is still a thin space between the SVGs if you zoom in to the right level.

It surprises me this bug has not been reported before, given the widespread recommendations of using SVGs for backgrounds.

Here is the exact SVG:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
      viewBox="0 0 130 24" xml:space="preserve" preserveAspectRatio="none">

    <path class="st0" d="M0,12c32.5,0,32.5,12,65,12s32.5-12,65-12V0C97.5,0,92.9,12,65,12C32.5,12,20.7,0,0,0"/>
    </svg>```

I can confirm this behavior with other SVGs as well, such as the ones at https://www.heropatterns.com/

Codepen for testing: https://codepen.io/TelFiRE/pen/gJzqaG

The space between the images is usually sub 1 pixel (meaning the line is just a lighter shade of green). It's subtle and may be hard to see if you have a dull monitor.

In asking this question, I'm hoping to understand WHY it is occurring in a way that lets me make lots of repeating SVG backgrounds without issue. It's not just about the one image, so I want to avoid hacky solutions/workarounds if at all possible. For example, chopping 2 pixels off the edge fixes it 99% of the way, but not entirely, and it leaves me wondering what I would do if I actually needed those two pixels. This particular SVG looks okay like that but more complicated patterns would be knocked out of alignment.

答:
Each svg file has the following properties: "fill" and "stroke".
Fill is a fill, and stroke is a contour. This space is both, which is by default transparencies. Edit the SVG file and add it to  this code:

.st0 {
    fill: #A5EF8B;
    stroke: #A5EF8B;
    }

enter image description here

Body:
In Webkit and Blink-based browsers, SVGs do not tile correctly. There is a space between the images at various zoom levels. There are a number of topics on StackOverflow addressing this, all marked as solved, but those people must not have tested their solutions thoroughly enough.

My SVGs are a perfectly even number of pixels (130 x 24).
They have background-size set to 130px 24px.
They are set to preserveAspectRatio="none".
There is absolutely zero empty space on the edges of the SVG.

Yet, while it looks fine at 100%, there is still a thin space between the SVGs if you zoom in to the right level.

It surprises me this bug has not been reported before, given the widespread recommendations of using SVGs for backgrounds.

Here is the exact SVG:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
      viewBox="0 0 130 24" xml:space="preserve" preserveAspectRatio="none">

    <path class="st0" d="M0,12c32.5,0,32.5,12,65,12s32.5-12,65-12V0C97.5,0,92.9,12,65,12C32.5,12,20.7,0,0,0"/>
    </svg>

I can confirm this behavior with other SVGs as well, such as the ones at https://www.heropatterns.com/

Codepen for testing: https://codepen.io/TelFiRE/pen/gJzqaG

The space between the images is usually sub 1 pixel (meaning the line is just a lighter shade of green). It's subtle and may be hard to see if you have a dull monitor.

In asking this question, I'm hoping to understand WHY it is occurring in a way that lets me make lots of repeating SVG backgrounds without issue. It's not just about the one image, so I want to avoid hacky solutions/workarounds if at all possible. For example, chopping 2 pixels off the edge fixes it 99% of the way, but not entirely, and it leaves me wondering what I would do if I actually needed those two pixels. This particular SVG looks okay like that but more complicated patterns would be knocked out of alignment.


问:
UIAutomator - How to click the menu item
I have automated go to setting in android phone using UI Automator and i clicked the menu using "getUiDevice().pressMenu();" and its opened menu with 3 sub menu item and i want to click the second menu by using name or index or id , please help how to click the sub menu in Android UIAutomator ?</p>

答:
Use clazz method is working</p>

```<code> UiObject2 item = mDevice.findObject(By.clazz("android.widget.ListView"));
</code>```

Body:
Use clazz method is working

 UiObject2 item = mDevice.findObject(By.clazz("android.widget.ListView"));


问:
Android - How to reopen an app few seconds after it is minimized by the home button?
I need my application (minimized by the home button) to be active again on the screen after 10 seconds.

The idea is to always keep the application on the screen. If the user needs to leave my app (by home button), the app will quickly return to the screen.

Is it possible to show an application minimized by the user programmatically?

答:
Since you control the environment, Android has APIs for this use case:

https://developer.android.com/work/dpc/dedicated-devices/lock-task-mode?hl=en


问:
How to make it so your player can jump every n seconds
I want to run this every 2 seconds

i dont know how to make a timer :(

```<code>        {
            transform.Translate(0f, 10f * Time.deltaTime, 0f);
        }
</code>```

答:
May be this could help you:

Declare the Timer-type variable and initialize it with Timer object by passing 2   seconds interval time in constructor like this:

```<code> System.Timers.Timer aTimer = new System.Timers.Timer(2000);
</code>```

Create an event handler to handle the event raised by the Timer after every two seconds, like this:

```<code>public void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
    transform.Translate(0f, 10f * Time.deltaTime, 0f);
}
</code>```

Now, make the Timer's "Elapsed" property to point to the event handler you just created, like this:

```<code>aTimer.Elapsed += OnTimedEvent;
</code>```

Now, call the Start() method on aTimer object to start the timer, like this:

```<code>aTimer.Start();
</code>```

For more details, visit System.Timers (documentation)

Body:
I want to run this every 2 seconds

i dont know how to make a timer :(

        {
            transform.Translate(0f, 10f * Time.deltaTime, 0f);
        }

Body:
May be this could help you:

Declare the Timer-type variable and initialize it with Timer object by passing 2   seconds interval time in constructor like this:

 System.Timers.Timer aTimer = new System.Timers.Timer(2000);

Create an event handler to handle the event raised by the Timer after every two seconds, like this:

public void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
    transform.Translate(0f, 10f * Time.deltaTime, 0f);
}

Now, make the Timer's "Elapsed" property to point to the event handler you just created, like this:

aTimer.Elapsed += OnTimedEvent;

Now, call the Start() method on aTimer object to start the timer, like this:

aTimer.Start();

For more details, visit System.Timers (documentation)


问:
How to get play button to continue timer on Javascript?
Codepen

I am trying to simply get my play button to function but I don't know how. I got my pause button to work by adding clearInterval(timer) so I'm guessing I do the opposite of this?

I have tried adding countDown to to playTimer function and tick to the addEventListener but those don't work.

```<code>var startButton = document.getElementById("start");
var startSound = document.getElementById("audio");
var timerSound = document.getElementById("timer");
var counter = document.getElementById("counter");
var pausePlay = document.getElementsByClassName("pausePlay");
var pauseButton = document.getElementById("pause");
var playButton = document.getElementById('play');
var middleButtons = document.getElementsByClassName("middleButtons");
var fiveMin = document.getElementById("fiveMin");
var end = document.getElementById("endSess");
var redo = document.getElementById("redo");

function playAudio(){
    startSound.play();
}

// Start button will disappear after click and countDown method will begin
function startTimer(){
    startButton.style.display="none";
    counter.style.display = "";
    for (var i = 0; i < pausePlay.length; i++) {
        pausePlay[i].style.display = "block";
      }

    countDown(10);
}
// function play(){

// }

function countDown(minutes){
    var seconds = 60;
    var mins = minutes;
    function tick(){

        var current_minutes = mins - 1;
        seconds --;

        counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
        if(seconds > 0){
            timer = setTimeout(tick, 1);
        } else {
            if(mins > 1){
                countDown(mins - 1);
            }
            else if (mins && seconds === 0 ){
               timerSound.play();
               for (var i = 0; i < pausePlay.length; i++){
                pausePlay[i].style.display = "none";
                }
                options();
            }
        }
    }
    tick();
  }
// Pause timer
  function pauseTimer(){
    clearInterval(timer);

  }
// Continue timer
function playTimer(){
    countDown();
}

// Display buttons after timer is finished
  function options(){
    for(var i = 0; i < middleButtons.length; i++){
        middleButtons[i].style.display = "block";
    }
  }
// Add five minutes to Counter as countdown
  function fiveBreak (){
      countDown(5);
  }
// Restart counter to another 25 minutes
  function restartTimer(){
    countDown(25);
}

// Start from the beginning with the start timer
  function endSess(){
    for(var i = 0; i < middleButtons.length; i++){
        middleButtons[i].style.display = "none";
        counter.style.display = "none";
    }
     startButton.style.display = "";
  }

startButton.addEventListener('click', startTimer, playAudio);
pauseButton.addEventListener('click', pauseTimer, playAudio );
playButton.addEventListener('click', playTimer, playAudio );
fiveMin.addEventListener('click', fiveBreak );
end.addEventListener('click', endSess);
redo.addEventListener('click', restartTimer);
</code>```

答:
here this is simple code to use for a basic countdown timer, I let you add your unnotified "audio" part

```<code><h3 id="Count-Down">10</h3>
<select id="Count-times" >
  <option value="20">20</option>
  <option value="10" selected >10</option>
  <option value="5">5</option>
</select>
<button id="bt-Start">start</button>
<button id="bt-Pause" disabled >pause</button>
<button id="bt-Clear" disabled >clear</button>

</code>```

JS:

```<code>CountDown = {
  CountDown : document.querySelector('#Count-Down'),
  CountTime : document.querySelector('#Count-times'),
  btStart   : document.querySelector('#bt-Start'),
  btPause   : document.querySelector('#bt-Pause'),
  btClear   : document.querySelector('#bt-Clear'),

  DownTime  : 10 * 1000,
  interV    : 0,

  Init()
  {
    // just for clean start on reload page
    this.CountTime.value = 10;

    // select time
    this.CountTime.onchange =_=>{
      this.DownTime              = Number(this.CountTime.value) * 1000
      this.CountDown.textContent = this.CountTime.value
    }

    // buttons click event
    this.btStart.onclick =_=>{
      this.CountDownTime();
      this.CountTime.disabled = true;
      this.btStart.disabled   = true;
      this.btPause.disabled   = false;
      this.btClear.disabled   = false;
    }

    this.btPause.onclick =_=>{
      clearInterval( this.interV );

      this.btStart.disabled    = false;
      this.btPause.disabled    = true;
    }

    this.btClear.onclick =_=>{
      clearInterval( this.interV );

      this.DownTime              = 10 * 1000;
      this.CountTime.value       = 10;
      this.CountDown.textContent = 10;

      this.CountTime.disabled  = false;
      this.btStart.disabled    = false;
      this.btPause.disabled    = true;
      this.btClear.disabled    = true;
    }
  }, /// Init

  CountDownTime()
  {
    let D_End = new Date(Date.now() + this.DownTime );

    this.interV = setInterval(_=>{
      this.DownTime = D_End - (new Date(Date.now()));

      if (this.DownTime > 0) {
      // this.CountDown.textContent = Math.floor(this.DownTime / 1000) + '-' + (this.DownTime % 1000) ;
        this.CountDown.textContent = (this.DownTime / 1000).toFixed(2); ;
      }
      else {
        this.btClear.click();
      }
    }, 100);
  }
}

CountDown.Init();
</code>```

Body:
Codepen

I am trying to simply get my play button to function but I don't know how. I got my pause button to work by adding clearInterval(timer) so I'm guessing I do the opposite of this?

I have tried adding countDown to to playTimer function and tick to the addEventListener but those don't work.

var startButton = document.getElementById("start");
var startSound = document.getElementById("audio");
var timerSound = document.getElementById("timer");
var counter = document.getElementById("counter");
var pausePlay = document.getElementsByClassName("pausePlay");
var pauseButton = document.getElementById("pause");
var playButton = document.getElementById('play');
var middleButtons = document.getElementsByClassName("middleButtons");
var fiveMin = document.getElementById("fiveMin");
var end = document.getElementById("endSess");
var redo = document.getElementById("redo");

function playAudio(){
    startSound.play();
}

// Start button will disappear after click and countDown method will begin
function startTimer(){
    startButton.style.display="none";
    counter.style.display = "";
    for (var i = 0; i < pausePlay.length; i++) {
        pausePlay[i].style.display = "block";
      }

    countDown(10);
}
// function play(){

// }

function countDown(minutes){
    var seconds = 60;
    var mins = minutes;
    function tick(){

        var current_minutes = mins - 1;
        seconds --;

        counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
        if(seconds > 0){
            timer = setTimeout(tick, 1);
        } else {
            if(mins > 1){
                countDown(mins - 1);
            }
            else if (mins && seconds === 0 ){
               timerSound.play();
               for (var i = 0; i < pausePlay.length; i++){
                pausePlay[i].style.display = "none";
                }
                options();
            }
        }
    }
    tick();
  }
// Pause timer
  function pauseTimer(){
    clearInterval(timer);

  }
// Continue timer
function playTimer(){
    countDown();
}

// Display buttons after timer is finished
  function options(){
    for(var i = 0; i < middleButtons.length; i++){
        middleButtons[i].style.display = "block";
    }
  }
// Add five minutes to Counter as countdown
  function fiveBreak (){
      countDown(5);
  }
// Restart counter to another 25 minutes
  function restartTimer(){
    countDown(25);
}

// Start from the beginning with the start timer
  function endSess(){
    for(var i = 0; i < middleButtons.length; i++){
        middleButtons[i].style.display = "none";
        counter.style.display = "none";
    }
     startButton.style.display = "";
  }

startButton.addEventListener('click', startTimer, playAudio);
pauseButton.addEventListener('click', pauseTimer, playAudio );
playButton.addEventListener('click', playTimer, playAudio );
fiveMin.addEventListener('click', fiveBreak );
end.addEventListener('click', endSess);
redo.addEventListener('click', restartTimer);

Body:
here this is simple code to use for a basic countdown timer, I let you add your unnotified "audio" part

<h3 id="Count-Down">10</h3>
<select id="Count-times" >
  <option value="20">20</option>
  <option value="10" selected >10</option>
  <option value="5">5</option>
</select>
<button id="bt-Start">start</button>
<button id="bt-Pause" disabled >pause</button>
<button id="bt-Clear" disabled >clear</button>

JS:

CountDown = {
  CountDown : document.querySelector('#Count-Down'),
  CountTime : document.querySelector('#Count-times'),
  btStart   : document.querySelector('#bt-Start'),
  btPause   : document.querySelector('#bt-Pause'),
  btClear   : document.querySelector('#bt-Clear'),

  DownTime  : 10 * 1000,
  interV    : 0,

  Init()
  {
    // just for clean start on reload page
    this.CountTime.value = 10;

    // select time
    this.CountTime.onchange =_=>{
      this.DownTime              = Number(this.CountTime.value) * 1000
      this.CountDown.textContent = this.CountTime.value
    }

    // buttons click event
    this.btStart.onclick =_=>{
      this.CountDownTime();
      this.CountTime.disabled = true;
      this.btStart.disabled   = true;
      this.btPause.disabled   = false;
      this.btClear.disabled   = false;
    }

    this.btPause.onclick =_=>{
      clearInterval( this.interV );

      this.btStart.disabled    = false;
      this.btPause.disabled    = true;
    }

    this.btClear.onclick =_=>{
      clearInterval( this.interV );

      this.DownTime              = 10 * 1000;
      this.CountTime.value       = 10;
      this.CountDown.textContent = 10;

      this.CountTime.disabled  = false;
      this.btStart.disabled    = false;
      this.btPause.disabled    = true;
      this.btClear.disabled    = true;
    }
  }, /// Init

  CountDownTime()
  {
    let D_End = new Date(Date.now() + this.DownTime );

    this.interV = setInterval(_=>{
      this.DownTime = D_End - (new Date(Date.now()));

      if (this.DownTime > 0) {
      // this.CountDown.textContent = Math.floor(this.DownTime / 1000) + '-' + (this.DownTime % 1000) ;
        this.CountDown.textContent = (this.DownTime / 1000).toFixed(2); ;
      }
      else {
        this.btClear.click();
      }
    }, 100);
  }
}

CountDown.Init();


问:
MongoDB Stitch SDK returns "aggregation stage "$lookup" is not supported"
Is the latest Stitch not supporting $lookup? I'm using mongodb-stitch-server-sdk@4.3.2 and my server is on version 4.0.6. I have a query like the following:

```<code>const {
    Stitch,
    UserPasswordCredential,
    RemoteMongoClient
} = require('mongodb-stitch-server-sdk');

const client = Stitch.initializeDefaultAppClient('<APP ID>');
client.auth.loginWithCredential(new UserPasswordCredential("<username>","<password>")).then(user => {
    client.close();
}).catch(err => {
    console.log(err);
    client.close();
})

mongodb = client.getServiceClient(
  RemoteMongoClient.factory,
  "fleet-home")
testQuery =
  [{
    $match: {
      _id: "c1ba5c3f-263b-5748-9492-e50e0a39cb7a"
    }
  },
  {
    $lookup: {
      from: "aircraft",
      localField: "aircraft_id",
      foreignField: "_id",
      as: "aircraft"
    }
  }]

test = mongodb
.db("FleetDatabase")
.collection("fleet")
.aggregate(testQuery)
.asArray().then((success) => {
  console.log(success)
})

</code>```

However, I am getting an error of UnhandledPromiseRejectionWarning: StitchServiceError: aggregation stage "$lookup" is not supported

答:
You can create a Stitch function to do this, and call it directly from your stitch client var (which you have named client):

See: https://docs.mongodb.com/stitch/functions/define-a-function/

to create a function. If you run your function as a system user, then you have unrestricted access to MongoDB CRUD and aggregation operations:

See: https://docs.mongodb.com/stitch/authentication/#system-users

Then to call the function:

See: https://docs.mongodb.com/stitch/functions/call-a-function/

In your app it would be like:

```<code>client.callFunction('functionName', args).then(response => {...
</code>```

Body:
Is the latest Stitch not supporting $lookup? I'm using mongodb-stitch-server-sdk@4.3.2 and my server is on version 4.0.6. I have a query like the following:

const {
    Stitch,
    UserPasswordCredential,
    RemoteMongoClient
} = require('mongodb-stitch-server-sdk');

const client = Stitch.initializeDefaultAppClient('<APP ID>');
client.auth.loginWithCredential(new UserPasswordCredential("<username>","<password>")).then(user => {
    client.close();
}).catch(err => {
    console.log(err);
    client.close();
})

mongodb = client.getServiceClient(
  RemoteMongoClient.factory,
  "fleet-home")
testQuery =
  [{
    $match: {
      _id: "c1ba5c3f-263b-5748-9492-e50e0a39cb7a"
    }
  },
  {
    $lookup: {
      from: "aircraft",
      localField: "aircraft_id",
      foreignField: "_id",
      as: "aircraft"
    }
  }]

test = mongodb
.db("FleetDatabase")
.collection("fleet")
.aggregate(testQuery)
.asArray().then((success) => {
  console.log(success)
})

However, I am getting an error of UnhandledPromiseRejectionWarning: StitchServiceError: aggregation stage "$lookup" is not supported

Body:
You can create a Stitch function to do this, and call it directly from your stitch client var (which you have named client):

See: https://docs.mongodb.com/stitch/functions/define-a-function/

to create a function. If you run your function as a system user, then you have unrestricted access to MongoDB CRUD and aggregation operations:

See: https://docs.mongodb.com/stitch/authentication/#system-users

Then to call the function:

See: https://docs.mongodb.com/stitch/functions/call-a-function/

In your app it would be like:

client.callFunction('functionName', args).then(response => {...


问:
Swift Output Weekdays as Strings
I want to use an enum to convert integers to the String name of Weekdays. I have come up with the following

```<code>// Enum to output days
enum EnumDays : Int
{
    case MONDAY = 0
    case TUESDAY
    case WEDNESDAY
    case THURSDAY
    case FRIDAY
    case SATURDAY
    case SUNDAY
}

var weekDay = EnumDays.init(rawValue: 0)
print("Day = \(String(describing: weekDay))")
</code>```

But we output the type as in

"Day = Optional(SubscriptInSwift.EnumDays.MONDAY)"

how can I produce an output as a String i.e.:

"Day = Monday"

This question is a minimum example of a problem I have had for some time, and although this example is about weekdays I am looking for a solution of how to generally convert Integers to String.

答:
You just have to unwrap weekDay

```<code>print("Day = \(String(describing: weekDay!))")
</code>```

Title: Swift Output Weekdays as Strings

Body:
I want to use an enum to convert integers to the String name of Weekdays. I have come up with the following

// Enum to output days
enum EnumDays : Int
{
    case MONDAY = 0
    case TUESDAY
    case WEDNESDAY
    case THURSDAY
    case FRIDAY
    case SATURDAY
    case SUNDAY
}

var weekDay = EnumDays.init(rawValue: 0)
print("Day = \(String(describing: weekDay))")

But we output the type as in

"Day = Optional(SubscriptInSwift.EnumDays.MONDAY)"

how can I produce an output as a String i.e.:

"Day = Monday"

This question is a minimum example of a problem I have had for some time, and although this example is about weekdays I am looking for a solution of how to generally convert Integers to String.

Body:
You just have to unwrap weekDay

print("Day = \(String(describing: weekDay!))")


问:
Error "converting string to float" when using model.predict()
When I use model.predict(), the following error occurs,

ValueError: could not convert string to float:

One-hot encoding was used in my code as follows,

```<code>features_df = pd.get_dummies(df, columns=['garage_type', 'city'])
</code>```

The predict code used is given below.

```<code>sample = [["attached"], ["Richardport"]]
predictedvalue = model.predict(sample)'
</code>```

Any suggestions to solve this error? Thank you.

答:
The reason why you are getting an error is because you are sending strings to your model, while the model is expecting a vector of floats which is to be of the same shape as that of your training data.

From the code, it is clear that you are using one hot encoding before you use your data for training. You need to convert your sample also into the same one hot encoded vector format to get the answer.

Body:
When I use model.predict(), the following error occurs,

ValueError: could not convert string to float:

One-hot encoding was used in my code as follows,

features_df = pd.get_dummies(df, columns=['garage_type', 'city'])

The predict code used is given below.

sample = [["attached"], ["Richardport"]]
predictedvalue = model.predict(sample)'

Any suggestions to solve this error? Thank you.


问:
Show / hide columns dynamically using JavaScript does not function
My mission is to appear toggle JavaScript in my DataTables but it seems not function not only the button even the functions.

Here is my Code

HTML

```<code>  <div class="col-lg-12 col-md-12 col-sm-12 mb-30">
    <table class="data-table stripe hover multiple-select-row nowrap" id="example">
      <thead>
        <tr>
          <th class="table-plus datatable-nosort">No</th>
          <th>Name</th>
          <th>Phone</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="table-plus">1</td>
          <td>Michael</td>
          <td>123456789</td>
          <td>michael@gmail.com</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
</code>```

JS

```<code><script>
    $(function(){
        $.fn.bootstrapSwitch.defaults.onColor = 'success';
        $.fn.bootstrapSwitch.defaults.offColor = 'danger';
        $.fn.bootstrapSwitch.defaults.size = 'mini';
        $.fn.bootstrapSwitch.defaults.state = 'false';
        $.fn.bootstrapSwitch.defaults.inverse = 'true';
        $(".toggle-vis").bootstrapSwitch();
            var table = $('#example').DataTable();
        $('.toggle-vis').on('switchChange.bootstrapSwitch', function(event, state) {
            event.preventDefault();
            var column = table.column($(this).attr('data-column'));
            column.visible( ! column.visible() );
        });
    });
</script>
</code>```

I am trying to replicate someones code here JSFiddle unfortunately the toggle is not appear.

答:
you should add the toggle-vis element</p>

```<code><input
      type="checkbox"
      data-column="0"
      class="toggle-vis"
      data-label-text="ID"
      checked/>
    <input
      type="checkbox"
      data-column="1"
      class="toggle-vis"
      data-label-text="Name"
      checked>
    <input
      type="checkbox"
      data-column="2"
      class="toggle-vis"
      data-label-text="Position"
      checked/>
</code>```

Body:
My mission is to appear toggle JavaScript in my DataTables but it seems not function not only the button even the functions.

Here is my Code

HTML

          No
          Name
          Phone
          Email

          1
          Michael
          123456789
          michael@gmail.com

JS

I am trying to replicate someones code here JSFiddle unfortunately the toggle is not appear.

Body:
you should add the toggle-vis element

<input
      type="checkbox"
      data-column="0"
      class="toggle-vis"
      data-label-text="ID"
      checked/>
    <input
      type="checkbox"
      data-column="1"
      class="toggle-vis"
      data-label-text="Name"
      checked>
    <input
      type="checkbox"
      data-column="2"
      class="toggle-vis"
      data-label-text="Position"
      checked/>


问:
My if statement conditions are not triggering properly despite the conditions being met
I'm learning how to program with Python by taking up small projects to get myself familiarized. I'm stuck on a tiny problem in which my if statement is not being triggered properly despite the conditions being met during the programs execution. this is the dice simulation project I made on my own.

I could not think of any additional methods at this time since I'm still a novice but learning as i'm going

```<code>import random
import time

print("Welcome to the dice simulator, lets find out how lucky you are!")

"\n"

min = 1
max = 6

roll = input("Do you want to play? ")

while roll == "yes" or roll == "y" or roll == "Yes" or roll == "Y":

    print("Now rolling both dice....")
    time.sleep(1)
    print("calculating....")
    time.sleep(3)

    print(random.randint(min, max))
    print(random.randint(min, max))

    if min == max: #This if condition does not work even if the dice match. Needs work.
        print("Amazing! You scored a double!")
    else: #This else condition works regardless of the outcome.
        print("Oof! Might wanna keep trying!")

    roll_again = input("Roll again? y/n: ")
    if roll_again == "n" or roll_again == "no" or roll_again == "No" or roll_again == "N":
        print("Goodbye!")
        break
    # else:
    #     print("Invalid answer")
    #     break
</code>```

If the if condition is met, a message will print congratulating the user for scoring a double number such as 1,1 or 6,6 for example. If the dice does not show matching number's, the else condition will print a message telling the user to better luck next time.

答:
TRY:-

```<code>import os
import datetime

directory = r'C:\Users\vasudeos\OneDrive\Desktop\Test Folder'
extensions = (['.jpg', '.jpeg', '.png']);
import random
import time

print("Welcome to the dice simulator, lets find out how lucky you are!")

"\n"

min = 1
max = 6

roll = input("Do you want to play? ")

while roll == "yes" or roll == "y" or roll == "Yes" or roll == "Y":

    print("Now rolling both dice....")
    time.sleep(1)
    print("calculating....")
    time.sleep(3)

    min1 = random.randint(min, max)
    max1 = random.randint(min, max)

    print("{}\n{}".format(min1, max1))

    if min1 == max1: #This if condition does not work even if the dice match. Needs work.
        print("Amazing! You scored a double!")
    else: #This else condition works regardless of the outcome.
        print("Oof! Might wanna keep trying!")

    roll_again = input("Roll again? y/n: ")
    if roll_again == "n" or roll_again == "no" or roll_again == "No" or roll_again == "N":
        print("Goodbye!")
        break
</code>```

As others have pointed, variables min and max have constant values (1, 6) throughout the execution of the program, and since their values aren't the same, and don't even change if min == max will always be false.

Body:
I'm learning how to program with Python by taking up small projects to get myself familiarized. I'm stuck on a tiny problem in which my if statement is not being triggered properly despite the conditions being met during the programs execution. this is the dice simulation project I made on my own.

I could not think of any additional methods at this time since I'm still a novice but learning as i'm going

import random
import time

print("Welcome to the dice simulator, lets find out how lucky you are!")

"\n"

min = 1
max = 6

roll = input("Do you want to play? ")

while roll == "yes" or roll == "y" or roll == "Yes" or roll == "Y":

    print("Now rolling both dice....")
    time.sleep(1)
    print("calculating....")
    time.sleep(3)

    print(random.randint(min, max))
    print(random.randint(min, max))

    if min == max: #This if condition does not work even if the dice match. Needs work.
        print("Amazing! You scored a double!")
    else: #This else condition works regardless of the outcome.
        print("Oof! Might wanna keep trying!")

    roll_again = input("Roll again? y/n: ")
    if roll_again == "n" or roll_again == "no" or roll_again == "No" or roll_again == "N":
        print("Goodbye!")
        break
    # else:
    #     print("Invalid answer")
    #     break

If the if condition is met, a message will print congratulating the user for scoring a double number such as 1,1 or 6,6 for example. If the dice does not show matching number's, the else condition will print a message telling the user to better luck next time.

Body:
TRY:-

import os
import datetime

directory = r'C:\Users\vasudeos\OneDrive\Desktop\Test Folder'
extensions = (['.jpg', '.jpeg', '.png']);
import random
import time

print("Welcome to the dice simulator, lets find out how lucky you are!")

"\n"

min = 1
max = 6

roll = input("Do you want to play? ")

while roll == "yes" or roll == "y" or roll == "Yes" or roll == "Y":

    print("Now rolling both dice....")
    time.sleep(1)
    print("calculating....")
    time.sleep(3)

    min1 = random.randint(min, max)
    max1 = random.randint(min, max)

    print("{}\n{}".format(min1, max1))

    if min1 == max1: #This if condition does not work even if the dice match. Needs work.
        print("Amazing! You scored a double!")
    else: #This else condition works regardless of the outcome.
        print("Oof! Might wanna keep trying!")

    roll_again = input("Roll again? y/n: ")
    if roll_again == "n" or roll_again == "no" or roll_again == "No" or roll_again == "N":
        print("Goodbye!")
        break

As others have pointed, variables min and max have constant values (1, 6) throughout the execution of the program, and since their values aren't the same, and don't even change if min == max will always be false.


问:
How to convert multiple d3.csv data into number?
right now after loading csv file I am looping each object within an array and converting one by one.

which looks like

```<code>fulldata.forEach(function(data){
      data.healthcare = +data.healthcare;
      data.a = +data.a;
      data.b = +data.b;
      data.c = +data.c;
    })
</code>```

assume there are about 100 feature that you need to convert into number, is there a way that convert multiple feature into number at once?

答:
You can use Object.keys() to get an array of features.

```<code>fulldata.forEach(function(data) {
  Object.keys(data).forEach(function(key) {
    data[key] = +data.key;
  });
})
</code>```

Body:
right now after loading csv file I am looping each object within an array and converting one by one.

which looks like

fulldata.forEach(function(data){
      data.healthcare = +data.healthcare;
      data.a = +data.a;
      data.b = +data.b;
      data.c = +data.c;
    })

assume there are about 100 feature that you need to convert into number, is there a way that convert multiple feature into number at once?

Body:
You can use Object.keys() to get an array of features.

fulldata.forEach(function(data) {
  Object.keys(data).forEach(function(key) {
    data[key] = +data.key;
  });
})