问:
Receive error when I installing gcutil in MacOS
I followed the instructions given by the official documents, but stuck in executing ./install.sh.

MacOS version:10.14.5 (18F132)
Python version:python2.7

After I download the zip file given by the gcloud website, I run the command ./install.sh.It told me

```<code>weiziyangdeMacBook-Pro:google-cloud-sdk weiziyang$ ./install.sh
Welcome to the Google Cloud SDK!
ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512
Traceback (most recent call last):
  File "/Users/weiziyang/google-cloud-sdk/bin/bootstrapping/install.py", line 12, in <module>
    import bootstrapping
  File "/Users/weiziyang/google-cloud-sdk/bin/bootstrapping/bootstrapping.py", line 32, in <module>
    import setup  # pylint:disable=g-import-not-at-top
  File "/Users/weiziyang/google-cloud-sdk/bin/bootstrapping/setup.py", line 55, in <module>
    from googlecloudsdk.core import properties
  File "/Users/weiziyang/google-cloud-sdk/lib/googlecloudsdk/core/properties.py", line 27, in <module>
    from googlecloudsdk.core import config
  File "/Users/weiziyang/google-cloud-sdk/lib/googlecloudsdk/core/config.py", line 29, in <module>
    from googlecloudsdk.core.util import files as file_utils
  File "/Users/weiziyang/google-cloud-sdk/lib/googlecloudsdk/core/util/files.py", line 600, in <module>
    class Checksum(object):
  File "/Users/weiziyang/google-cloud-sdk/lib/googlecloudsdk/core/util/files.py", line 603, in Checksum
    def __init__(self, algorithm=hashlib.sha256):
AttributeError: 'module' object has no attribute 'sha256'
</code>```

I checked the module of python2, it provided that I haved installed hashlib correctly and has the attribute 'sha256'

```<code>weiziyangdeMacBook-Pro:google-cloud-sdk weiziyang$ python2
Python 2.7.10 (default, Feb 22 2019, 21:55:15)
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib
>>> hashlib.sha256
<built-in function openssl_sha256>
>>> exit()

</code>```

I expect it can be installed correctly.

答:
This is what I've done
Go to /usr/local/Cellar/ and remove all python folder except python@3.x.x then run ./install.sh again and then it will work.

Body:
I followed the instructions given by the official documents, but stuck in executing ./install.sh.

MacOS version:10.14.5 (18F132)
Python version:python2.7

After I download the zip file given by the gcloud website, I run the command ./install.sh.It told me

weiziyangdeMacBook-Pro:google-cloud-sdk weiziyang$ ./install.sh
Welcome to the Google Cloud SDK!
ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512
Traceback (most recent call last):
  File "/Users/weiziyang/google-cloud-sdk/bin/bootstrapping/install.py", line 12, in <module>
    import bootstrapping
  File "/Users/weiziyang/google-cloud-sdk/bin/bootstrapping/bootstrapping.py", line 32, in <module>
    import setup  # pylint:disable=g-import-not-at-top
  File "/Users/weiziyang/google-cloud-sdk/bin/bootstrapping/setup.py", line 55, in <module>
    from googlecloudsdk.core import properties
  File "/Users/weiziyang/google-cloud-sdk/lib/googlecloudsdk/core/properties.py", line 27, in <module>
    from googlecloudsdk.core import config
  File "/Users/weiziyang/google-cloud-sdk/lib/googlecloudsdk/core/config.py", line 29, in <module>
    from googlecloudsdk.core.util import files as file_utils
  File "/Users/weiziyang/google-cloud-sdk/lib/googlecloudsdk/core/util/files.py", line 600, in <module>
    class Checksum(object):
  File "/Users/weiziyang/google-cloud-sdk/lib/googlecloudsdk/core/util/files.py", line 603, in Checksum
    def __init__(self, algorithm=hashlib.sha256):
AttributeError: 'module' object has no attribute 'sha256'

I checked the module of python2, it provided that I haved installed hashlib correctly and has the attribute 'sha256'

weiziyangdeMacBook-Pro:google-cloud-sdk weiziyang$ python2
Python 2.7.10 (default, Feb 22 2019, 21:55:15)
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib
>>> hashlib.sha256
<built-in function openssl_sha256>
>>> exit()

I expect it can be installed correctly.


来源: stackexchange

问:
Macro for text-to-columns
I'm trying to write a code to do the following:

Using text-to-columns,the data should get divided in different columns.
The data in Cells A1-A8 is like this:

This data should appear in different columns.

答:
You can build the FieldInfo parameter dynamically by building out the string. In the example below, there are 10 resultant columns. The For loop builds the sFieldInfo variable, and specifies all the columns in Text format.</p>

```<code>sComma = ""
sFieldInfo = ""
For x = 1 To 10
    sFieldInfo = sFieldInfo & sComma & " Array(" & x & ", xlTextFormat)"
    sComma = ","
Next x

Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.TextToColumns Destination:=Range("J5"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar:="/", _
    TrailingMinusNumbers:=True, _
    FieldInfo:=Array(sFieldInfo)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Macro for text-to-columns

Body:
You can build the FieldInfo parameter dynamically by building out the string. In the example below, there are 10 resultant columns. The For loop builds the sFieldInfo variable, and specifies all the columns in Text format.

sComma = ""
sFieldInfo = ""
For x = 1 To 10
    sFieldInfo = sFieldInfo & sComma & " Array(" & x & ", xlTextFormat)"
    sComma = ","
Next x

Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.TextToColumns Destination:=Range("J5"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar:="/", _
    TrailingMinusNumbers:=True, _
    FieldInfo:=Array(sFieldInfo)


问:
is there a way to return last file in the subfolders when using PowerShell
I have PowerShell script and i want to return multiple folders based on their positional using a wile card ex. sqlfile*\table i get-childitems -recurse. Thank you</p>

答:
"I want to return the newest and last file which is in the end of the
  last subfolder."

Is this what you are going for based on your comment above?

```<code>Get-ChildItem -Recurse -Path D:\Temp -Directory

# Results
<#
    Directory: D:\Temp

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        06-May-20     20:30                AddressFiles
d-----        17-Feb-20     15:50                est
d-----        14-Mar-20     17:03                here
d-----        26-May-20     10:38                hold
d-----        06-May-20     20:30                LogFiles
d-----        06-Feb-20     14:56                NewFolder
d-----        12-Feb-20     14:24                ParentFolder
d-----        03-Feb-20     11:55                Reference
d-----        06-Feb-20     14:56                Source
d-----        24-Feb-20     22:03                Target
d-----        22-May-20     20:51                Zips

    Directory: D:\Temp\NewFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        03-Feb-20     11:55                New folder
d-----        20-Jan-20     11:17                temp

    Directory: D:\Temp\ParentFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        12-Feb-20     14:08                ChildFolder

    Directory: D:\Temp\ParentFolder\ChildFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        12-Feb-20     14:08                GrandchildFolder
#>

Get-ChildItem -Recurse -Path D:\Temp -Directory |
Select-Object -Last 1

# Results
<#
    Directory: D:\Temp\ParentFolder\ChildFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        12-Feb-20     14:08                GrandchildFolder
#>

(Get-ChildItem -Recurse -Path D:\Temp -Directory |
Select-Object -Last 1).Fullname

# Results

<#
D:\Temp\ParentFolder\ChildFolder\GrandchildFolder
#>

$LastSubFolder = (Get-ChildItem -Recurse -Path D:\Temp -Directory |
Select-Object -Last 1).Fullname

Get-ChildItem -Path $LastSubFolder

# Results
<#
    Directory: D:\Temp\ParentFolder\ChildFolder\GrandchildFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        28-Aug-07     13:08        2646058 GrandchildThumperLong.wav
-a----        28-Aug-07     13:05         683670 GrandchildThumperShort.wav
-a----        23-Apr-99     18:22         668440 GrandchildWELCOM98.WAV
#>

Get-ChildItem -Path $LastSubFolder | Sort-Object -Property LastWriteTime

# Results
<#
    Directory: D:\Temp\ParentFolder\ChildFolder\GrandchildFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        23-Apr-99     18:22         668440 GrandchildWELCOM98.WAV
-a----        28-Aug-07     13:05         683670 GrandchildThumperShort.wav
-a----        28-Aug-07     13:08        2646058 GrandchildThumperLong.wav
#>

Get-ChildItem -Path $LastSubFolder | Sort-Object -Property LastWriteTime |
Select-Object -First 1 -Last 1

# Results
<#

    Directory: D:\Temp\ParentFolder\ChildFolder\GrandchildFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        23-Apr-99     18:22         668440 GrandchildWELCOM98.WAV
-a----        28-Aug-07     13:08        2646058 GrandchildThumperLong.wav

#>
</code>```

Body:
"I want to return the newest and last file which is in the end of the
  last subfolder."

Is this what you are going for based on your comment above?

Get-ChildItem -Recurse -Path D:\Temp -Directory

# Results
<#
    Directory: D:\Temp

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        06-May-20     20:30                AddressFiles
d-----        17-Feb-20     15:50                est
d-----        14-Mar-20     17:03                here
d-----        26-May-20     10:38                hold
d-----        06-May-20     20:30                LogFiles
d-----        06-Feb-20     14:56                NewFolder
d-----        12-Feb-20     14:24                ParentFolder
d-----        03-Feb-20     11:55                Reference
d-----        06-Feb-20     14:56                Source
d-----        24-Feb-20     22:03                Target
d-----        22-May-20     20:51                Zips

    Directory: D:\Temp\NewFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        03-Feb-20     11:55                New folder
d-----        20-Jan-20     11:17                temp

    Directory: D:\Temp\ParentFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        12-Feb-20     14:08                ChildFolder

    Directory: D:\Temp\ParentFolder\ChildFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        12-Feb-20     14:08                GrandchildFolder
#>

Get-ChildItem -Recurse -Path D:\Temp -Directory |
Select-Object -Last 1

# Results
<#
    Directory: D:\Temp\ParentFolder\ChildFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        12-Feb-20     14:08                GrandchildFolder
#>

(Get-ChildItem -Recurse -Path D:\Temp -Directory |
Select-Object -Last 1).Fullname

# Results

<#
D:\Temp\ParentFolder\ChildFolder\GrandchildFolder
#>

$LastSubFolder = (Get-ChildItem -Recurse -Path D:\Temp -Directory |
Select-Object -Last 1).Fullname

Get-ChildItem -Path $LastSubFolder

# Results
<#
    Directory: D:\Temp\ParentFolder\ChildFolder\GrandchildFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        28-Aug-07     13:08        2646058 GrandchildThumperLong.wav
-a----        28-Aug-07     13:05         683670 GrandchildThumperShort.wav
-a----        23-Apr-99     18:22         668440 GrandchildWELCOM98.WAV
#>

Get-ChildItem -Path $LastSubFolder | Sort-Object -Property LastWriteTime

# Results
<#
    Directory: D:\Temp\ParentFolder\ChildFolder\GrandchildFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        23-Apr-99     18:22         668440 GrandchildWELCOM98.WAV
-a----        28-Aug-07     13:05         683670 GrandchildThumperShort.wav
-a----        28-Aug-07     13:08        2646058 GrandchildThumperLong.wav
#>

Get-ChildItem -Path $LastSubFolder | Sort-Object -Property LastWriteTime |
Select-Object -First 1 -Last 1

# Results
<#

    Directory: D:\Temp\ParentFolder\ChildFolder\GrandchildFolder

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        23-Apr-99     18:22         668440 GrandchildWELCOM98.WAV
-a----        28-Aug-07     13:08        2646058 GrandchildThumperLong.wav

#>


问:
Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'
I am using windows 10 command line for a django project using python34 however, I am facing difficulties with SQL.

I have already installed mysqlclient using pip install mysqlclient==1.3.5 and located the file to make sure I was not delusional. I then ran python manage.py migrate to migrate the tables to the SQL database (I am using phpmyadmin). However when the command returned with...

```<code> File "C:\Users\user\env\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?
</code>```

I am aware that questions like these already exist, but not one solution seems to have made any impact on attempts.

答:
This command did the trick from @Aniket Sinha's answer above:

pip install mysqlclient

Body:
I am using windows 10 command line for a django project using python34 however, I am facing difficulties with SQL.

I have already installed mysqlclient using pip install mysqlclient==1.3.5 and located the file to make sure I was not delusional. I then ran python manage.py migrate to migrate the tables to the SQL database (I am using phpmyadmin). However when the command returned with...

 File "C:\Users\user\env\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?

I am aware that questions like these already exist, but not one solution seems to have made any impact on attempts.


问:
How to get row count from Different Databases. Database Names, Schema Names and Table Names, stored in SQL Table
I have table that contains Database, Schema, and Table Name. I would like to count the row for each rows using group by for defined column in Same Table. </p>

```<code>DECLARE @WeeklyRowCount TABLE
(
    db VARCHAR(50)
    ,sch VARCHAR(15)
    ,Tb VARCHAR(100)
    ,col VARCHAR(50)
)

DECLARE @cmd VARCHAR(MAX) = (
SELECT ' UNION ALL SELECT COUNT(*) AS C, DATE_STAMP,'''
     + QUOTENAME(sch) + '.' + QUOTENAME(tb)
    + ''' AS T FROM ' + QUOTENAME(db) + '.' + QUOTENAME(sch) + '.' + QUOTENAME(tb) + 'GROUP BY col'
    FROM @WeeklyRowCount )

SELECT COUNT(*) AS C, col ,'Table name' AS T FROM db.sch.tb GROUP BY col
</code>```

<p>I have tried to use dynamic SQL but due to limitation of 8000 character, full query is not showing up. </p>

答:
You can use undocumented stored procedure sp_msforeachtable to run against each table in the database, to get the row count. But, as it is undocumented stored procedure, in future, it might be removed.

From your question, I understand you want rowcount at table level. The below code generates row count at table level and inserts into table.

CREATE table WeeklyRowCount
(
    db VARCHAR(50)
    ,sch VARCHAR(15)
    ,Tb VARCHAR(120)
    ,rcnt VARCHAR(50)
)

exec sp_MSforeachtable ' INSERT INTO WeeklyRowCount(db,sch,tb,col) SELECT db_name() as db,OBJECT_SCHEMA_NAME(OBJECT_ID(''?'')) as sch, ''?'' as tb, count(1) as rcnt  from ? '

SELECT * FROM WeeklyRowCount
```

<p>If you want to run it againt different databases, Use three part identifier for the table containing rowcount <code>WeeklyRowcount</code></p>

<pre class="lang-sql prettyprint-override"><code>USE dbName
GO
CREATE table WeeklyRowCount
(
    db VARCHAR(50)
    ,sch VARCHAR(15)
    ,Tb VARCHAR(120)
    ,rcnt VARCHAR(50)
)

USE DbName1
go

exec sp_MSforeachtable ' INSERT INTO dbname.dbo.WeeklyRowCount(db,sch,tb,col) SELECT db_name() as db,OBJECT_SCHEMA_NAME(OBJECT_ID(''?'')) as sch, ''?'' as tb, count(1) as rcnt  from ? '

use DbName2
go

exec sp_MSforeachtable ' INSERT INTO dbname.dbo.WeeklyRowCount(db,sch,tb,col) SELECT db_name() as db,OBJECT_SCHEMA_NAME(OBJECT_ID(''?'')) as sch, ''?'' as tb, count(1) as rcnt  from ? '

SELECT * FROM dbname.dbo.WeeklyRowCount
</code>```

For more information about sp_msforeachtable

Body:
I have table that contains Database, Schema, and Table Name. I would like to count the row for each rows using group by for defined column in Same Table.

DECLARE @WeeklyRowCount TABLE
(
    db VARCHAR(50)
    ,sch VARCHAR(15)
    ,Tb VARCHAR(100)
    ,col VARCHAR(50)
)

DECLARE @cmd VARCHAR(MAX) = (
SELECT ' UNION ALL SELECT COUNT(*) AS C, DATE_STAMP,'''
     + QUOTENAME(sch) + '.' + QUOTENAME(tb)
    + ''' AS T FROM ' + QUOTENAME(db) + '.' + QUOTENAME(sch) + '.' + QUOTENAME(tb) + 'GROUP BY col'
    FROM @WeeklyRowCount )

SELECT COUNT(*) AS C, col ,'Table name' AS T FROM db.sch.tb GROUP BY col

I have tried to use dynamic SQL but due to limitation of 8000 character, full query is not showing up.

Body:
You can use undocumented stored procedure sp_msforeachtable to run against each table in the database, to get the row count. But, as it is undocumented stored procedure, in future, it might be removed.

From your question, I understand you want rowcount at table level. The below code generates row count at table level and inserts into table.

CREATE table WeeklyRowCount
(
    db VARCHAR(50)
    ,sch VARCHAR(15)
    ,Tb VARCHAR(120)
    ,rcnt VARCHAR(50)
)

exec sp_MSforeachtable ' INSERT INTO WeeklyRowCount(db,sch,tb,col) SELECT db_name() as db,OBJECT_SCHEMA_NAME(OBJECT_ID(''?'')) as sch, ''?'' as tb, count(1) as rcnt  from ? '

SELECT * FROM WeeklyRowCount

If you want to run it againt different databases, Use three part identifier for the table containing rowcount WeeklyRowcount

USE dbName
GO
CREATE table WeeklyRowCount
(
    db VARCHAR(50)
    ,sch VARCHAR(15)
    ,Tb VARCHAR(120)
    ,rcnt VARCHAR(50)
)

USE DbName1
go

exec sp_MSforeachtable ' INSERT INTO dbname.dbo.WeeklyRowCount(db,sch,tb,col) SELECT db_name() as db,OBJECT_SCHEMA_NAME(OBJECT_ID(''?'')) as sch, ''?'' as tb, count(1) as rcnt  from ? '

use DbName2
go

exec sp_MSforeachtable ' INSERT INTO dbname.dbo.WeeklyRowCount(db,sch,tb,col) SELECT db_name() as db,OBJECT_SCHEMA_NAME(OBJECT_ID(''?'')) as sch, ''?'' as tb, count(1) as rcnt  from ? '

SELECT * FROM dbname.dbo.WeeklyRowCount

For more information about sp_msforeachtable


问:
How to integrate png/jpeg files to an unity mobile app project
I'm trying to develop an geography quiz mobile app with Unity. So I need to display images of country flags and four different answers and integrate that images(png/jpeg) in my project. My questions is how can I do that? Would you recommend me to implement a server for that and get them via REST-Requests or just add all country flags to a folder in my project and grab them from there? If so how can I let these images display with four different answer opportunities?

I would appreciate if you could tell me how you would develop that kind of an app with Unity.
Thanks!

答:
Put all flag images in the sprites folder. Now create a script and attach it to your UI component in Unity and in that script add a public array variable images of type Sprite.

```<code>public Image question1;
public Image question2;
public Image question3;
public Image question4;
public Sprite[] images;
</code>```

Now attach all the images you have to this public variable through Unity.

So whenever you a display a question, load the sprites to each question component according to index of the images.

```<code>public void setFlags(int indexOfFlag1,int indexOfFlag2,int indexOfFlag3,int indexOfFlag4){
    question1.sprite = images[indexOfFlag1];
    question2.sprite = images[indexOfFlag2];
    question3.sprite = images[indexOfFlag3];
    question4.sprite = images[indexOfFlag4];
}
</code>```

Body:
Put all flag images in the sprites folder. Now create a script and attach it to your UI component in Unity and in that script add a public array variable images of type Sprite.

public Image question1;
public Image question2;
public Image question3;
public Image question4;
public Sprite[] images;

Now attach all the images you have to this public variable through Unity.

So whenever you a display a question, load the sprites to each question component according to index of the images.

public void setFlags(int indexOfFlag1,int indexOfFlag2,int indexOfFlag3,int indexOfFlag4){
    question1.sprite = images[indexOfFlag1];
    question2.sprite = images[indexOfFlag2];
    question3.sprite = images[indexOfFlag3];
    question4.sprite = images[indexOfFlag4];
}


问:
Why does Javascript give me a uncaught type null error?
I'm having some trouble with my Javscript for a project (Its own document we're not allowed to use inline JS) my only that I can find while attempting to execute my program is this </p>

<p>"payment.js:182 Uncaught TypeError: Cannot set property 'onsubmit' of null
    at init (payment.js:182)". </p>

<p>Now this error does not show up on JSHint when I verify my code so I don't understand how to fix it, it would be great if someone could give me some help. Heres the code: </p>

```<code>"use strict";

//validate form inputs from payment.html
function validate() {

    var errMsg = "";
    var result = true;      //assumes no errors

    //assign elements to variables
    var mastercard_check = document.getElementById("mastercard").checked;
    var visa_check = document.getElementById("visa").checked;
    var express_check = document.getElementById("express").checked;
    var credit_name = document.getElementById("credit_name").value;
    var credit_number = document.getElementById("credit_number").value;
    var credit_expiry = document.getElementById("credit_expiry").value;
    var credit_vv = document.getElementById("credit_vv").value;

    //validations for form
    if (!(mastercard_check || visa_check || express_check)) {
        errMsg += "Please choose a card type\n";
        result = false;
    }

    if (credit_name.length > 40) {
        errMsg += "Please enter a name for your credit card between 1-40 characters\n";
        result = false;
    }
    else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
        errMsg += "Credit card name can only contain alpha characters\n";
        result = false;
    }

    if (isNaN(credit_number)) {
        errMsg = errMsg + "Credit card number must contain digits only\n";
        result = false;
    }
    else if (credit_number.length < 15 || credit_number.length > 16){
        errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
        result = false;
    }
    else {
        var tempMsg = checkCardNumber(credit_number);
        if (tempMsg != "") {
            errMsg += tempMsg;
            result = false;
        }
    }

    if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
        errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
        result = false;
    }

    if (!credit_vv) {
        errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
        result = false;
    }

    if (errMsg != "") {
        alert(errMsg);
    }

    return result;
}

//obtain the credit card type
function getCardType() {

    var cardType = "Unknown";
    var cardArray = document.getElementById("credit_type").getElementsByTagName("input");

    for(var i = 0; i < cardArray.length; i++) {
        if (cardArray[i].checked) {
            cardType = cardArray[i].value;
        }
    }
    return cardType;

}

//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
    var errMsg = "";
    var card = getCardType();
    switch(card) {
        case "visa":
            if (!(credit_number.length == 16)) {
                errMsg = "Visa number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(4).*$/)) {
                errMsg = "Visa number must start with a 4. \n";
            }
            break;
        case "mastercard":
            if (!(credit_number.length == 16)) {
                errMsg = "Mastercard number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
                errMsg = "Mastercard number must start with digits 51 through 55. \n";
            }
            break;
        case "express":
            if (!(credit_number.length == 15)) {
                errMsg = "American Express number must contian 15 digits\n";
            }
            else if (!credit_number.match(/^(34|37).*$/)) {
                errMsg = "American Express number must start with 34 or 37. \n";
            }
            break;
    }
    return errMsg;
}

//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
    var cost = 0;
    if (size.search("three") != -1) cost = 100;
    if (size.search("four")!= -1) cost += 150;
    if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
    var cost = 0;
    if(sessionStorage.firstname != undefined){
        document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;

    document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;

    document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;

    document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;

    document.getElementById("confirm_package").textContent = sessionStorage.package;

    document.getElementById("confirm_size").textContent = sessionStorage.size;

    document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
        cost = calcCost(sessionStorage.size, sessionStorage.quantity);

        document.getElementById("firstname").value = sessionStorage.firstname;
    document.getElementById("lastname").value = sessionStorage.lastname;
    document.getElementById("street").value = sessionStorage.street;
      document.getElementById("suburb").value = sessionStorage.suburb;
      document.getElementById("state").value = sessionStorage.state;
      document.getElementById("postcode").value = sessionStorage.postcode;
      document.getElementById("phone").value = sessionStorage.phone;
      document.getElementById("email").value = sessionStorage.email;
      document.getElementById("preferred").value = sessionStorage.preferred;
      document.getElementById("deal").value = sessionStorage.deal;
      document.getElementById("quality").value = sessionStorage.quality;
      document.getElementById("quantity").value = sessionStorage.quantity;
      document.getElementById("extrabags").value = sessionStorage.extrabags;
      document.getElementById("accomodation").value = sessionStorage.accomodation;
      document.getElementById("travel").value = sessionStorage.travel;
    document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
    document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
    }

}

function cancelBooking() {
window.location = "index.html";
}

function init() {

    getInfo();
    var payment = document.getElementById("payment");
    payment.onsubmit = validate;
    var cancel = document.getElementById("cancel");
    cancel.onclick = cancelBooking;
  }

window.onload = init;
</code>```

答: It might be that the ID at var payment = document.getElementById("payment"); is wrong and JS can't find it, also if you are calling some function you should do it like this payment.onsubmit = validate(); check that the ID is correct.

Body:
I'm having some trouble with my Javscript for a project (Its own document we're not allowed to use inline JS) my only that I can find while attempting to execute my program is this

"payment.js:182 Uncaught TypeError: Cannot set property 'onsubmit' of null
    at init (payment.js:182)".

Now this error does not show up on JSHint when I verify my code so I don't understand how to fix it, it would be great if someone could give me some help. Heres the code:

"use strict";

//validate form inputs from payment.html
function validate() {

    var errMsg = "";
    var result = true;      //assumes no errors

    //assign elements to variables
    var mastercard_check = document.getElementById("mastercard").checked;
    var visa_check = document.getElementById("visa").checked;
    var express_check = document.getElementById("express").checked;
    var credit_name = document.getElementById("credit_name").value;
    var credit_number = document.getElementById("credit_number").value;
    var credit_expiry = document.getElementById("credit_expiry").value;
    var credit_vv = document.getElementById("credit_vv").value;

    //validations for form
    if (!(mastercard_check || visa_check || express_check)) {
        errMsg += "Please choose a card type\n";
        result = false;
    }

    if (credit_name.length > 40) {
        errMsg += "Please enter a name for your credit card between 1-40 characters\n";
        result = false;
    }
    else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
        errMsg += "Credit card name can only contain alpha characters\n";
        result = false;
    }

    if (isNaN(credit_number)) {
        errMsg = errMsg + "Credit card number must contain digits only\n";
        result = false;
    }
    else if (credit_number.length < 15 || credit_number.length > 16){
        errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
        result = false;
    }
    else {
        var tempMsg = checkCardNumber(credit_number);
        if (tempMsg != "") {
            errMsg += tempMsg;
            result = false;
        }
    }

    if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
        errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
        result = false;
    }

    if (!credit_vv) {
        errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
        result = false;
    }

    if (errMsg != "") {
        alert(errMsg);
    }

    return result;
}

//obtain the credit card type
function getCardType() {

    var cardType = "Unknown";
    var cardArray = document.getElementById("credit_type").getElementsByTagName("input");

    for(var i = 0; i < cardArray.length; i++) {
        if (cardArray[i].checked) {
            cardType = cardArray[i].value;
        }
    }
    return cardType;

}

//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
    var errMsg = "";
    var card = getCardType();
    switch(card) {
        case "visa":
            if (!(credit_number.length == 16)) {
                errMsg = "Visa number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(4).*$/)) {
                errMsg = "Visa number must start with a 4. \n";
            }
            break;
        case "mastercard":
            if (!(credit_number.length == 16)) {
                errMsg = "Mastercard number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
                errMsg = "Mastercard number must start with digits 51 through 55. \n";
            }
            break;
        case "express":
            if (!(credit_number.length == 15)) {
                errMsg = "American Express number must contian 15 digits\n";
            }
            else if (!credit_number.match(/^(34|37).*$/)) {
                errMsg = "American Express number must start with 34 or 37. \n";
            }
            break;
    }
    return errMsg;
}

//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
    var cost = 0;
    if (size.search("three") != -1) cost = 100;
    if (size.search("four")!= -1) cost += 150;
    if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
    var cost = 0;
    if(sessionStorage.firstname != undefined){
        document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;

    document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;

    document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;

    document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;

    document.getElementById("confirm_package").textContent = sessionStorage.package;

    document.getElementById("confirm_size").textContent = sessionStorage.size;

    document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
        cost = calcCost(sessionStorage.size, sessionStorage.quantity);

        document.getElementById("firstname").value = sessionStorage.firstname;
    document.getElementById("lastname").value = sessionStorage.lastname;
    document.getElementById("street").value = sessionStorage.street;
      document.getElementById("suburb").value = sessionStorage.suburb;
      document.getElementById("state").value = sessionStorage.state;
      document.getElementById("postcode").value = sessionStorage.postcode;
      document.getElementById("phone").value = sessionStorage.phone;
      document.getElementById("email").value = sessionStorage.email;
      document.getElementById("preferred").value = sessionStorage.preferred;
      document.getElementById("deal").value = sessionStorage.deal;
      document.getElementById("quality").value = sessionStorage.quality;
      document.getElementById("quantity").value = sessionStorage.quantity;
      document.getElementById("extrabags").value = sessionStorage.extrabags;
      document.getElementById("accomodation").value = sessionStorage.accomodation;
      document.getElementById("travel").value = sessionStorage.travel;
    document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
    document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
    }

}

function cancelBooking() {
window.location = "index.html";
}

function init() {

    getInfo();
    var payment = document.getElementById("payment");
    payment.onsubmit = validate;
    var cancel = document.getElementById("cancel");
    cancel.onclick = cancelBooking;
  }

window.onload = init;


问:
How to load elements into a string array
I have the following code to display filenames in a gridview. the variable filename contains the filenames that are present in a folder. now i want to store these filename values into a string array for further usage.

'Displaying files from a folder onto a gridview

```<code>   Dim inqueuePath As String = "C:\Users\Desktop\Sample"
   Dim fileInfo() As String
   Dim rowint As Integer = 0
   Dim name As String
   Dim directoryInfo As New System.IO.DirectoryInfo(inqueuePath)
fileInfo = System.IO.Directory.GetFiles(inqueuePath)

  With TaskGrid
    .Columns.Add("Column 0", "TaskName")
    .AutoResizeColumns()
 End With

For Each name In fileInfo
    ConfigWindow.TaskGrid.Rows.Add()
    Dim filename As String = System.IO.Path.GetFileName(name)
    ConfigWindow.TaskGrid.Item(0, rowint).Value = filename
    rowint = rowint + 1
Next
</code>```

Any suggestions please?

答:
As Stevo3000 points out in his comment, fileInfo already is a string array.

The Directory.GetFiles Method (String) returns the names of files (including their paths) in the specified directory.

You can find more details here on MSDN.

ContentLicense: CC BY-SA 3.0

Body:
I have the following code to display filenames in a gridview. the variable filename contains the filenames that are present in a folder. now i want to store these filename values into a string array for further usage.

'Displaying files from a folder onto a gridview

   Dim inqueuePath As String = "C:\Users\Desktop\Sample"
   Dim fileInfo() As String
   Dim rowint As Integer = 0
   Dim name As String
   Dim directoryInfo As New System.IO.DirectoryInfo(inqueuePath)
fileInfo = System.IO.Directory.GetFiles(inqueuePath)

  With TaskGrid
    .Columns.Add("Column 0", "TaskName")
    .AutoResizeColumns()
 End With

For Each name In fileInfo
    ConfigWindow.TaskGrid.Rows.Add()
    Dim filename As String = System.IO.Path.GetFileName(name)
    ConfigWindow.TaskGrid.Item(0, rowint).Value = filename
    rowint = rowint + 1
Next

Any suggestions please?


问:
Cordova ios with wkwebview plugin - window.open(url, "_system") doesn't work
I can't open links externally on system browser.

Cordova version 9.0.0 (cordova-lib@9.0.1)

Active plugins:

```<code>"cordova-ios": "^5.1.1",
"cordova-plugin-keyboard": "1.2.0",
"cordova-plugin-splashscreen": "^5.0.3",
"cordova-plugin-wkwebview-engine": "^1.2.1"
</code>```

My noteworthy lines on config.xml

```<code>    <access origin="*" />
    <allow-navigation href="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />

    <feature name="CDVWKWebViewEngine">
        <param name="ios-package" value="CDVWKWebViewEngine" />
    </feature>
    <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
    <preference name="KeyboardDisplayRequiresUserAction" value="false" />
    <preference name="BackupWebStorage" value="local"/>
</code>```

I've tried with:

```<code>window.open(url, "_self")
window.open(url, "_blank")
window.open(url, "_system")
</code>```

But the only function that works and returns something in console is the one with "_self" arg.
I've tried with HTML tag:

```<code><a href="http://url" target="_system">foo</a>
</code>```

But it doesn't work as well.

Trying to find out the source of the problem, it's seems to me there is somewhere a bug on the implementation of the wkwebview plugin on the ios's WebKit WebView, maybe related with the recent changes apported by Apple to avoid the deploying of UIWebView-based apps and ios sdk <13 on the App Store

答:
I spent a few hours trying to get this to work. I found a work-around for the issue with the @zestia/cordova-plugin-wkwebview-engine-windowopen plugin.

Add to your project using:

cordova plugins add @zestia/cordova-plugin-wkwebview-engine-windowopen

Body:
I can't open links externally on system browser.

Cordova version 9.0.0 (cordova-lib@9.0.1)

Active plugins:

"cordova-ios": "^5.1.1",
"cordova-plugin-keyboard": "1.2.0",
"cordova-plugin-splashscreen": "^5.0.3",
"cordova-plugin-wkwebview-engine": "^1.2.1"

My noteworthy lines on config.xml

    <access origin="*" />
    <allow-navigation href="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />

    <feature name="CDVWKWebViewEngine">
        <param name="ios-package" value="CDVWKWebViewEngine" />
    </feature>
    <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
    <preference name="KeyboardDisplayRequiresUserAction" value="false" />
    <preference name="BackupWebStorage" value="local"/>

I've tried with:

window.open(url, "_self")
window.open(url, "_blank")
window.open(url, "_system")

But the only function that works and returns something in console is the one with "_self" arg.
I've tried with HTML tag:

foo

But it doesn't work as well.

Trying to find out the source of the problem, it's seems to me there is somewhere a bug on the implementation of the wkwebview plugin on the ios's WebKit WebView, maybe related with the recent changes apported by Apple to avoid the deploying of UIWebView-based apps and ios sdk <13 on the App Store


问:
Where to put the Lhost and port number| python
i have an assignment i have no perior knowledge to use argparse. pls help where to put the hostip and port number

Error:

```<code>usage: server.py [-h] -a HOST -p PORT
server.py: error: the following arguments are required: -a/--host, -p/--port
</code>```

piece of code

```<code>import argparse, sys
import signal
from socket import *

parser = argparse.ArgumentParser(description='Simple test')
parser.add_argument('-a', '--host', help='set lhost', required=True)
parser.add_argument('-p', '--port', help='set lport', required=True)
args = vars(parser.parse_args())

host = args['host']
port = int(args['port'])
print('\n\n\n')
print('[+] SERVER IP:', host)
print('[+] SERVER HOST:', port)
</code>```

答:
Arguments are parsed when you start the command:

```<code>python3 your_program.py -a 'your_host' -p 5000
</code>```

Output:

```<code>[+] SERVER IP: your_host
[+] SERVER HOST: 5000
</code>```

Body:
i have an assignment i have no perior knowledge to use argparse. pls help where to put the hostip and port number

Error:

usage: server.py [-h] -a HOST -p PORT
server.py: error: the following arguments are required: -a/--host, -p/--port

piece of code

import argparse, sys
import signal
from socket import *

parser = argparse.ArgumentParser(description='Simple test')
parser.add_argument('-a', '--host', help='set lhost', required=True)
parser.add_argument('-p', '--port', help='set lport', required=True)
args = vars(parser.parse_args())

host = args['host']
port = int(args['port'])
print('\n\n\n')
print('[+] SERVER IP:', host)
print('[+] SERVER HOST:', port)

Body:
Arguments are parsed when you start the command:

python3 your_program.py -a 'your_host' -p 5000

Output:

[+] SERVER IP: your_host
[+] SERVER HOST: 5000


问:
Couchbase: Cannot perform operations on a shutdown bucket
I am getting this error when try to insert 2M objects via node.js into Couchbase. 1M works fine.

C:\Users\Administrator\Desktop\node_modules\couchbase\lib\bucket.js:
  728 throw new Error('cannot perform operations on a shutdown bucket');

I am using Couchbase 3.0.1, node.js 2.0.2 SDK.

This is the code:

```<code>     var Couchbase = require('couchbase');

var myCluster = new Couchbase.Cluster('couchbase://10.0.0.103,10.0.0.102,10.0.0.101,');

var myBucket = myCluster.openBucket('rre');

   for (var i = 0;i<1000000;i++)
   {

    myBucket.insert('dwhtryrdue_'+i,  {
    "guid": "003dddbf-da50-46d4-a2aa-319677b5d2be",
    "CampaignID": 22,
    "ZoneID": 29,
    "AdvertiserID": 30,
    "BannerID": 36,
    "UserID": 32,
    "ClickIP": "Bette",
    "ClickHost": "Jerry",
    "ClickReferringURL": "Dejesus",
    "ClickDateTime": "2014-06-09T12:53:22 -00:00",
    "ClickCountry": "Central African Republic",
    "ClickState": "Kentucky",
    "ClickBrowser": "Chrome"
    }, function(err, res) {

    });

    }
</code>```

答:
You need to authenticate using USERNAME and PASSWORD, incase you setup a custom cluster.
So, in the code ...

```<code>var myCluster = new Couchbase.Cluster('couchbase://10.0.0.103,10.0.0.102,10.0.0.101,');
myCluster.authenticate('Administrator', 'adminadmin'); // Add this credential

var myBucket = myCluster.openBucket('rre');
</code>```

By default, the USERNAME is Administrator and PASSWORD will be the cluster password(adminadmin, in my case).

P.S.-This solution is in particular to Error: cannot perform operations on a shutdown bucket

Body:
I am getting this error when try to insert 2M objects via node.js into Couchbase. 1M works fine.

C:\Users\Administrator\Desktop\node_modules\couchbase\lib\bucket.js:
  728 throw new Error('cannot perform operations on a shutdown bucket');

I am using Couchbase 3.0.1, node.js 2.0.2 SDK.

This is the code:

     var Couchbase = require('couchbase');

var myCluster = new Couchbase.Cluster('couchbase://10.0.0.103,10.0.0.102,10.0.0.101,');

var myBucket = myCluster.openBucket('rre');

   for (var i = 0;i<1000000;i++)
   {

    myBucket.insert('dwhtryrdue_'+i,  {
    "guid": "003dddbf-da50-46d4-a2aa-319677b5d2be",
    "CampaignID": 22,
    "ZoneID": 29,
    "AdvertiserID": 30,
    "BannerID": 36,
    "UserID": 32,
    "ClickIP": "Bette",
    "ClickHost": "Jerry",
    "ClickReferringURL": "Dejesus",
    "ClickDateTime": "2014-06-09T12:53:22 -00:00",
    "ClickCountry": "Central African Republic",
    "ClickState": "Kentucky",
    "ClickBrowser": "Chrome"
    }, function(err, res) {

    });

    }

Body:
You need to authenticate using USERNAME and PASSWORD, incase you setup a custom cluster.
So, in the code ...

var myCluster = new Couchbase.Cluster('couchbase://10.0.0.103,10.0.0.102,10.0.0.101,');
myCluster.authenticate('Administrator', 'adminadmin'); // Add this credential

var myBucket = myCluster.openBucket('rre');

By default, the USERNAME is Administrator and PASSWORD will be the cluster password(adminadmin, in my case).

P.S.-This solution is in particular to Error: cannot perform operations on a shutdown bucket


问:
Is there a decoder for Here Api TPEGOpenLRBase64 Code?
For my master thesis I am writing a reference implementation in Java. It uses HERE Api to obtain traffic incident information. The XML received contains a TPEGOpenLRBase64 code.
TomTom provides an open standard with which a OpenLRBase64 code can be decoded and the location can be transferred to the routing database (https://github.com/tomtom-international/openlr) (https://www.openlr-association.com/method.html).
However, this decoder does not work for the OpenLR code provided by HERE. According to their own statements, they use TPEG OLR / OpenLR for encoding and decoding.
Do any of you know a reference implementation or a GitHub project that uses this decoder? Unfortunately I have not found anything online.

Perhaps someone could also explain to me why there seem to be two open standards. According to the OpenLR Association, TomTom works with TISA (https://www.openlr-association.com/openlr-association.html). HERE informed me that they were using a TISA based TPEG OLR encoder to encode the location. Isn't the TomTom OpenLR standard the official TISA standard?

答:
The difference between TISA OLR and TomTom OpenLR relates to the history of the specification: TomTom submitted the OpenLR specification to TISA. It was adopted in a slightly modified form by TISA as part 22 of the TISA SP14006 (TPEG2) standard series. The TISA standard was later in turn adopted without modifications as ISO 21219-22:2017.

In the TISA standard the abbreviation OLR (OpenLR Location Referencing) is used to describe this location referencing method.

As part of the adoption by TISA the standard was modified to be in line with the conventions and rules used in the TPEG2 series of standards. The concepts and the information in the references are the same, but the TISA version uses some different field names and the binary and XML representations are slightly different from those found in the TomTom OpenLR version. This means there are now two versions of the standard that are not interoperable at the binary or XML level.

The implementation in the Location Library follows the TISA OLR (and thus also ISO 21219-22:2017) specification for marshalling and unmarshalling of OLR References. Whenever we use the terms OLR or OpenLR we refer to the TISA OLR version of the standard.


问:
c# constructor injection and constructor overloads
I'm using constructor injection for the first time and wish to write my code defensively.

Therefore if I have a class with a constructor and a save method as below:

```<code>public SomeConstructor(string name, Object someObject)
{
  _name= name;
  _someObject= someObject;
}

public void Save()
{
  // Does a database save
}
</code>```

But then need to create another related method in this Class that doesn't need the _someObject so I create an overloaded chained constructor as:

```<code>public SomeConstructor(string name) : this(name, null)
{
}
</code>```

How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?

I'm not using an injection tool.

Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.

What I wanted to avoid was a series of validation checks at the start of each method.

答:
Use the friction you are experiencing as a warning system. It's really telling you that you're likely moving towards low cohesion and violation of the Single Responsibility Principle.

If this is the case, refactor the class into two separate classes.

Body:
I'm using constructor injection for the first time and wish to write my code defensively.

Therefore if I have a class with a constructor and a save method as below:

public SomeConstructor(string name, Object someObject)
{
  _name= name;
  _someObject= someObject;
}

public void Save()
{
  // Does a database save
}

But then need to create another related method in this Class that doesn't need the _someObject so I create an overloaded chained constructor as:

public SomeConstructor(string name) : this(name, null)
{
}

How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?

I'm not using an injection tool.

Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.

What I wanted to avoid was a series of validation checks at the start of each method.


问:
CSS center span positioned as absolute
I have a span positioned as absolute inside a div (with top and left values set). The span is connected to user input and when the user inputs text the span exands with the given text towards the right to contain the text, but I'd like it to grow in both sides, which means when user inputs a word of 7 characters, the character in order #4 should be in the exact center.

Is there anyway to achieve this in pure CSS? or a way to mutate the value of left using JS but with decent accuracy.

答:
You could use flexbox, or text-align to do this but if you're tied to absolute positioning then there's ways to do that too:

  Centered Text

```

This will put the top left corner of the  at the center of the
 then move the  half left and half up putting it in the center of the

Title: CSS center span positioned as absolute

Body:
You could use flexbox, or text-align to do this but if you're tied to absolute positioning then there's ways to do that too:

<div>
  <span>Centered Text</span>
</div>

<style>

div {
  position: relative;
  width: 200px;
  height: 40px;
  border: 1px solid black;
}

span {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

</style>

This will put the top left corner of the <span> at the center of the <div> then move the <span> half left and half up putting it in the center of the <div>


问:
Johansen test for cointegration in R
I am building a VAR model. As far as I understood by reading different articles in Internet, I need first to check stationarity. By using the adf.test I found out that the data that I have is not stationary. So the next step would be to check a cointegration relationship. I did it using Johansen-Procedure Unit Root / Cointegration Test.

jo_eigen <- ca.jo(Canada, type="trace",ecdet="trend",spec="transitory")

The first hypothesis,r=0, tests for the presence of cointegration shows that there is cointegration. Would it be correct to use VAR model for forecast in this case?

Thank you!
BR
Anna

答: Since there is statistical evidence that there is a cointegration relationship you should use a VEC model in order to take advantage of the relation between the time series.</p>

Title: Johansen test for cointegration in R


问:
Front end of the notary in cordapp-samples
I want to set up the UI for the notary in cordApp samples. As the notary's Web port is not configured by default,I am trying to change the client's Gradle file to configure the notary.

Is there any other way to configure the notary's UI ?

I checked,It can be seen through the Node Explorer.Is there any other way to check the notary on web front?

答:
You can configure the notary's webport in a similar way as you would configure for any other node.
Your notary must have an RPC address configured.
Once you have an rpc address configured, you can either use the default corda webserver (which is now deprecated) or you must configure your own webserver or use spring-webserver).
Without specifying the web port you can define your spring boot server, and connect to the node via RPC.

Step 1 Define your Spring boot server

```<code>@SpringBootApplication
private open class Starter

    /**
     * Starts our Spring Boot application.
     */
    fun main(args: Array<String>) {
        val app = SpringApplication(Starter::class.java)
        app.setBannerMode(Banner.Mode.OFF)
        app.isWebEnvironment = true
        app.run(*args)
    }
</code>```

Step 2 Start your server by defining a starter task in your gradle build file

```<code>task runPartyAServer(type: JavaExec) {
    classpath = sourceSets.main.runtimeClasspath
    main = 'net.corda.server.ServerKt'
}
</code>```

Step 3 Define the rpc configuration used to connect to the node.

```<code>server.port=10055
config.rpc.username=user1
config.rpc.password=test
config.rpc.host=localhost
config.rpc.port=10008
</code>```

Step 4 Connect to the node using the above config defined.

```<code> val rpcAddress = NetworkHostAndPort(host, rpcPort)
 val rpcClient = CordaRPCClient(rpcAddress)
 val rpcConnection = rpcClient.start(username, password)
 proxy = rpcConnection.proxy
</code>```

Step 5 Use the proxy to connect to the notary node.

You can refer to the complete code here.

Body:
You can configure the notary's webport in a similar way as you would configure for any other node.
Your notary must have an RPC address configured.
Once you have an rpc address configured, you can either use the default corda webserver (which is now deprecated) or you must configure your own webserver or use spring-webserver).
Without specifying the web port you can define your spring boot server, and connect to the node via RPC.

Step 1 Define your Spring boot server

@SpringBootApplication
private open class Starter

    /**
     * Starts our Spring Boot application.
     */
    fun main(args: Array<String>) {
        val app = SpringApplication(Starter::class.java)
        app.setBannerMode(Banner.Mode.OFF)
        app.isWebEnvironment = true
        app.run(*args)
    }

Step 2 Start your server by defining a starter task in your gradle build file

task runPartyAServer(type: JavaExec) {
    classpath = sourceSets.main.runtimeClasspath
    main = 'net.corda.server.ServerKt'
}

Step 3 Define the rpc configuration used to connect to the node.

server.port=10055
config.rpc.username=user1
config.rpc.password=test
config.rpc.host=localhost
config.rpc.port=10008

Step 4 Connect to the node using the above config defined.

 val rpcAddress = NetworkHostAndPort(host, rpcPort)
 val rpcClient = CordaRPCClient(rpcAddress)
 val rpcConnection = rpcClient.start(username, password)
 proxy = rpcConnection.proxy

Step 5 Use the proxy to connect to the notary node.

You can refer to the complete code here.


问:
Docker run -p ?/? (what are this two port numbers and what they represents )
I used command "docker run -p 8080/8080 --name my_local_image ...." and it failed saying Unable to find image '8080/8080:latest' locally

8080/8080 = what this two port represents exactly ?

答:
Replace this " -p 8080/8080 " by this " -p 8080:8080 "

The first port : the Docker host ( you can use this port to access to your container) to access to the container from the outside.

the second one : is the port used by your application.

Example : I want to run tomcat server in a docker container, the default port of tomcat is 8080 and I want to expose my docker on port 9000 so i have to write :

```<code>docker run -p 9000:8080 --name myTomcatContainer tomcat
</code>```

So with this configuration I can access to Tomcat from outside using :
http://host-ip:9000

Body:
Replace this " -p 8080/8080 " by this " -p 8080:8080 "

The first port : the Docker host ( you can use this port to access to your container) to access to the container from the outside.

the second one : is the port used by your application.

Example : I want to run tomcat server in a docker container, the default port of tomcat is 8080 and I want to expose my docker on port 9000 so i have to write :

docker run -p 9000:8080 --name myTomcatContainer tomcat

So with this configuration I can access to Tomcat from outside using :
http://host-ip:9000


问:
Does Anyone know which all fields in an X.509 certificate is used for authenticating the digital signature?
I'm trying validate an X.509 certificate received over a network. I have understood that the digital signature is created by creating a message digest of the fields(don't know which fields) in the signature and then encrypting it using the CA(Certificate Authority) private Key.We can validate the certificate by decrypting the digital signature using CA public key and comparing it with the message digest of the certificate fields.

I'm stuck at this point as I don't know which all fields I should take to create the message digest for the validation. Can somebody please help me out

答:
From a glance at the RFC it appears to be the whole tbsCertificate field.

[...] a digital signature computed upon
the ASN.1 DER encoded tbsCertificate.  The ASN.1 DER encoded
tbsCertificate is used as the input to the signature function.


问:
tf.reduce_mean is not working in tf.function
code below

@tf.function

def train_step(self, batch):

```<code>with tf.GradientTape() as disc_tape, tf.GradientTape() as infe_tape, tf.GradientTape() as gener_tape:
  loss_encoder, loss_decoder, loss_disc = self.compute_loss(batch)

  grad_encoder = gener_tape.gradient(loss_encoder, self.model.inference_net.trainable_variables)
  grad_decoder = infe_tape.gradient(loss_decoder, self.model.generative_net.trainable_variables)
  grad_disc = disc_tape.gradient(loss_disc, self.model.discriminator.trainable_variables)

  self.infe_optimizer.apply_gradients(zip(grad_encoder, self.model.inference_net.trainable_variables))
  self.genr_optimizer.apply_gradients(zip(grad_decoder, self.model.generative_net.trainable_variables))
  self.disc_optimizer.apply_gradients(zip(grad_disc, self.model.discriminator.trainable_variables))

  return loss_encoder, loss_decoder, loss_disc
</code>```

@tf.function

def train(self, epoch):

```<code>loss_history = tf.zeros([3,0])
for batch in self.train_dataset:
  loss_encoder, loss_decoder, loss_disc = self.train_step(batch)
  loss_each = tf.expand_dims(tf.stack([loss_encoder, loss_decoder, loss_disc], axis=0), 1)
  loss_history = tf.concat([loss_history, loss_each], axis=1)

mean_loss_encoder, mean_loss_decoder, mean_loss_disc = tf.reduce_mean(loss_history, axis=1)
tf.summary.scalar('encoder loss', data=mean_loss_encoder, step=epoch, description='train_loss')
tf.summary.scalar('decoder loss', data=mean_loss_decoder, step=epoch, description='train_loss')
tf.summary.scalar('discriminator loss', data=mean_loss_disc, step=epoch, description='train_loss')
print('encoder training loss %.5f' % mean_loss_encoder, 'decoder training loss %.5f' % mean_loss_decoder, 'discriminator training loss %.5f' % mean_loss_disc)
</code>```

@tf.function

def validation_step(self, batch):
     return self.compute_loss(batch, training=tf.constant(False, tf.bool))

@tf.function

def validation(self, epoch):
    '''produce mean loss for epoch and append to self.val_loss_monior'''

```<code>loss_history = tf.zeros([3,0])
for batch in self.validation_dataset:
    loss_encoder, loss_decoder, loss_disc = self.validation_step(batch)
    loss_each = tf.expand_dims(tf.concat([loss_encoder, loss_decoder, loss_disc], axis=0), 1)
    loss_history = tf.concat([loss_history, loss_each], axis=1)
mean_loss_each = tf.reduce_mean(loss_history, axis=1)
print('encoder validation loss %.5f' % mean_loss_each[0], 'decoder validation loss %.5f' % mean_loss_each[1], 'discriminator validation loss %.5f' % mean_loss_each[2])

tf.summary.scalar('encoder loss', data=mean_loss_each[0], step=epoch, description='val_loss')
tf.summary.scalar('decoder loss', data=mean_loss_each[1], step=epoch, description='val_loss')
tf.summary.scalar('discriminator loss', data=mean_loss_each[2], step=epoch, description='val_loss')

# self.val_loss_monior: (3, self.patience), each row store history loss for each network
loss_each = tf.expand_dims(mean_loss_each, 1)
if epoch + 1 > self.patience:
  is_less =  self.val_loss_monior < loss_each
  is_less_encoder, is_less_decoder, is_less_discriminator = list(map(lambda x: tf.raw_ops.Any(input=tf.cast(tf.squeeze(x), tf.bool), axis=0), tf.split(is_less, 3, axis=0)))

  if not is_less_encoder:
     self.infe_optimizer.learning_rate *= self.decay_rate
  if not is_less_decoder:
     self.genr_optimizer.learning_rate *= self.decay_rate
  if not is_less_discriminator:
     self.disc_optimizer.learning_rate *= self.decay_rate

self.val_loss_monior = tf.slice(self.val_loss_monior, [0, 1], [3, self.patience - 1])
self.val_loss_monior = tf.concat([self.val_loss_monior, loss_each], axis=1)

tf.summary.scalar('encoder learning rate', data=self.infe_optimizer.learning_rate, step=epoch)
tf.summary.scalar('decoder learning rate', data=self.genr_optimizer.learning_rate, step=epoch)
tf.summary.scalar('discriminator learning rate', data=self.disc_optimizer.learning_rate, step=epoch)
</code>```

@tf.function

def fit(self):

```<code>self.val_loss_monitor = tf.zeros([3, self.patience])
for epoch in range(self.epochs):
  start = time.time()
  epoch = tf.cast(epoch, tf.int64)
  self.train(epoch)
  self.validation(epoch)

  print ('Time for epoch {} is {} sec'.format(epoch, time.time()-start))
  display.clear_output(wait=True)
  if (epoch + 1) % 5 == 0:
    self.generate_images(epoch)
</code>```

error massage below

OperatorNotAllowedInGraphError: in user code:

```<code><ipython-input-5-8af39e045349>:152 fit  *
    self.train(epoch)
<ipython-input-5-8af39e045349>:90 train  *
    mean_loss_encoder, mean_loss_decoder, mean_loss_disc = tf.reduce_mean(loss_history, axis=1)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:561 __iter__
    self._disallow_iteration()
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:554 _disallow_iteration
    self._disallow_when_autograph_enabled("iterating over `tf.Tensor`")
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:532 _disallow_when_autograph_enabled
    " decorating it directly with @tf.function.".format(task))

OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did not convert this function. Try decorating it directly with @tf.function.
</code>```

The problem should be

mean_loss_encoder, mean_loss_decoder, mean_loss_disc = tf.reduce_mean(loss_history, axis=1)

Error is about iterating over tf.Tensor is not allowed.
Is reduce_mean not working in tf.function?

答:
Use
a = tf.reduce_mean(loss_history, axis=1)
, if want to use tensor element, use a[0], a[1], ..., it works.
It look like that tensor can not catch separately.

Body:
code below

@tf.function

def train_step(self, batch):

with tf.GradientTape() as disc_tape, tf.GradientTape() as infe_tape, tf.GradientTape() as gener_tape:
  loss_encoder, loss_decoder, loss_disc = self.compute_loss(batch)

  grad_encoder = gener_tape.gradient(loss_encoder, self.model.inference_net.trainable_variables)
  grad_decoder = infe_tape.gradient(loss_decoder, self.model.generative_net.trainable_variables)
  grad_disc = disc_tape.gradient(loss_disc, self.model.discriminator.trainable_variables)

  self.infe_optimizer.apply_gradients(zip(grad_encoder, self.model.inference_net.trainable_variables))
  self.genr_optimizer.apply_gradients(zip(grad_decoder, self.model.generative_net.trainable_variables))
  self.disc_optimizer.apply_gradients(zip(grad_disc, self.model.discriminator.trainable_variables))

  return loss_encoder, loss_decoder, loss_disc

@tf.function

def train(self, epoch):

loss_history = tf.zeros([3,0])
for batch in self.train_dataset:
  loss_encoder, loss_decoder, loss_disc = self.train_step(batch)
  loss_each = tf.expand_dims(tf.stack([loss_encoder, loss_decoder, loss_disc], axis=0), 1)
  loss_history = tf.concat([loss_history, loss_each], axis=1)

mean_loss_encoder, mean_loss_decoder, mean_loss_disc = tf.reduce_mean(loss_history, axis=1)
tf.summary.scalar('encoder loss', data=mean_loss_encoder, step=epoch, description='train_loss')
tf.summary.scalar('decoder loss', data=mean_loss_decoder, step=epoch, description='train_loss')
tf.summary.scalar('discriminator loss', data=mean_loss_disc, step=epoch, description='train_loss')
print('encoder training loss %.5f' % mean_loss_encoder, 'decoder training loss %.5f' % mean_loss_decoder, 'discriminator training loss %.5f' % mean_loss_disc)

@tf.function

def validation_step(self, batch):
     return self.compute_loss(batch, training=tf.constant(False, tf.bool))

@tf.function

def validation(self, epoch):
    '''produce mean loss for epoch and append to self.val_loss_monior'''

loss_history = tf.zeros([3,0])
for batch in self.validation_dataset:
    loss_encoder, loss_decoder, loss_disc = self.validation_step(batch)
    loss_each = tf.expand_dims(tf.concat([loss_encoder, loss_decoder, loss_disc], axis=0), 1)
    loss_history = tf.concat([loss_history, loss_each], axis=1)
mean_loss_each = tf.reduce_mean(loss_history, axis=1)
print('encoder validation loss %.5f' % mean_loss_each[0], 'decoder validation loss %.5f' % mean_loss_each[1], 'discriminator validation loss %.5f' % mean_loss_each[2])

tf.summary.scalar('encoder loss', data=mean_loss_each[0], step=epoch, description='val_loss')
tf.summary.scalar('decoder loss', data=mean_loss_each[1], step=epoch, description='val_loss')
tf.summary.scalar('discriminator loss', data=mean_loss_each[2], step=epoch, description='val_loss')

# self.val_loss_monior: (3, self.patience), each row store history loss for each network
loss_each = tf.expand_dims(mean_loss_each, 1)
if epoch + 1 > self.patience:
  is_less =  self.val_loss_monior < loss_each
  is_less_encoder, is_less_decoder, is_less_discriminator = list(map(lambda x: tf.raw_ops.Any(input=tf.cast(tf.squeeze(x), tf.bool), axis=0), tf.split(is_less, 3, axis=0)))

  if not is_less_encoder:
     self.infe_optimizer.learning_rate *= self.decay_rate
  if not is_less_decoder:
     self.genr_optimizer.learning_rate *= self.decay_rate
  if not is_less_discriminator:
     self.disc_optimizer.learning_rate *= self.decay_rate

self.val_loss_monior = tf.slice(self.val_loss_monior, [0, 1], [3, self.patience - 1])
self.val_loss_monior = tf.concat([self.val_loss_monior, loss_each], axis=1)

tf.summary.scalar('encoder learning rate', data=self.infe_optimizer.learning_rate, step=epoch)
tf.summary.scalar('decoder learning rate', data=self.genr_optimizer.learning_rate, step=epoch)
tf.summary.scalar('discriminator learning rate', data=self.disc_optimizer.learning_rate, step=epoch)

@tf.function

def fit(self):

self.val_loss_monitor = tf.zeros([3, self.patience])
for epoch in range(self.epochs):
  start = time.time()
  epoch = tf.cast(epoch, tf.int64)
  self.train(epoch)
  self.validation(epoch)

  print ('Time for epoch {} is {} sec'.format(epoch, time.time()-start))
  display.clear_output(wait=True)
  if (epoch + 1) % 5 == 0:
    self.generate_images(epoch)

error massage below

OperatorNotAllowedInGraphError: in user code:

<ipython-input-5-8af39e045349>:152 fit  *
    self.train(epoch)
<ipython-input-5-8af39e045349>:90 train  *
    mean_loss_encoder, mean_loss_decoder, mean_loss_disc = tf.reduce_mean(loss_history, axis=1)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:561 __iter__
    self._disallow_iteration()
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:554 _disallow_iteration
    self._disallow_when_autograph_enabled("iterating over `tf.Tensor`")
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:532 _disallow_when_autograph_enabled
    " decorating it directly with @tf.function.".format(task))

OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did not convert this function. Try decorating it directly with @tf.function.

The problem should be

mean_loss_encoder, mean_loss_decoder, mean_loss_disc = tf.reduce_mean(loss_history, axis=1)

Error is about iterating over tf.Tensor is not allowed.
Is reduce_mean not working in tf.function?


问:
Google Sheets API -- Automatically get max range of sheet
it's known that in order to get the values from rows-columns in the Google sheets API, the format is something like this:

```<code>gapi.client.sheets.spreadsheets.values.get({
  spreadsheetId: id,
  range: "myData!A1:E"
}).then(res => {
  console.log(res.result);
}, err => console.log(err));
</code>```

Notice the "range" has to be within specific parameters, but how do I simply get the values in the max range? Is there some shorthand like "myData!Min:Max" ? I know that you can make another request to get the max row and column length:

```<code>sheets.spreadsheets.get({
    spreadsheetId: id,
    ranges: [],
    auth: something
}, (err, resp) => {
    var sheetOne = resp.data.sheets[0];
    console.log(sheetOne.properties.gridProperties); // { rowCount: 1024, columnCount: 7 } (for example)
})
</code>```

and then once I have that I can theoretically automatically generate the range string with a number-to-letter switching-system to get the column letter names or something like that, and make another request to get the max columns, but first of all:

It might be complicated to make a function that returns a letter-format range from just number maxes

even so, I would like to get only the range that have non-empty values in it; if I have a 1000 row spreadsheet but only using the first 20 rows and columns, then I Want to automatically limit the range to the actual values.

Any way to do this with the API???

答:
To return all the cells in the sheet named myData, you can use myData, rather than myData!A1:E:

```<code>gapi.client.sheets.spreadsheets.values.get({
    spreadsheetId: id,
    range: "myData"
}).then(res => {
    console.log(res.result);
}, err => console.log(err));
</code>```

With regard to your second question, as far as I know, there is no way to get only the range that has non-empty values in it using A1 notation.

However, you could iterate through the values once the api has returned them to determine which have values.

From https://developers.google.com/sheets/api/guides/concepts

A1 notation:

Some API methods require a range in A1 notation. This is a string like Sheet1!A1:B2, that refers to a group of cells in the spreadsheet, and is typically used in formulas. For example, valid ranges are:

Sheet1!A1:B2 refers to the first two cells in the top two rows of Sheet1.

Sheet1!A:A refers to all the cells in the first column of Sheet1.

Sheet1!1:2 refers to the all the cells in the first two rows of
Sheet1.

Sheet1!A5:A refers to all the cells of the first column of Sheet 1,
from row 5 onward.

A1:B2 refers to the first two cells in the top two
rows of the first visible sheet.

Sheet1 refers to all the cells in
Sheet1.

Body:
it's known that in order to get the values from rows-columns in the Google sheets API, the format is something like this:

gapi.client.sheets.spreadsheets.values.get({
  spreadsheetId: id,
  range: "myData!A1:E"
}).then(res => {
  console.log(res.result);
}, err => console.log(err));

Notice the "range" has to be within specific parameters, but how do I simply get the values in the max range? Is there some shorthand like "myData!Min:Max" ? I know that you can make another request to get the max row and column length:

sheets.spreadsheets.get({
    spreadsheetId: id,
    ranges: [],
    auth: something
}, (err, resp) => {
    var sheetOne = resp.data.sheets[0];
    console.log(sheetOne.properties.gridProperties); // { rowCount: 1024, columnCount: 7 } (for example)
})

and then once I have that I can theoretically automatically generate the range string with a number-to-letter switching-system to get the column letter names or something like that, and make another request to get the max columns, but first of all:

It might be complicated to make a function that returns a letter-format range from just number maxes

even so, I would like to get only the range that have non-empty values in it; if I have a 1000 row spreadsheet but only using the first 20 rows and columns, then I Want to automatically limit the range to the actual values.

Any way to do this with the API???

Body:
To return all the cells in the sheet named myData, you can use myData, rather than myData!A1:E:

gapi.client.sheets.spreadsheets.values.get({
    spreadsheetId: id,
    range: "myData"
}).then(res => {
    console.log(res.result);
}, err => console.log(err));

With regard to your second question, as far as I know, there is no way to get only the range that has non-empty values in it using A1 notation.

However, you could iterate through the values once the api has returned them to determine which have values.

From https://developers.google.com/sheets/api/guides/concepts

A1 notation:

Some API methods require a range in A1 notation. This is a string like Sheet1!A1:B2, that refers to a group of cells in the spreadsheet, and is typically used in formulas. For example, valid ranges are:

Sheet1!A1:B2 refers to the first two cells in the top two rows of Sheet1.

Sheet1!A:A refers to all the cells in the first column of Sheet1.

Sheet1!1:2 refers to the all the cells in the first two rows of
Sheet1.

Sheet1!A5:A refers to all the cells of the first column of Sheet 1,
from row 5 onward.

A1:B2 refers to the first two cells in the top two
rows of the first visible sheet.

Sheet1 refers to all the cells in
Sheet1.


问:
Slow debugging issue in Visual Studio
In my Visual Studio instance, even if I just wrote a single line of return in a C# console application, it will take me a minute after pressing F5 to execute the actual code (I mean the time it takes to stop on the single return statement after pressing F5 -- I set a breakpoint on the return statement in the main function). What is wrong? Is there a check list?

I am using Visual Studio 2008 VSTS edition and debugging on Windows Server 2003 x64.

答:
Go to menu Tools → Options → Debugger → Symbols and check if you have public symbols set or UNC network paths set. Also check menu Tools* → Options → Debugger → General to see if you have source server set.

All of these can affect debugging based on slow network speed or unavailable servers. The 5 minute wait time is network timeouts.

If nothing in options is set, check to see if you have the _NT_SYMBOL_PATH environment variable set.

Title: Slow debugging issue in Visual Studio

LastEditorDisplayName: Kent Fredric

OwnerDisplayName: Steve Steiner


问:
How to show storage usage to each user
We have a web platform that allows users to upload and download their data stored in a storage connected to Linux via NFS.
currently about 350GB data is stored.

I want to show each user their current storage usage on the web in real time like Google drive or Dropbox when you update a file, the remaining disk space is shown right away.

My idea was to run du command on Linux and send an update query to DB but du takes so long.

Is there any better idea that I can do this on real time?

Thanks

答:
Given that users are only allowed to upload or download data, the sizes of files stored will not change while on your storage server since "Edits" are not possible.

If you store the name and location of the file upon insert into a database, it would be wise to include the size of the file uploaded too.
In php, you can do this with filesize().

This way, if you need to fetch the size of all the users files, all you need to do is grab all records owned by them, and add the file size column. This would give you a precise size of the users files, even if the files are located across different servers.

Title: How to show storage usage to each user


问:
Html tab active
I use this example code in https://www.w3schools.com/howto/howto_js_tabs.asp, i Just want that if the user click button Paris even the user refresh the page, the tab will still be in Paris

```<code><div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">Enrollment</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')" id="secondOpen" >Student</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')" id="thirdOpen">Parents</button>
</div>

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<script>
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
//is this right?
first = document.getElementById("defaultOpen");
second = document.getElementById("secondOpen");
third = document.getElementById("thirdOpen");
if (second == ('active')){
    document.getElementById("secondOpen").click();
}else if(third == ('active')){
    document.getElementById("thirdOpen").click();
}else{
document.getElementById("defaultOpen").click();
}
</script>
</code>```

this is the example of html, I just want that if the user click the paris, even the user refresh the page the paris will active

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// is this right?
first = document.getElementById("defaultOpen");
second = document.getElementById("secondOpen");
third = document.getElementById("thirdOpen");
if (second == ('active')){
document.getElementById("secondOpen").click();
}else if(third == ('active')){
    document.getElementById("thirdOpen").click();
}else{
document.getElementById("defaultOpen").click();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}</code>```

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

```

答:
In the script you can add this.

Inside the onclick we store the active tab in localStorage

function openCity(evt, cityName) {
  <------your existing code---->
  localStorage.setItem('prevActive', cityName);
}
```

<p>and below your onclick handler we create a new load function and call it at the end.</p>

<pre class="lang-js prettyprint-override"><code>function load(){
    const cityName = localStorage.getItem('prevActive');
    if(cityName){
        const tab = document.getElementById(cityName);
        tab.style.display = "block";
        tab.className += " active";
        const tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            if(tablinks[i].textContent === cityName){
                tablinks[i].className += ' active';
                break;
            }
        }
    }
}
load();
</code>```

Here is a live demo

Title: Html tab active

Body:
I use this example code in https://www.w3schools.com/howto/howto_js_tabs.asp, i Just want that if the user click button Paris even the user refresh the page, the tab will still be in Paris

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">Enrollment</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')" id="secondOpen" >Student</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')" id="thirdOpen">Parents</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

this is the example of html, I just want that if the user click the paris, even the user refresh the page the paris will active

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// is this right?
first = document.getElementById("defaultOpen");
second = document.getElementById("secondOpen");
third = document.getElementById("thirdOpen");
if (second == ('active')){
document.getElementById("secondOpen").click();
}else if(third == ('active')){
    document.getElementById("thirdOpen").click();
}else{
document.getElementById("defaultOpen").click();
}

body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

Body:
In the script you can add this.

Inside the onclick we store the active tab in localStorage

function openCity(evt, cityName) {
  <------your existing code---->
  localStorage.setItem('prevActive', cityName);
}

and below your onclick handler we create a new load function and call it at the end.

function load(){
    const cityName = localStorage.getItem('prevActive');
    if(cityName){
        const tab = document.getElementById(cityName);
        tab.style.display = "block";
        tab.className += " active";
        const tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            if(tablinks[i].textContent === cityName){
                tablinks[i].className += ' active';
                break;
            }
        }
    }
}
load();

Here is a live demo


问:
Onclick event on moving images does not work
I am trying to count the numbers of clicks that click on the fox image.
But it does not works.
I am sure that this onclick function is works.

```<code>$(document).ready(function () {
    var i = 0;
    $(".fox").click(function(){
        $(".animal-quantity").html(i++);
    });
});
</code>```

Can anyone help me with this issue.
Thank you very much.
Link below is my full code.
https://jsfiddle.net/rbtj3ywo/1/

答:
In your CSS code exists

```<code>#animals {
    pointer-events: none;
}
</code>```

Note: pointer-events: none Means Disables any action.

Just delete it to solve the problem.

Body:
I am trying to count the numbers of clicks that click on the fox image.
But it does not works.
I am sure that this onclick function is works.

$(document).ready(function () {
    var i = 0;
    $(".fox").click(function(){
        $(".animal-quantity").html(i++);
    });
});

Can anyone help me with this issue.
Thank you very much.
Link below is my full code.
https://jsfiddle.net/rbtj3ywo/1/

Body:
In your CSS code exists

#animals {
    pointer-events: none;
}

Note: pointer-events: none Means Disables any action.

Just delete it to solve the problem.


问:
Typescript: set "node_modules" directory path
How can i set/configure a resolution path for the whole "node_modules" directory (not separate modules) for Typescript compiler if that directory is not located in the default resolution path?</p>

答:
This is the way I solved this issue with Typescript within the root directory:

I set tsconfig.json to:

```<code>"compilerOptions": {

   "baseUrl": "./",

   "typeRoots": ["node_modules/@types"],
 }
</code>```

I hope this helps someone to complement the previous answer.

RON

Body:
This is the way I solved this issue with Typescript within the root directory:

I set tsconfig.json to:

"compilerOptions": {

   "baseUrl": "./",

   "typeRoots": ["node_modules/@types"],
 }

I hope this helps someone to complement the previous answer.

RON


问:
Querying a hierarchy of parent->children - I want to sum an amount, but make sure I only count rows which have the same parent once
I have an n-level hierarchy of categories, and a set of products which can be arbitrarily mapped into categories. The same product can be in multiple categories, including multiple children of the same parent.

What I'm trying to do is write a report that shows the total ordered amount of a product in a parent category. For instance, if the parent category is "Bikes" and the children are "Bikes - Boys" and "Bikes - Girls", I want to make sure I'm including an ordered product only once in the "Bikes" category row even if it is in both child categories.

The query I have now is:

```<code>WITH
  hierarchy AS (
    SELECT
      prod.id as [prodId]
    , prod.Name as [prodName]
    , cat.id as [catId]
    , cat.parentId as [catParentId]
    , cat.name as [catName]
    FROM product_cat_map AS link
    INNER JOIN product AS prod
      ON prod.id = link.productId
    INNER JOIN category AS cat
      ON cat.id = link.catId
    where cat.parentid is not null
    UNION ALL
    SELECT
      child.prodId as [prodId]
    , child.prodName as [prodName]
    , parent.id as [catId]
    , parent.parentId as [catParentId]
    , parent.name as [catName]
    FROM hierarchy AS child
    INNER JOIN category AS parent
      ON parent.id = child.catParentId
    where parent.parentid is not null
  )
select h.catName as [category],h.prodId as [product],sum(o.amount)
from hierarchy h
inner join ord o on h.prodId = o.productId
group by h.catName, h.prodId
</code>```

The hierarchy "with" clause works great. In my example, if the bike that is in both "Bikes - Boys" and "Bikes - Girls" is ordered once, I get three rows - "Bikes", "Bikes - Boys", and "Bikes - Girls".

Using my example above, though, if the bike that is in both "Bikes - Boys" and "Bikes - Girls" costs $1 and is ordered twice, the first row of my result set is category="Bikes", product=1, total=$4.

I feel like I'm missing something incredibly obvious, but I can't wrap my head around it. Help?

答:
Can try changing this line:

```<code>from hierarchy h
</code>```

to:

```<code>from (select distinct * from hierarchy) h
</code>```

Body:
I have an n-level hierarchy of categories, and a set of products which can be arbitrarily mapped into categories. The same product can be in multiple categories, including multiple children of the same parent.

What I'm trying to do is write a report that shows the total ordered amount of a product in a parent category. For instance, if the parent category is "Bikes" and the children are "Bikes - Boys" and "Bikes - Girls", I want to make sure I'm including an ordered product only once in the "Bikes" category row even if it is in both child categories.

The query I have now is:

WITH
  hierarchy AS (
    SELECT
      prod.id as [prodId]
    , prod.Name as [prodName]
    , cat.id as [catId]
    , cat.parentId as [catParentId]
    , cat.name as [catName]
    FROM product_cat_map AS link
    INNER JOIN product AS prod
      ON prod.id = link.productId
    INNER JOIN category AS cat
      ON cat.id = link.catId
    where cat.parentid is not null
    UNION ALL
    SELECT
      child.prodId as [prodId]
    , child.prodName as [prodName]
    , parent.id as [catId]
    , parent.parentId as [catParentId]
    , parent.name as [catName]
    FROM hierarchy AS child
    INNER JOIN category AS parent
      ON parent.id = child.catParentId
    where parent.parentid is not null
  )
select h.catName as [category],h.prodId as [product],sum(o.amount)
from hierarchy h
inner join ord o on h.prodId = o.productId
group by h.catName, h.prodId

The hierarchy "with" clause works great. In my example, if the bike that is in both "Bikes - Boys" and "Bikes - Girls" is ordered once, I get three rows - "Bikes", "Bikes - Boys", and "Bikes - Girls".

Using my example above, though, if the bike that is in both "Bikes - Boys" and "Bikes - Girls" costs $1 and is ordered twice, the first row of my result set is category="Bikes", product=1, total=$4.

I feel like I'm missing something incredibly obvious, but I can't wrap my head around it. Help?

Body:
Can try changing this line:

from hierarchy h

to:

from (select distinct * from hierarchy) h