问:
winrm or requests is not installed: cannot import name certs with installed pywinrm
I'm trying to rollout directories, users and standard software over ansible on windows systems. To do so I've created a role which will handle that for me.
Now I've two environments: 1 dev environment with two Windows Server 2016 VM's and 1 QA environment with two Windows 2016 Server VM's.

The role is the same, only the vm's are others.

When I execute my role on the dev environment side everything works fine. All tasks for windows systems can be executed.

Here are my entries in dev host file for ansible:

```<code>[dev_win_servers]
dev_win_1 ansible_host=10.40.85.15 ansible_port=443 ansible_connection=winrm ansible_winrm_transport=ntlm ansible_user=Administrator ansible_password='{{ pw_dev_win_1 }}' ansible_winrm_server_cert_validation=ignore
dev_win_2 ansible_host=10.40.85.16 ansible_port=443 ansible_connection=winrm ansible_winrm_transport=ntlm ansible_user=Administrator ansible_password='{{ pw_dev_win_2 }}' ansible_winrm_server_cert_validation=ignore
</code>```

When I execute the same role on qa systems I'm getting this error:

```<code>TASK [Gathering Facts] ****************************************************************************************************************************************************************************************************************************************************************************************************************
fatal: [eti_banksystem_ha2_win1]: FAILED! => {"msg": "winrm or requests is not installed: cannot import name certs"}
</code>```

The hosts on QA network are quiet the same, only IP Address and server names are different:

```<code>[qa_win_servers]
qa_win_1 ansible_host=10.40.11.100 ansible_port=443 ansible_connection=winrm ansible_winrm_transport=ntlm ansible_user=Administrator ansible_password='{{ pw_qa_win_1 }}' ansible_winrm_server_cert_validation=ignore
qa_win_2 ansible_host=10.40.11.101 ansible_port=443 ansible_connection=winrm ansible_winrm_transport=ntlm ansible_user=Administrator ansible_password='{{ pw_qu_win_2 }}' ansible_winrm_server_cert_validation=ignore
</code>```

On the windows VM's in dev and qa I've configured a winrm listener over https on port 443 with that command (example for one host):

PS C:\Users\Administrator> winrm create winrm/config/Listener? Address=*+Transport=HTTPS '@{Hostname="eti-dcv-ha2-ap3"; CertificateThumbprint="C398C1C5857D5FDAAC791289439CB88FE9
0DE755"; Port="443"}'
```

<p>The certificate is a local generated selfsigned cert which I've generated before with:</p>

<pre class="lang-bsh prettyprint-override"><code>New-SelfSignedCertificate -DnsName "qa_win_2" -CertStoreLocation Cert:\LocalMachine\My
</code>```

On my ansible servers in dev and uat all python packages installed via yum are the same and in same version. I've checked it over executing this on both ansible servers, put result in a text file and do a diff over it:

yum list | grep ^python | awk '{ print $1 }' | sort
```

<p>Also pywinrm and requests is installed on both systems like this</p>

<pre class="lang-sh prettyprint-override"><code>fgi-dcv-depl1 root# yum list | grep winrm
python2-winrm.noarch                  0.3.0-1.el7              @epel.xc
fgi-dcv-depl1 root# yum list | grep requests
python-requests.noarch                2.6.0-1.el7_1            @base.xcmonthly
python2-requests_ntlm.noarch          1.1.0-1.el7              @epel.xc
python-requests-kerberos.noarch       0.7.0-2.el7              epel.xc
python-requests-toolbelt.noarch       0.8.0-1.el7              epel.xc
python-txrequests.noarch              0.9.2-3.el7              epel.xc
python2-requests.noarch               2.6.0-0.el7              epel.xc
python2-requests-file.noarch          1.4.3-3.el7              epel.xc
python2-requests-gssapi.noarch        1.0.1-1.el7              epel.xc
python2-requests-mock.noarch          1.5.2-1.el7              epel.xc
python2-requests-oauthlib.noarch      0.8.0-5.el7              base.xcmonthly
python34-requests.noarch              2.12.5-3.el7             epel.xc
python36-requests.noarch              2.12.5-3.el7             epel.xc
fgi-dcv-depl1 root#
</code>```

And over pip:

```<code>fgi-dcv-depl1 root# pip2.7 list | grep winrm
pywinrm                          0.3.0
fgi-dcv-depl1 root# pip2.7 list | grep requests
requests                         2.19.1
requests-ntlm                    1.1.0
fgi-dcv-depl1 root#
</code>```

As both systems are behind a firewall which will deny the access to the internet I'm not able to install anything over pip:

fgi-dcv-depl1 root# pip2.7 install --upgrade requests
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f2a4c9bd6d0>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/requests/
Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f2a4c9bd810>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/requests/
^COperation cancelled by user
fgi-dcv-depl1 root#
```

<p>EDIT: I've found some ideas more to try out the winrm connection over python console. On my dev systems:</p>

<pre class="lang-py prettyprint-override"><code>fgi-dcv-appdeploysrv root# python
Python 2.7.5 (default, Jun 20 2019, 20:27:34)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import winrm
>>> s=winrm.Session('https://10.40.85.15:443',auth=('administrator','mypw'),transport='ntlm',server_cert_validation='ignore')
>>> r=s.run_cmd('ipconfig')
>>> print r.std_out

Windows IP Configuration

Ethernet adapter Ethernet0:

   Connection-specific DNS Suffix  . :
   IPv4 Address. . . . . . . . . . . : 10.40.85.15
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 10.40.85.1

>>> quit()
</code>```

On qa system the import of winrm doesn't work:

fgi-dcv-depl1 root# python
Python 2.7.5 (default, Jun 20 2019, 20:27:34)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import winrm
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/winrm/__init__.py", line 6, in <module>
    from winrm.protocol import Protocol
  File "/usr/lib/python2.7/site-packages/winrm/protocol.py", line 11, in <module>
    from winrm.transport import Transport
  File "/usr/lib/python2.7/site-packages/winrm/transport.py", line 15, in <module>
    import requests
  File "/usr/lib/python2.7/site-packages/requests/__init__.py", line 58, in <module>
    from . import utils
  File "/usr/lib/python2.7/site-packages/requests/utils.py", line 32, in <module>
    from .exceptions import InvalidURL
  File "/usr/lib/python2.7/site-packages/requests/exceptions.py", line 10, in <module>
    from .packages.urllib3.exceptions import HTTPError as BaseHTTPError
  File "/usr/lib/python2.7/site-packages/requests/packages/__init__.py", line 95, in load_module
    raise ImportError("No module named '%s'" % (name,))
ImportError: No module named 'requests.packages.urllib3'
>>> quit()
fgi-dcv-depl1 root#
```

Meybe the error is somewhere here?

Anybody who can help here?

Thanks and best regards,
David

答:
Use:

```<code>sudo pip uninstall urllib3
</code>```

then try:

```<code>sudo yum install python-urllib3
</code>```

Body:
I'm trying to rollout directories, users and standard software over ansible on windows systems. To do so I've created a role which will handle that for me.
Now I've two environments: 1 dev environment with two Windows Server 2016 VM's and 1 QA environment with two Windows 2016 Server VM's.

The role is the same, only the vm's are others.

When I execute my role on the dev environment side everything works fine. All tasks for windows systems can be executed.

Here are my entries in dev host file for ansible:

[dev_win_servers]
dev_win_1 ansible_host=10.40.85.15 ansible_port=443 ansible_connection=winrm ansible_winrm_transport=ntlm ansible_user=Administrator ansible_password='{{ pw_dev_win_1 }}' ansible_winrm_server_cert_validation=ignore
dev_win_2 ansible_host=10.40.85.16 ansible_port=443 ansible_connection=winrm ansible_winrm_transport=ntlm ansible_user=Administrator ansible_password='{{ pw_dev_win_2 }}' ansible_winrm_server_cert_validation=ignore

When I execute the same role on qa systems I'm getting this error:

TASK [Gathering Facts] ****************************************************************************************************************************************************************************************************************************************************************************************************************
fatal: [eti_banksystem_ha2_win1]: FAILED! => {"msg": "winrm or requests is not installed: cannot import name certs"}

The hosts on QA network are quiet the same, only IP Address and server names are different:

[qa_win_servers]
qa_win_1 ansible_host=10.40.11.100 ansible_port=443 ansible_connection=winrm ansible_winrm_transport=ntlm ansible_user=Administrator ansible_password='{{ pw_qa_win_1 }}' ansible_winrm_server_cert_validation=ignore
qa_win_2 ansible_host=10.40.11.101 ansible_port=443 ansible_connection=winrm ansible_winrm_transport=ntlm ansible_user=Administrator ansible_password='{{ pw_qu_win_2 }}' ansible_winrm_server_cert_validation=ignore

On the windows VM's in dev and qa I've configured a winrm listener over https on port 443 with that command (example for one host):

PS C:\Users\Administrator> winrm create winrm/config/Listener? Address=*+Transport=HTTPS '@{Hostname="eti-dcv-ha2-ap3"; CertificateThumbprint="C398C1C5857D5FDAAC791289439CB88FE9
0DE755"; Port="443"}'

The certificate is a local generated selfsigned cert which I've generated before with:

New-SelfSignedCertificate -DnsName "qa_win_2" -CertStoreLocation Cert:\LocalMachine\My

On my ansible servers in dev and uat all python packages installed via yum are the same and in same version. I've checked it over executing this on both ansible servers, put result in a text file and do a diff over it:

yum list | grep ^python | awk '{ print $1 }' | sort

Also pywinrm and requests is installed on both systems like this

fgi-dcv-depl1 root# yum list | grep winrm
python2-winrm.noarch                  0.3.0-1.el7              @epel.xc
fgi-dcv-depl1 root# yum list | grep requests
python-requests.noarch                2.6.0-1.el7_1            @base.xcmonthly
python2-requests_ntlm.noarch          1.1.0-1.el7              @epel.xc
python-requests-kerberos.noarch       0.7.0-2.el7              epel.xc
python-requests-toolbelt.noarch       0.8.0-1.el7              epel.xc
python-txrequests.noarch              0.9.2-3.el7              epel.xc
python2-requests.noarch               2.6.0-0.el7              epel.xc
python2-requests-file.noarch          1.4.3-3.el7              epel.xc
python2-requests-gssapi.noarch        1.0.1-1.el7              epel.xc
python2-requests-mock.noarch          1.5.2-1.el7              epel.xc
python2-requests-oauthlib.noarch      0.8.0-5.el7              base.xcmonthly
python34-requests.noarch              2.12.5-3.el7             epel.xc
python36-requests.noarch              2.12.5-3.el7             epel.xc
fgi-dcv-depl1 root#

And over pip:

fgi-dcv-depl1 root# pip2.7 list | grep winrm
pywinrm                          0.3.0
fgi-dcv-depl1 root# pip2.7 list | grep requests
requests                         2.19.1
requests-ntlm                    1.1.0
fgi-dcv-depl1 root#

As both systems are behind a firewall which will deny the access to the internet I'm not able to install anything over pip:

fgi-dcv-depl1 root# pip2.7 install --upgrade requests
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f2a4c9bd6d0>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/requests/
Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f2a4c9bd810>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/requests/
^COperation cancelled by user
fgi-dcv-depl1 root#

EDIT: I've found some ideas more to try out the winrm connection over python console. On my dev systems:

fgi-dcv-appdeploysrv root# python
Python 2.7.5 (default, Jun 20 2019, 20:27:34)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import winrm
>>> s=winrm.Session('https://10.40.85.15:443',auth=('administrator','mypw'),transport='ntlm',server_cert_validation='ignore')
>>> r=s.run_cmd('ipconfig')
>>> print r.std_out

Windows IP Configuration

Ethernet adapter Ethernet0:

   Connection-specific DNS Suffix  . :
   IPv4 Address. . . . . . . . . . . : 10.40.85.15
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 10.40.85.1

>>> quit()

On qa system the import of winrm doesn't work:

fgi-dcv-depl1 root# python
Python 2.7.5 (default, Jun 20 2019, 20:27:34)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import winrm
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/winrm/__init__.py", line 6, in <module>
    from winrm.protocol import Protocol
  File "/usr/lib/python2.7/site-packages/winrm/protocol.py", line 11, in <module>
    from winrm.transport import Transport
  File "/usr/lib/python2.7/site-packages/winrm/transport.py", line 15, in <module>
    import requests
  File "/usr/lib/python2.7/site-packages/requests/__init__.py", line 58, in <module>
    from . import utils
  File "/usr/lib/python2.7/site-packages/requests/utils.py", line 32, in <module>
    from .exceptions import InvalidURL
  File "/usr/lib/python2.7/site-packages/requests/exceptions.py", line 10, in <module>
    from .packages.urllib3.exceptions import HTTPError as BaseHTTPError
  File "/usr/lib/python2.7/site-packages/requests/packages/__init__.py", line 95, in load_module
    raise ImportError("No module named '%s'" % (name,))
ImportError: No module named 'requests.packages.urllib3'
>>> quit()
fgi-dcv-depl1 root#

Meybe the error is somewhere here?

Anybody who can help here?

Thanks and best regards,
David

Body:
Use:

sudo pip uninstall urllib3

then try:

sudo yum install python-urllib3


来源: stackexchange

问:
using both QUERY and FILTER together in a single statement?
I hope someone can help me; I am building some spreadsheets to help with time-tracking. I have a list of tasks, with columns for criteria including date, hours spent, category of work, and client.

I want to filter this data by month, so for example I would like to know how long I spent in a single month on correspondence. This means I need to select all the rows where category = 'correspondence' and where the dates are all from one specified month. At the moment, I am having to use a query which outputs to an intermediary table, and then run a filter function on that table in order to output to my final table. Here are my two functions:

```<code>=QUERY( 'Task List'!A4:F , "select A, B, E, F where C = 'Correspondence'" )
</code>```

that gives me the first table, with just the rows where the category is "Correspondence". Then, on that table, I have to run the next function:

```<code>=filter(J4:M,J4:J>=date(2015,4,1),J4:J<=date(2015,4,31))
</code>```

To get only the rows from this month of April. If possible I would like to remove the intermediary table (which serves no other purpose and just clutters my sheet).

Is it possible to combine these statements and do the process in one step?

Thanks.

答:
I came to this question needing to filter by weeknum() and year() as well as  query by contains(). It can be helpful to combine the query and filter functions for similar but more dynamic date and text matching needs. If for example the OP had needed to show this data by week, that is not available in the Google Query Language.

The filter function does not have the contains function so you are limited to exact match text or using Reg-Ex. The Query Lanuague does not have the Weeknum functions.

Combining Filter and Query can be useful in scenario similar to this question but with a dynamic timeline (no hard set month or date such as rolling timeline) and where the text your matching is not exact (when you need to use a contains function from query language).
Here is an example for combining filter and query in Google sheets.

```<code>=(sum(Filter(QUERY(FB!$A:$Z, "select Q where B contains 'Apple'"), Weeknum (QUERY(FB!$A:$Z, "select E where B contains 'Apple'")) = Weeknum($A8))))

</code>```

In this example I queried Facebook ads data export for any posts which contained the word 'Apple'  in their title, and where Weeknum() matched the ongoing weeks on my sheet, in order to pull weekly data from multiple sources into one table to build reports, with minimal updating required as the timeline runs on.

It selects Q(spend) Where B(title) contains Apple, and Weeknum(E) matches week number on current row of sheet(A8). I have found this useful many times.  Query + Filter Example Sheet Here.

If OP wanted to pull this info dynamically as the months went on if A column contained months in order the formula could be pulled along and would automatically pull data from query data filtered by matching month month.

```<code>=(sum(Filter(QUERY( 'Task List'!A:Z , "select A, B, E, F, J where C contains 'Correspondence'" ), Month(QUERY( 'Task List'!A4:F , "select J where C contains 'Correspondence'" )) = Month('$A2'))))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I hope someone can help me; I am building some spreadsheets to help with time-tracking. I have a list of tasks, with columns for criteria including date, hours spent, category of work, and client.

I want to filter this data by month, so for example I would like to know how long I spent in a single month on correspondence. This means I need to select all the rows where category = 'correspondence' and where the dates are all from one specified month. At the moment, I am having to use a query which outputs to an intermediary table, and then run a filter function on that table in order to output to my final table. Here are my two functions:

=QUERY( 'Task List'!A4:F , "select A, B, E, F where C = 'Correspondence'" )

that gives me the first table, with just the rows where the category is "Correspondence". Then, on that table, I have to run the next function:

=filter(J4:M,J4:J>=date(2015,4,1),J4:J<=date(2015,4,31))

To get only the rows from this month of April. If possible I would like to remove the intermediary table (which serves no other purpose and just clutters my sheet).

Is it possible to combine these statements and do the process in one step?

Thanks.

Body:
I came to this question needing to filter by weeknum() and year() as well as  query by contains(). It can be helpful to combine the query and filter functions for similar but more dynamic date and text matching needs. If for example the OP had needed to show this data by week, that is not available in the Google Query Language.

The filter function does not have the contains function so you are limited to exact match text or using Reg-Ex. The Query Lanuague does not have the Weeknum functions.

Combining Filter and Query can be useful in scenario similar to this question but with a dynamic timeline (no hard set month or date such as rolling timeline) and where the text your matching is not exact (when you need to use a contains function from query language).
Here is an example for combining filter and query in Google sheets.

=(sum(Filter(QUERY(FB!$A:$Z, "select Q where B contains 'Apple'"), Weeknum (QUERY(FB!$A:$Z, "select E where B contains 'Apple'")) = Weeknum($A8))))

In this example I queried Facebook ads data export for any posts which contained the word 'Apple'  in their title, and where Weeknum() matched the ongoing weeks on my sheet, in order to pull weekly data from multiple sources into one table to build reports, with minimal updating required as the timeline runs on.

It selects Q(spend) Where B(title) contains Apple, and Weeknum(E) matches week number on current row of sheet(A8). I have found this useful many times.  Query + Filter Example Sheet Here.

If OP wanted to pull this info dynamically as the months went on if A column contained months in order the formula could be pulled along and would automatically pull data from query data filtered by matching month month.

=(sum(Filter(QUERY( 'Task List'!A:Z , "select A, B, E, F, J where C contains 'Correspondence'" ), Month(QUERY( 'Task List'!A4:F , "select J where C contains 'Correspondence'" )) = Month('$A2'))))

ContentLicense: CC BY-SA 4.0


问:
How to assert an actual value against 2 or more expected values?
I'm testing a method to see if it returns the correct string. This string is made up of a lot of lines whose order might change, thus usually giving 2 possible combinations. That order is not important for my application.

However, because the order of the lines might change, writing just an Assert statement will not work, since sometimes it will pass the test, and sometimes it will fail the test.

So, is it possible to write a test that will assert an actual string value against 2 or more expected string values and see if it is equal to any of them?

答:
If the content for a line is fixed you can split it at line endings before comparing. Then simply compare each line to a set of expected values.
Something like this:

```<code>   Set<String> expectedValues = ...
   String[] split = text.split("\n");
   for(String str : split) {
      assert(expectedValues.contains(str));
   }
</code>```

If you want to check that all expected values are present you can assert that expectedValue.remove(str) == true and assert after the loop that the Set is empty. If some lines may occur multiple times you have to use a Bag instead of a Set.

Body:
If the content for a line is fixed you can split it at line endings before comparing. Then simply compare each line to a set of expected values.
Something like this:

   Set<String> expectedValues = ...
   String[] split = text.split("\n");
   for(String str : split) {
      assert(expectedValues.contains(str));
   }

If you want to check that all expected values are present you can assert that expectedValue.remove(str) == true and assert after the loop that the Set is empty. If some lines may occur multiple times you have to use a Bag instead of a Set.


问:
Difference between cluster-admin and admin Kubernetes ClusterRoles
Both cluster roles are per default in every Kubernetes cluster, but what is the purpose of having both / the concrete difference between them? </p>

答:
The cluster admin has every permission on every resource on the cluster because the rule is

```<code>rules:
- apiGroups:
  - '*'
  resources:
  - '*'
  verbs:
  - '*'
- nonResourceURLs:
  - '*'
  verbs:
  - '*'
</code>```

whereas for admin role the rules are such that it has almost all permission on almost all resources but its not wildcard access like cluster admin.When a new resource or a custom resource is introduced if you want to have permission for that resource to the admin you need to add that resource to the admin role's rule but for cluster admin it's not necessary because cluster admin has wildcard in the rules.

Body:
The cluster admin has every permission on every resource on the cluster because the rule is

rules:
- apiGroups:
  - '*'
  resources:
  - '*'
  verbs:
  - '*'
- nonResourceURLs:
  - '*'
  verbs:
  - '*'

whereas for admin role the rules are such that it has almost all permission on almost all resources but its not wildcard access like cluster admin.When a new resource or a custom resource is introduced if you want to have permission for that resource to the admin you need to add that resource to the admin role's rule but for cluster admin it's not necessary because cluster admin has wildcard in the rules.


问:
hibernate : Making an API who allow user to store a title a description and an image into database
I'm trying to make an API in java who allows me to save into database a "chronic", chronic contains a title, an image, and a description.

My aim is to have a form (angular side) with title, description and upload an image and make a post request once the form is complete.

But i'm really struggling with the java part as i don't know how to store images .. tutorials doesn't help me that much as i can't really understand the dynamics behind the process, so i'm asking for help, here's my code  :

MODEL

```<code>@Entity
public class Chroniques extends AbstractEntity {

 private String title;

 @Lob
 @Column(length = 16777215)
 private byte[] img;
 private String description;

 public Chroniques(String title, byte[] img, String description) {
     super();
     this.title = title;
     this.img = img;
     this.description = description;
 }

 public Chroniques() {
     super();
 }

 //Getters Setters
</code>```

REPOSITORY

```<code>public void persist(T entity) {
        em.persist(entity);
    }
</code>```

SERVICE

```<code>public void saveChronique(Chroniques chroniques) {
        chroniquesRepository.persist(chroniques);
    }
</code>```

CONTROLLER

```<code>@RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public void createChronique(@RequestBody Chroniques chronique) {
         chroniquesService.saveChronique(chronique);
    }
</code>```

When i try to run on postman i get these logs of error :

```<code>{
    "timestamp": "2020-02-18T18:33:21.473+0000",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'multipart/form-data;boundary=--------------------------739290743229099187971927;charset=UTF-8' not supported",
    "trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=--------------------------739290743229099187971927;charset=UTF-8' not supported\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:225)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:158)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:131)\r\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:660)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\r\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.lang.Thread.run(Thread.java:748)\r\n",
    "path": "/api/chroniques/save"
}
</code>```

That's all i got for now, i think i need to treat text, description separatly from image ..

答:
i think it has nothing to do with hibernate

looks like an issue with controller

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/HttpMediaTypeNotSupportedException.html

try to fix it with consumes parameter

Body:
I'm trying to make an API in java who allows me to save into database a "chronic", chronic contains a title, an image, and a description.

My aim is to have a form (angular side) with title, description and upload an image and make a post request once the form is complete.

But i'm really struggling with the java part as i don't know how to store images .. tutorials doesn't help me that much as i can't really understand the dynamics behind the process, so i'm asking for help, here's my code  :

MODEL

@Entity
public class Chroniques extends AbstractEntity {

 private String title;

 @Lob
 @Column(length = 16777215)
 private byte[] img;
 private String description;

 public Chroniques(String title, byte[] img, String description) {
     super();
     this.title = title;
     this.img = img;
     this.description = description;
 }

 public Chroniques() {
     super();
 }

 //Getters Setters

REPOSITORY

public void persist(T entity) {
        em.persist(entity);
    }

SERVICE

public void saveChronique(Chroniques chroniques) {
        chroniquesRepository.persist(chroniques);
    }

CONTROLLER

@RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public void createChronique(@RequestBody Chroniques chronique) {
         chroniquesService.saveChronique(chronique);
    }

When i try to run on postman i get these logs of error :

{
    "timestamp": "2020-02-18T18:33:21.473+0000",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'multipart/form-data;boundary=--------------------------739290743229099187971927;charset=UTF-8' not supported",
    "trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=--------------------------739290743229099187971927;charset=UTF-8' not supported\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:225)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:158)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:131)\r\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:660)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\r\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.lang.Thread.run(Thread.java:748)\r\n",
    "path": "/api/chroniques/save"
}

That's all i got for now, i think i need to treat text, description separatly from image ..


问:
Regex to remove a character if followed by another character in java
Working on a regex in java to find words that follow the below rules

Regex Rules:

Word could start with - (optional Prefix)letters could be any of these 'c''p''y''r''a''u'

Followed by capital T

Followed by number between 0 to 9

(optional Suffix)Followed by lower case letters that doesn't include
letters p or y or r or u. Can be one or two letters

Problem:If the above said suffix for the word is a or b or c and followed by a capital N then the regex should ignore that letter and what follows it.Look in test cases for clarification.

Test cases

pT1c - should return the whole word pT1c (since N doesnt follow the c)

cT4bcN2 - should return just cT4b (since c is followed by N ignore those two letters and the rest that follows them)

cT3cN2 - should return cT3(since c is followed by N ignore those 2 letters and the rest that follows them)

So far I have

[cpyrau]*[T][0-9X?][a-oqstv-z]{0,2}([N])?(?(1)(?=[abc]))

Which works for the first test case but for all others it includes the letter before N if it is a or c so I’m getting cT4bc and cT3c for second and third test case.

Any help is appreciated.

答:
Does this do what you are after?</p>

```<code>\b[cpyrau]*T\d(?:(?![a-c]N)[a-oqstv-z]){0,2}
</code>```

Body:
Does this do what you are after?

\b[cpyrau]*T\d(?:(?![a-c]N)[a-oqstv-z]){0,2}


问:
Terraform: store the contents of a set of files into a single variable
This is in TF V0.12 if that helps
In a directory, I have a variable number of single-line files.

I need to somehow read the contents of them all concatenating them with a newline between and store the result into a single variable. (not an array of strings)
I know I can get the list of files to read using:

```<code>locals{
  my files=tolist(fileset("${var.file_path}", "**")) }
</code>```

And if I only had a single file I know I can read in the contents by using

```<code>locals {
  file_value=file("${var.file_path}\\${local.my_files}") # if there was only a single file
}
</code>```

But my brains just turned to cotton wool how I can do the read for multiple,  I feel like I should be using a count and a concatenate within a null resource but can't seem to work the logic out.
Is that the right path or how should I be doing it?

答:
We can break this problem down into three steps:

Enumerate the filenames matching your desired pattern.

Read the content of each file into memory.

Concatenate all of the file contents together.

We can reformulate the above into three local value expressions, with each one building on the previous one:

```<code>locals {
  filenames            = fileset(".", "${var.file_path}/**")
  file_contents        = { for fn in local.filenames : fn => file(fn) }
  file_contents_concat = join("\n", local.file_contents)
}
</code>```

Alternatively, we can do all of those steps together in a single expression:

```<code>locals {
  file_contents_concat = join("\n", [
    for fn in fileset(".", "${var.file_path}/**") : file(fn)
  ])
}
</code>```

Note that in the fileset call I included var.file_path in the pattern argument rather than in the path argument because that way the resulting file paths will all be relative to the current working directory, and so we can just pass them directly to file without having to re-prepend var.file_path there.

(The separation between path and pattern for fileset is there to help with situations like mirroring a bunch of files into S3, where it's helpful to have the resulting paths be relative to the bucket root rather than the current working directory, but that sort of mapping isn't important here because the filenames don't appear in the result at all.)

Body:
This is in TF V0.12 if that helps
In a directory, I have a variable number of single-line files.

I need to somehow read the contents of them all concatenating them with a newline between and store the result into a single variable. (not an array of strings)
I know I can get the list of files to read using:

locals{
  my files=tolist(fileset("${var.file_path}", "**")) }

And if I only had a single file I know I can read in the contents by using

locals {
  file_value=file("${var.file_path}\\${local.my_files}") # if there was only a single file
}

But my brains just turned to cotton wool how I can do the read for multiple,  I feel like I should be using a count and a concatenate within a null resource but can't seem to work the logic out.
Is that the right path or how should I be doing it?

Body:
We can break this problem down into three steps:

Enumerate the filenames matching your desired pattern.

Read the content of each file into memory.

Concatenate all of the file contents together.

We can reformulate the above into three local value expressions, with each one building on the previous one:

locals {
  filenames            = fileset(".", "${var.file_path}/**")
  file_contents        = { for fn in local.filenames : fn => file(fn) }
  file_contents_concat = join("\n", local.file_contents)
}

Alternatively, we can do all of those steps together in a single expression:

locals {
  file_contents_concat = join("\n", [
    for fn in fileset(".", "${var.file_path}/**") : file(fn)
  ])
}

Note that in the fileset call I included var.file_path in the pattern argument rather than in the path argument because that way the resulting file paths will all be relative to the current working directory, and so we can just pass them directly to file without having to re-prepend var.file_path there.

(The separation between path and pattern for fileset is there to help with situations like mirroring a bunch of files into S3, where it's helpful to have the resulting paths be relative to the bucket root rather than the current working directory, but that sort of mapping isn't important here because the filenames don't appear in the result at all.)


问:
PHP website, should I develop into a Linux distribution instead of Windows?
In few months I start a project in PHP and I am hesitating to do like usual : develop on my Windows Vista 64bits machine. Since I know few things on Linux, I think it can be a good way to learn by working on a Linux distribution.

Do you think it's a good idea or not? I would run a VirtualBox with Ubuntu (on my Vista64bits). I was thinking to install XAMPP to be able to develop in PHP.

If you think it's a good idea, feel free to suggest me some tutorial about what I should know with Virtualizing an OS, or Linux/dev.

Update
I have build many website in PHP with Windows, the question is more about if it's a good way to start learning Linux by developing on it via a Virtual machine? I have 4 gigs rams, will it be smooth if I install Eclipse in the Virtual Machine? etc.

答:
The side effect of developing inside a VM: more overhead and eventually the needs of additional tools to make the development more comfortable.
Often people need special tools for their development like Photoshop or some vector design tools not available on Linux. If the working copy of the project is inside the VM, it makes sense to have easy access to it. So you will setup SAMBA (which makes often problems with the login from XP) or setup SSL(SFTP)/FTP.
Also you must learn how to use networking with the VM (NAT, bridging, port forwarding).

On the other side, developing on another platform as the target can give some headache. I found myself often confused with .htaccess files for password protection, because oft the different path on Windows/Linux. If you forget to change this entries later on the production server, you have a problem...

A better solution: use the best of both worlds.
A VM eventually running later headless (no gui, more like a "remote server") with Ubuntu/Debian/FreeBSD) and only running the needed servers (Apache, MySQL, FTP, SSH...).

Eclipse or the other development tools on Windows/Mac.

OwnerDisplayName: Daok

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daok

OwnerDisplayName: devarni


问:
Determine whether a row is selected in a DataGridView
I'm looping through a DataGridView, and I need to do this :</p>

```<code> for(int i = 0; i < DGV.Rows.Count - 2; i)
 {
    // if the row is selected
    // do something
 }
</code>```

Body:
I'm looping through a DataGridView, and I need to do this :

 for(int i = 0; i < DGV.Rows.Count - 2; i)
 {
    // if the row is selected
    // do something
 }

Body: DataGridView.SelectedRows


问:
Rank and count elements of list of lists in django
I have a Genre and a User models. Each Genre has an id and a name, and there is a many-to-many relationship, so that each User likes 0 or more Genres.

Is there an efficient query for obtaining how many likes has each Genre, across all users, in descendant order?

My current approach works, but it is extremely inefficient since it has to read all the likes of all the users for each genre:

```<code>In [1]: genres = list(Genre.objects.values('name', 'id'))

In[2]: genres
Out[2]:
[{'id': 10, 'name': 'Rock'},
 {'id': 11, 'name': 'Pop'},
 {'id': 12, 'name': 'Hip hop'},
 {'id': 13, 'name': 'Electronic'},
 {'id': 14, 'name': 'Classical'}]

In [3]: likes_by_users = []

In [4]: users = list(User.objects.all())

In [5]: for u in users:
...:     current_user_likes = []
...:     likes_by_users.append(current_user_likes)
...:     for lg in u.liked_genres.all():
...:         current_user_likes.append(lg.pk)

In [6]: likes_by_users
Out[6]:
[[14],
 [11, 12],
 [11, 10, 13, 12],
 [],
 [13, 12, 10, 1
 [10, 11]]

In [7]: counts = {}

In [8]: for g in genres:
    ...:     counts[g['id']] = {
    ...:         'name' : g['name'],
    ...:         'likes': 0
    ...:     }
    ...:     for l in likes_by_users:
    ...:         for gid in l:
    ...:             if gid == g['id']:
    ...:                 counts[gid]['likes'] += 1

In [9]: ranking = sorted(list(counts.values()), key=lambda x : x['likes'], reverse=True)
</code>```

And this is exactly the output that I need:

```<code>In [9]: ranking
Out[9]:
[{'likes': 4, 'name': 'Pop'},
 {'likes': 3, 'name': 'Rock'},
 {'likes': 3, 'name': 'Hip hop'},
 {'likes': 2, 'name': 'Electronic'},
 {'likes': 1, 'name': 'Classical'}]
</code>```

Is there a query or another method for obtaining in an efficient way the required ranking?

答:
Try this</p>

```<code>from django.db.models import Count
Genre.objects.annotate(likes=Count('user')).order_by('-likes')
</code>```

Body:
I have a Genre and a User models. Each Genre has an id and a name, and there is a many-to-many relationship, so that each User likes 0 or more Genres.

Is there an efficient query for obtaining how many likes has each Genre, across all users, in descendant order?

My current approach works, but it is extremely inefficient since it has to read all the likes of all the users for each genre:

In [1]: genres = list(Genre.objects.values('name', 'id'))

In[2]: genres
Out[2]:
[{'id': 10, 'name': 'Rock'},
 {'id': 11, 'name': 'Pop'},
 {'id': 12, 'name': 'Hip hop'},
 {'id': 13, 'name': 'Electronic'},
 {'id': 14, 'name': 'Classical'}]

In [3]: likes_by_users = []

In [4]: users = list(User.objects.all())

In [5]: for u in users:
...:     current_user_likes = []
...:     likes_by_users.append(current_user_likes)
...:     for lg in u.liked_genres.all():
...:         current_user_likes.append(lg.pk)

In [6]: likes_by_users
Out[6]:
[[14],
 [11, 12],
 [11, 10, 13, 12],
 [],
 [13, 12, 10, 1
 [10, 11]]

In [7]: counts = {}

In [8]: for g in genres:
    ...:     counts[g['id']] = {
    ...:         'name' : g['name'],
    ...:         'likes': 0
    ...:     }
    ...:     for l in likes_by_users:
    ...:         for gid in l:
    ...:             if gid == g['id']:
    ...:                 counts[gid]['likes'] += 1

In [9]: ranking = sorted(list(counts.values()), key=lambda x : x['likes'], reverse=True)

And this is exactly the output that I need:

In [9]: ranking
Out[9]:
[{'likes': 4, 'name': 'Pop'},
 {'likes': 3, 'name': 'Rock'},
 {'likes': 3, 'name': 'Hip hop'},
 {'likes': 2, 'name': 'Electronic'},
 {'likes': 1, 'name': 'Classical'}]

Is there a query or another method for obtaining in an efficient way the required ranking?

Body:
Try this

from django.db.models import Count
Genre.objects.annotate(likes=Count('user')).order_by('-likes')


问:
Content Validation in JCR
We are evaluating a few technologies to build a repository of WSDLs, and XSDs used within our organization. One of the options we have is to use Apache JackRabbit, that implements JCR 1.0 and 2.0. It almost meets our expectations on uploading contents, authentication and versioning. However, we are also planning to upload several pieces of metadata (e.g., createdBy,lastModifiedBy,lastModifiedTime, etc.) with the WSDLs and XSDs to the repository. We have read through several of the posts on StackOverflow, JCR specs and wiki pages in the JackRabbit's website, but did not quite understand - how the metadata that we are uploading can be validated ? For example, if we upload the metadata as an XML -formated content, we want the repository to validate the XML against an XML schema.
In terms of the JCR API, is there a way to enable validation of XML while importing the XML content through Session.importXML ? </p>

答:
As Randall says, the JCR API doesn't provide hooks to validate content while you're storing it.

One common pattern is to upload data to an intermediate location in the JCR tree, say /incoming, and have JCR observers watch this incoming data, validate it and move it to its final location if valid.

Another option is to use Apache Sling [1] which provides an OSGi-based scriptable application layer on top of a JCR repository. With Sling you can intercept HTTP POST requests, for example, to validate data before storing it.

[1] http://sling.apache.org

Title: Content Validation in JCR


问:
Variable is not defined after several if and for statements using regex search function for parsing in Python
I'm parsing several text files in Python in order to find blocks of code that get repeated over and over again. The aim is to merge the similar blocks of codes of different files into another file.

Therefore, I need to scan the text file, find the block of interest by using a regex search and then storing the line where it begins and ends in the original text file. In the end, I can then write that block of code into another file, using the "begin and end lines" as a boundary.

The extract of code below is a part of this main code that I described, but the variable "layer_end" is not being defined. Any suggestions?

```<code>    with open(f_path, 'r') as gcode: # Opening each file separately
        for i, line in enumerate(gcode.readlines()): # Searching for the beginning of given layer
            if rgx_start.search(line):
                start_i = prev_start[cube_i]
                print(start_i)
                if i > start_i:
                    layer_start = i + 2
                    break
        for i, line in enumerate(gcode.readlines()):  # Searching for the end of given layer
            if rgx_end.search(line):
                if i > layer_start:
                    layer_end = i - 2
                    break
        for i, line in enumerate(gcode.readlines()):
            if i in range(layer_start, (layer_end + 1)):  # Writing the code of that given layer
                final_code.write(line)
        prev_start.append(layer_start)
        print(prev_start)
        prev_end.append(layer_end)
</code>```

答:
readlines can only be called once per open file. start_i never changes inside the for-loop and since the inner if is only true, if i is greater than some value, you can just start at this element.

```<code>with open(f_path, 'r') as gcode: # Opening each file separately
    lines = gcode.readlines()

start_i = prev_start[cube_i]
for i, line in enumerate(lines[start_i+1:]): # Searching for the beginning of given layer
    if rgx_start.search(line):
        layer_start = start_i + i + 3
        break
for i, line in enumerate(lines[layer_start+1:]):  # Searching for the end of given layer
    if rgx_end.search(line):
        layer_end = layer_start + i - 1
        break
final_code.write(lines[layer_start:layer_end + 1)
prev_start.append(layer_start)
print(prev_start)
prev_end.append(layer_end)
</code>```

Body:
I'm parsing several text files in Python in order to find blocks of code that get repeated over and over again. The aim is to merge the similar blocks of codes of different files into another file.

Therefore, I need to scan the text file, find the block of interest by using a regex search and then storing the line where it begins and ends in the original text file. In the end, I can then write that block of code into another file, using the "begin and end lines" as a boundary.

The extract of code below is a part of this main code that I described, but the variable "layer_end" is not being defined. Any suggestions?

    with open(f_path, 'r') as gcode: # Opening each file separately
        for i, line in enumerate(gcode.readlines()): # Searching for the beginning of given layer
            if rgx_start.search(line):
                start_i = prev_start[cube_i]
                print(start_i)
                if i > start_i:
                    layer_start = i + 2
                    break
        for i, line in enumerate(gcode.readlines()):  # Searching for the end of given layer
            if rgx_end.search(line):
                if i > layer_start:
                    layer_end = i - 2
                    break
        for i, line in enumerate(gcode.readlines()):
            if i in range(layer_start, (layer_end + 1)):  # Writing the code of that given layer
                final_code.write(line)
        prev_start.append(layer_start)
        print(prev_start)
        prev_end.append(layer_end)

Body:
readlines can only be called once per open file. start_i never changes inside the for-loop and since the inner if is only true, if i is greater than some value, you can just start at this element.

with open(f_path, 'r') as gcode: # Opening each file separately
    lines = gcode.readlines()

start_i = prev_start[cube_i]
for i, line in enumerate(lines[start_i+1:]): # Searching for the beginning of given layer
    if rgx_start.search(line):
        layer_start = start_i + i + 3
        break
for i, line in enumerate(lines[layer_start+1:]):  # Searching for the end of given layer
    if rgx_end.search(line):
        layer_end = layer_start + i - 1
        break
final_code.write(lines[layer_start:layer_end + 1)
prev_start.append(layer_start)
print(prev_start)
prev_end.append(layer_end)


问:
How to make an extension for multiple types in Swift 5
I have the following extension which I want to make usable for both an UITextView and an UILabel.

extension UITextView {
    func setTextWithTypeAnimation(typedText: String, characterDelay: TimeInterval = 2.5) {
        text = ""
        var writingTask: DispatchWorkItem?
        writingTask = DispatchWorkItem { [weak weakSelf = self] in
            for character in typedText {
                DispatchQueue.main.async {
                    weakSelf?.text!.append(character)
                }
                Thread.sleep(forTimeInterval: characterDelay/100)
            }
        }

        if let task = writingTask {
            let queue = DispatchQueue(label: "typespeed", qos: DispatchQoS.userInteractive)
            queue.asyncAfter(deadline: .now() + 0.05, execute: task)
        }
    }
}
```

<p>I tried to set the type to UIView found here: Stack Overflow: Single extension for UITextView and UITextField in Swift </p>

<pre class="lang-swift prettyprint-override"><code>extension UIView  {
    func setTextWithTypeAnimation(typedText: String, characterDelay: TimeInterval = 2.5) {
        if self is UILabel || self is UITextView {
            text = ""
            var writingTask: DispatchWorkItem?
            writingTask = DispatchWorkItem { [weak weakSelf = self] in
                for character in typedText {
                    DispatchQueue.main.async {
                        weakSelf?.text!.append(character)
                    }
                    Thread.sleep(forTimeInterval: characterDelay/100)
                }
            }

            if let task = writingTask {
                let queue = DispatchQueue(label: "typespeed", qos: DispatchQoS.userInteractive)
                queue.asyncAfter(deadline: .now() + 0.05, execute: task)
            }
        }
    }
}
</code>```

That of course doesn't work because UIView has no text property so I get the following error:

```<code>Use of unresolved identifier 'text'
</code>```

How can I solve this?

答:
That of course doesn't work because UIView has no text property

This is exactly the piece you want to think about. What do you need in order to write this method? Two things: it needs a text property. And it needs to be a class type (because you use a weak modifier on it). So say that.

```<code>protocol TypeAnimated: AnyObject {
    var text: String? { get set }
}
</code>```

Except that for historical reasons, UITextView has a String! while UILabel has a String?. That's very frustrating, but we can bridge the two with a new property:

```<code>protocol TypeAnimated: AnyObject {
    var animatedText: String { get set }
}
</code>```

Now, given that protocol, you can write you method:

```<code>extension TypeAnimated  {
    func setTextWithTypeAnimation(typedText: String, characterDelay: TimeInterval = 2.5) {
        animatedText = ""
        var writingTask: DispatchWorkItem?
        writingTask = DispatchWorkItem { [weak weakSelf = self] in
            for character in typedText {
                DispatchQueue.main.async {
                    weakSelf?.animatedText!.append(character)
                }
                Thread.sleep(forTimeInterval: characterDelay/100)
            }
        }

        if let task = writingTask {
            let queue = DispatchQueue(label: "typespeed", qos: DispatchQoS.userInteractive)
            queue.asyncAfter(deadline: .now() + 0.05, execute: task)
        }
    }
}
</code>```

Now, you just need to label any types you want to conform to this protocol, and they'll get the extension.

```<code>extension UILabel: TypeAnimated {
    var animatedText: String {
        get { return text ?? "" }
        set { text = newValue }
    }
}

extension UITextView: TypeAnimated {
    var animatedText: String {
        get { return text ?? "" }
        set { text = newValue }
    }
}
</code>```

As a side note, generating a new queue every time this is executed is almost certainly not what you mean. You should probably just set this up as a series of asyncAfter calls to the main queue, or use a Timer, or call asyncAfter inside the asyncAfter block. But none of this really impacts your question.

I haven't tested this, but this is how I would probably approach the problem:

```<code>extension TypeAnimated  {
    func setTextWithTypeAnimation(typedText: String, characterDelay: TimeInterval = 2.5/100) {
        func addNextCharacter(from string: Substring) {
            DispatchQueue.main.asyncAfter(deadline: .now() + characterDelay) { [weak self] in
                if let self = self, let nextChar = string.first {
                    self.animatedText.append(nextChar)
                    addNextCharacter(from: string.dropFirst())
                }
            }

        }

        animatedText = ""
        addNextCharacter(from: typedText[...])
    }
}
</code>```

Body:
I have the following extension which I want to make usable for both an UITextView and an UILabel.

extension UITextView {
    func setTextWithTypeAnimation(typedText: String, characterDelay: TimeInterval = 2.5) {
        text = ""
        var writingTask: DispatchWorkItem?
        writingTask = DispatchWorkItem { [weak weakSelf = self] in
            for character in typedText {
                DispatchQueue.main.async {
                    weakSelf?.text!.append(character)
                }
                Thread.sleep(forTimeInterval: characterDelay/100)
            }
        }

        if let task = writingTask {
            let queue = DispatchQueue(label: "typespeed", qos: DispatchQoS.userInteractive)
            queue.asyncAfter(deadline: .now() + 0.05, execute: task)
        }
    }
}

I tried to set the type to UIView found here: Stack Overflow: Single extension for UITextView and UITextField in Swift

extension UIView  {
    func setTextWithTypeAnimation(typedText: String, characterDelay: TimeInterval = 2.5) {
        if self is UILabel || self is UITextView {
            text = ""
            var writingTask: DispatchWorkItem?
            writingTask = DispatchWorkItem { [weak weakSelf = self] in
                for character in typedText {
                    DispatchQueue.main.async {
                        weakSelf?.text!.append(character)
                    }
                    Thread.sleep(forTimeInterval: characterDelay/100)
                }
            }

            if let task = writingTask {
                let queue = DispatchQueue(label: "typespeed", qos: DispatchQoS.userInteractive)
                queue.asyncAfter(deadline: .now() + 0.05, execute: task)
            }
        }
    }
}

That of course doesn't work because UIView has no text property so I get the following error:

Use of unresolved identifier 'text'

How can I solve this?

Body:
That of course doesn't work because UIView has no text property

This is exactly the piece you want to think about. What do you need in order to write this method? Two things: it needs a text property. And it needs to be a class type (because you use a weak modifier on it). So say that.

protocol TypeAnimated: AnyObject {
    var text: String? { get set }
}

Except that for historical reasons, UITextView has a String! while UILabel has a String?. That's very frustrating, but we can bridge the two with a new property:

protocol TypeAnimated: AnyObject {
    var animatedText: String { get set }
}

Now, given that protocol, you can write you method:

extension TypeAnimated  {
    func setTextWithTypeAnimation(typedText: String, characterDelay: TimeInterval = 2.5) {
        animatedText = ""
        var writingTask: DispatchWorkItem?
        writingTask = DispatchWorkItem { [weak weakSelf = self] in
            for character in typedText {
                DispatchQueue.main.async {
                    weakSelf?.animatedText!.append(character)
                }
                Thread.sleep(forTimeInterval: characterDelay/100)
            }
        }

        if let task = writingTask {
            let queue = DispatchQueue(label: "typespeed", qos: DispatchQoS.userInteractive)
            queue.asyncAfter(deadline: .now() + 0.05, execute: task)
        }
    }
}

Now, you just need to label any types you want to conform to this protocol, and they'll get the extension.

extension UILabel: TypeAnimated {
    var animatedText: String {
        get { return text ?? "" }
        set { text = newValue }
    }
}

extension UITextView: TypeAnimated {
    var animatedText: String {
        get { return text ?? "" }
        set { text = newValue }
    }
}

As a side note, generating a new queue every time this is executed is almost certainly not what you mean. You should probably just set this up as a series of asyncAfter calls to the main queue, or use a Timer, or call asyncAfter inside the asyncAfter block. But none of this really impacts your question.

I haven't tested this, but this is how I would probably approach the problem:

extension TypeAnimated  {
    func setTextWithTypeAnimation(typedText: String, characterDelay: TimeInterval = 2.5/100) {
        func addNextCharacter(from string: Substring) {
            DispatchQueue.main.asyncAfter(deadline: .now() + characterDelay) { [weak self] in
                if let self = self, let nextChar = string.first {
                    self.animatedText.append(nextChar)
                    addNextCharacter(from: string.dropFirst())
                }
            }

        }

        animatedText = ""
        addNextCharacter(from: typedText[...])
    }
}


问:
Swagger codegen to Java Spring generates incorrect file response entity from OpenAPI component of binary format
I am using swagger-codegen-maven-plugin to generate  Spring interface from OpenAPI file (OpenAPI 3.0.2)

```<code><groupId>io.swagger.codegen.v3</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>3.0.14</version>
</code>```

The response of one rest API should be PDF file

```<code>components:
    schemas:
        contractFile:
            type: string
            format: binary
</code>```

Generated Java REST interface then contains the following method

```<code>default ResponseEntity<File> getContract(@ApiParam(value = "File to download",required=true) @PathVariable("uid") String uid) {
...
}
</code>```

File class represents the path to the filesystem, but I don't have the file on the filesystem, just bytes in java memory and I don't want to save them as the file to disk.

I want getContract to return some StreamResource or some other representation of file from Stream/bytes in memory. Is it possible this via swagger-codegen-maven-plugin or some other option?

答:
Try something like this:</p>

```<code>responses:
     '200':
          description: A PDF file
          content:
            application/pdf:
              schema:
                type: string
                format: binary
</code>```

Body:
I am using swagger-codegen-maven-plugin to generate  Spring interface from OpenAPI file (OpenAPI 3.0.2)

<groupId>io.swagger.codegen.v3</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>3.0.14</version>

The response of one rest API should be PDF file

components:
    schemas:
        contractFile:
            type: string
            format: binary

Generated Java REST interface then contains the following method

default ResponseEntity<File> getContract(@ApiParam(value = "File to download",required=true) @PathVariable("uid") String uid) {
...
}

File class represents the path to the filesystem, but I don't have the file on the filesystem, just bytes in java memory and I don't want to save them as the file to disk.

I want getContract to return some StreamResource or some other representation of file from Stream/bytes in memory. Is it possible this via swagger-codegen-maven-plugin or some other option?

Body:
Try something like this:

responses:
     '200':
          description: A PDF file
          content:
            application/pdf:
              schema:
                type: string
                format: binary


问:
Most efficient way to search event log messages
Suppose I want to find the newest occurrence of event 4688 that contains the string 0x1278. I am able to find the event by getting a certain number of events and then searching the message for that string:

```<code>Get-WinEvent -MaxEvents 1000 -FilterHashTable @{LogName="Security";Id=4688} | Where-Object {$_.Message -match "0x1278"}
</code>```

There are two issues with this approach:

The script must always wait for 1000 events to be returned, even if the event being searched for was at index 3.

If the event was older and would have been at index 1034, too few events were checked and it wasn't found when it should have been.

Is there a way to address these issues? Ideally the event should be found in the shortest time possible.

答:
Use -FilterXPath to offload filtering to the event log service!

This approach won't allow us to search the text of the rendered log message, but it will allow us to very granularly query structured data in the event.

Assuming that you're searching 0x1278 because it's a process ID event, we can query for that specific event with the following XPath expression:

```<code>*[System[EventID=4688] and EventData[Data[@Name='NewProcessId']='0x3e8']]
</code>```

Used with Get-WinEvent, we end up with something like:

```<code>Get-WinEvent -MaxEvents 1000 -FilterXPath "*[System[EventID=4688] and EventData[Data[@Name='NewProcessId']='0x3e8']]" -LogName "Security"
</code>```

Now the eventlog service only needs to return one event, making your Get-WinEvent query execute much faster

Body:
Suppose I want to find the newest occurrence of event 4688 that contains the string 0x1278. I am able to find the event by getting a certain number of events and then searching the message for that string:

Get-WinEvent -MaxEvents 1000 -FilterHashTable @{LogName="Security";Id=4688} | Where-Object {$_.Message -match "0x1278"}

There are two issues with this approach:

The script must always wait for 1000 events to be returned, even if the event being searched for was at index 3.

If the event was older and would have been at index 1034, too few events were checked and it wasn't found when it should have been.

Is there a way to address these issues? Ideally the event should be found in the shortest time possible.

Body:
Use -FilterXPath to offload filtering to the event log service!

This approach won't allow us to search the text of the rendered log message, but it will allow us to very granularly query structured data in the event.

Assuming that you're searching 0x1278 because it's a process ID event, we can query for that specific event with the following XPath expression:

*[System[EventID=4688] and EventData[Data[@Name='NewProcessId']='0x3e8']]

Used with Get-WinEvent, we end up with something like:

Get-WinEvent -MaxEvents 1000 -FilterXPath "*[System[EventID=4688] and EventData[Data[@Name='NewProcessId']='0x3e8']]" -LogName "Security"

Now the eventlog service only needs to return one event, making your Get-WinEvent query execute much faster


问:
AngularJS Scope is not accessible through console
I just started learning angular js. I have understanding that we can access and debug scope available to any dom element by selecting/inspecting anywhere on the page and running

```<code>angular.element($0).scope()
</code>```

code on console. But if you try this, I find its value undefined. How they are hiding it and how can I reach to data through console?

答:
Load angular.js instead of angular.min.js. You will get better stack traces and data debugging will be enabled.

From the Docs:

angular.element — jQuery/jqLite Extras

AngularJS also provides the following additional methods and events to both jQuery and jqLite:

scope() - retrieves the scope of the current element or its parent. Requires Debug Data to be enabled.

— AngularJS angular.element API Reference - jQuery/jqLite Extras

For more information, see

AngularJS $compileProvider API Reference

AngularJS angular.reloadWithDebugInfo API Reference

Body:
I just started learning angular js. I have understanding that we can access and debug scope available to any dom element by selecting/inspecting anywhere on the page and running

angular.element($0).scope()

code on console. But if you try this, I find its value undefined. How they are hiding it and how can I reach to data through console?


答:
If your using junit I'd just do something like the following:</p>

```<code>assertTrue(myString.equals("Value1") || myString.equals("Value"));
</code>```

Title: How to assert an actual value against 2 or more expected values?

Body:
I'm testing a method to see if it returns the correct string. This string is made up of a lot of lines whose order might change, thus usually giving 2 possible combinations. That order is not important for my application.

However, because the order of the lines might change, writing just an Assert statement will not work, since sometimes it will pass the test, and sometimes it will fail the test.

So, is it possible to write a test that will assert an actual string value against 2 or more expected string values and see if it is equal to any of them?

Body:
If your using junit I'd just do something like the following:

assertTrue(myString.equals("Value1") || myString.equals("Value"));


问:
StyleCop.Analyzers Nuget Dependencies
I have created a Nuget package on a private Azure Artifacts environment, that houses a custom configuration for StyleCop.Analyzers so that the configuration for coding standards can be centralised. This all works absolutely fine and can be installed in other projects with no issue.

I have a separate class library which is being built into a Nuget package, and this project utilises my custom StyleCop package. This package also builds correctly, but in the list of dependencies is my custom StyleCop.Analyzers package. This means that everywhere the class library gets installed, the custom StyleCop.Analyzers package will be installed as well. I don't feel this is correct as it is purely a development-scoped package and should not be included as an actual dependency.

The class library does not feature a .nuspec file, everything is handled through the .csproj and some Azure Pipeline's wizardry. Is the dependency chain correct, or is there something that can be done to ensure that the custom StyleCop.Analyzers package is not listed as a dependency?

答: Turns out if you add <devDependency>true</devDependency> node to the .nuspec file then the dependency does not get shipped to packages that consume it.

Title: StyleCop.Analyzers Nuget Dependencies


问:
Add new id column and fill incremental value to already existing table
I need to add an id column to my table which is having around 500cr rows and update it with  incremental value. Please suggest what is the best way of doing it.
I tried running a query to update the value and store in new table but the query failed after 6 hrs saying timeout. Please help.</p>

答:
I found this to work better when you need to generate numeric ids:</p>

```<code>RANK() OVER(ORDER BY GENERATE_UUID())
</code>```

Body:
I found this to work better when you need to generate numeric ids:

RANK() OVER(ORDER BY GENERATE_UUID())


问:
Do I need Nginx with Gunicorn if I am not serving any static content?
In a typical python server setup it is recommended to have Nginx web server serve the static content and proxy the dynamic requests to  Gunicorn app server.
Now if I am not serving any static content through my python application do I still need Nginx in front of Gunicorn ? What would be the advantages ?
Detailed explanation would be really appreciated.

All the static content is served through CDN and the backend server will only need to serve the APIs(REST). So when I will only server dynamic content, will I need to have Nginx ? Does it have any advantage in case of high load etc.

答:
Even if you don't use NGINX for serving static assets putting gunicorn behind a proxy server is the recommended setup.

For example, putting gunicorn behind a proxy will allow to add some back pressure to your system in order to protect you from attacks such as Slowloris.


问:
How can mod_rewrite choose the correct RewriteCond in an ElseIf logic in order to decide whether to add WWW or not?
I'm looking for the following logic:

If the Host has only 1 dot, add www (e.g. example.com will turn to www.example.com)

Else, if the Host starts with www, remove it (e.g. www.dummy.example.com will turn to dummy.example.com)

I'd like to keep it general, no example.com inside the code.

Here's what I have so far with what I need commented out:

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [L,R=301]
# ElseIf
# RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
# RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,QSA,NC,L]
</code>```

答:
Have it like this:</p>

```<code>RewriteEngine On

# check for single dot
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# ElseIf check for www and 2 or more dots
RewriteCond %{HTTP_HOST} ^www\.([^.]+\.[^.]+\..+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,NE,L]
</code>```

Body:
I'm looking for the following logic:

If the Host has only 1 dot, add www (e.g. example.com will turn to www.example.com)

Else, if the Host starts with www, remove it (e.g. www.dummy.example.com will turn to dummy.example.com)

I'd like to keep it general, no example.com inside the code.

Here's what I have so far with what I need commented out:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [L,R=301]
# ElseIf
# RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
# RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,QSA,NC,L]

Body:
Have it like this:

RewriteEngine On

# check for single dot
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# ElseIf check for www and 2 or more dots
RewriteCond %{HTTP_HOST} ^www\.([^.]+\.[^.]+\..+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,NE,L]


问:
Unable to properly convert tf.keras model to quantized format for coral TPU
I'am trying to convert a tf.keras model based on mobilenetv2 with transpose convolution using latest tf-nighlty. Here is the conversion code

```<code>#saved_model_dir='/content/ksaved'  # tried from saved model also
#converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)

converter = tf.lite.TFLiteConverter.from_keras_model(reshape_model)
converter.experimental_new_converter=True
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8

converter.representative_dataset = representative_dataset_gen

tflite_quant_modell = converter.convert()
open("/content/model_quant.tflite", "wb").write(tflite_quant_modell)
</code>```

The conversion was successful(in google colab); but it has quantize and dequantize operators at the ends(as seen using netron). All operators seems to be supported. Representative data set images are float32 in generator and the model has a 4 channel float32 input by default. It looks like we need a UINT8 input and output inside model for coral TPU. How can we properly carry out this conversion?

Ref:-

Full integer quantization of weights and activations

How to quantize inputs and outputs of optimized tflite model

Coral Edge TPU Compiler cannot convert tflite model: Model not quantized

I tried with 'tf.compat.v1.lite.TFLiteConverter.from_keras_model_file' instead of v2 version.I got error: "Quantization not yet supported for op: TRANSPOSE_CONV" while trying to quantize the model in latest tf 1.15 (using representative dataset) and "Internal compiler error. Aborting! " from coral tpu compiler using tf2.0 quantized tflite

Tflite model @ https://github.com/tensorflow/tensorflow/issues/31368

It seems to work until the last constitutional block (1x7x7x160)
The compiler error(Aborting) does not give any information regarding the potential cause and all types of convolutional layers seems to be supported as per coral docs.

Coral doc: https://coral.ai/docs/edgetpu/models-intro/#quantization

答:
Here is a dummy model example of quantizing a keras model. Notice I'm using strict tf1.15 for the example, because tf2.0 deprecated:

```<code>converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
</code>```

with the from_keras_model api. I think the most confusing thing about this is that you can still call it but nothing happens. This means that model will still take in float inputs. I notice that you are using tf2.0, because from_keras_model is a tf2.0 api. Coral still suggest using tf1.15 for converting model for now. I suggest downgrading tensorflow or maybe even just use this (while keeping tf2.0, it may or may not work):

```<code>tf.compat.v1.lite.TFLiteConverter.from_keras_model_file
</code>```

More on it here.

Body:
I'am trying to convert a tf.keras model based on mobilenetv2 with transpose convolution using latest tf-nighlty. Here is the conversion code

#saved_model_dir='/content/ksaved'  # tried from saved model also
#converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)

converter = tf.lite.TFLiteConverter.from_keras_model(reshape_model)
converter.experimental_new_converter=True
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8

converter.representative_dataset = representative_dataset_gen

tflite_quant_modell = converter.convert()
open("/content/model_quant.tflite", "wb").write(tflite_quant_modell)

The conversion was successful(in google colab); but it has quantize and dequantize operators at the ends(as seen using netron). All operators seems to be supported. Representative data set images are float32 in generator and the model has a 4 channel float32 input by default. It looks like we need a UINT8 input and output inside model for coral TPU. How can we properly carry out this conversion?

Ref:-

Full integer quantization of weights and activations

How to quantize inputs and outputs of optimized tflite model

Coral Edge TPU Compiler cannot convert tflite model: Model not quantized

I tried with 'tf.compat.v1.lite.TFLiteConverter.from_keras_model_file' instead of v2 version.I got error: "Quantization not yet supported for op: TRANSPOSE_CONV" while trying to quantize the model in latest tf 1.15 (using representative dataset) and "Internal compiler error. Aborting! " from coral tpu compiler using tf2.0 quantized tflite

Tflite model @ https://github.com/tensorflow/tensorflow/issues/31368

It seems to work until the last constitutional block (1x7x7x160)
The compiler error(Aborting) does not give any information regarding the potential cause and all types of convolutional layers seems to be supported as per coral docs.

Coral doc: https://coral.ai/docs/edgetpu/models-intro/#quantization

Body:
Here is a dummy model example of quantizing a keras model. Notice I'm using strict tf1.15 for the example, because tf2.0 deprecated:

converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8

with the from_keras_model api. I think the most confusing thing about this is that you can still call it but nothing happens. This means that model will still take in float inputs. I notice that you are using tf2.0, because from_keras_model is a tf2.0 api. Coral still suggest using tf1.15 for converting model for now. I suggest downgrading tensorflow or maybe even just use this (while keeping tf2.0, it may or may not work):

tf.compat.v1.lite.TFLiteConverter.from_keras_model_file

More on it here.


问:
reducing the weighting of one of the x variables in glmnet
I can create a model using glmnet.
However if I know beforehand that the contribution of one variable is weak (say x[,1]) how can I reduce its contribution in the glmnet function?

```<code>library(glmnet)
x <- matrix(rnorm(100*20),100,20)
y <- rnorm(100)
fit1 <- glmnet(x,y)
print(fit1)
coef(fit1,s=0.01) # extract coefficients at a single value of lambda
predict(fit1,newx=x[1:10,],s=c(0.01,0.005)) # make predictions
</code>```

答: Why just not remove it? I don't think you can the reduce the "contribution" of one variable. That variable makes noise to your prediction. When an independent variable added to a model the R² is increased, no matter what. If that variable does not have any relationship to dependent variable( which is your situation ) smaller amount of "contribution" is added to R².  If dependent(x) and independent(y) does have a relationship then the greater amount of R² is achieved which means you can explain the y with x better.</p>

Body:
I can create a model using glmnet.
However if I know beforehand that the contribution of one variable is weak (say x[,1]) how can I reduce its contribution in the glmnet function?

library(glmnet)
x <- matrix(rnorm(100*20),100,20)
y <- rnorm(100)
fit1 <- glmnet(x,y)
print(fit1)
coef(fit1,s=0.01) # extract coefficients at a single value of lambda
predict(fit1,newx=x[1:10,],s=c(0.01,0.005)) # make predictions


问:
Not able to return value in django templetes using class-based view
I am new to Django and I don't know much about class-based view. I was trying to return value in Django template and  I am not able to access those value using template tag.I was trying to print value of distance and duration which you can see in my chart.html code.
 Here is my views.py code

```<code>class chartView(TemplateView):
    template_name = 'chart.html'

    def calculate(self):
        self.res=requests.get('https://ipinfo.io/')
        self.data=self.res.json()
        self.current_loc=self.data['city']
        gmaps = googlemaps.Client(key='****************************')
        my_dist = gmaps.distance_matrix(self.current_loc,'bhaktapur')['rows'][0]['elements'][0]
        # Printing the result
        #the variable name describes the distance and time for that bloodbank eg:-redcross,whitecross etc.
        redcross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'lalitpur')['rows'][0]['elements'][0]
        whitecross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'jorpati')['rows'][0]['elements'][0]
        greencross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'maharajgunj')['rows'][0]['elements'][0]
        yellowcross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        dist_list=[redcross,whitecross,greencross,yellowcross]

        return render(request,'chart.html',{'dist_list': dist_list})

    def get_context_data(self, **kwargs):
        context  = super().get_context_data(**kwargs)
        context["qs"]= app.objects.all()
        return context
</code>```

my url.py code

```<code>urlpatterns = [

    re_path(r'chart.html/$',views.chartView.as_view(),name="Charts"),
]
urlpatterns += staticfiles_urlpatterns()
</code>```

chart.html code

```<code>{% for items in qs %}
<div class="conty">
    <canvas class="myChart"></canvas>

</div><br><br>
<div align="center">
    <table>
        <tr>
            <th>{{items.name}}</th>
            <th>{{dist_list[0]['distance']}}</th>
            <th>{{dist_list[0]['duration']}}</th>
        </tr>
    </table>
</div>

{% endfor %}
</code>```

and my error is

```<code>django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[0]['duration']' from 'dist_list[0]['duration']'
[19/Feb/2020 00:32:22] "GET /chart.html/ HTTP/1.1" 500 159883
</code>```

答:
```<code>        <th>{{dist_list[0]['duration']}}</th>
</code>```

or

```<code>        <th>{{dist_list[0].get('duration')}}</th>
</code>```

instead of

```<code>        <th>{{dist_list[0][duration]}}</th>
</code>```

Also replace the calculate function as following:

```<code>class ChartView(TemplateView):
    template_name = 'chart.html'

    def get_context_data(self, **kwargs):
        context  = super().get_context_data(**kwargs)
        context["qs"]= app.objects.all()

        res=requests.get('https://ipinfo.io/')
        data=self.res.json()
        current_loc=self.data['city']
        gmaps = googlemaps.Client(key='****************************')
        my_dist = gmaps.distance_matrix(self.current_loc,'bhaktapur')['rows'][0]['elements'][0]
        # Printing the result
        #the variable name describes the distance and time for that bloodbank eg:-redcross,whitecross etc.
        redcross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'lalitpur')['rows'][0]['elements'][0]
        whitecross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'jorpati')['rows'][0]['elements'][0]
        greencross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'maharajgunj')['rows'][0]['elements'][0]
        yellowcross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        dist_list=[redcross,whitecross,greencross,yellowcross]
        context['dist_list'] = dist_list
        return context
</code>```

Body:
I am new to Django and I don't know much about class-based view. I was trying to return value in Django template and  I am not able to access those value using template tag.I was trying to print value of distance and duration which you can see in my chart.html code.
 Here is my views.py code

class chartView(TemplateView):
    template_name = 'chart.html'

    def calculate(self):
        self.res=requests.get('https://ipinfo.io/')
        self.data=self.res.json()
        self.current_loc=self.data['city']
        gmaps = googlemaps.Client(key='****************************')
        my_dist = gmaps.distance_matrix(self.current_loc,'bhaktapur')['rows'][0]['elements'][0]
        # Printing the result
        #the variable name describes the distance and time for that bloodbank eg:-redcross,whitecross etc.
        redcross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'lalitpur')['rows'][0]['elements'][0]
        whitecross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'jorpati')['rows'][0]['elements'][0]
        greencross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'maharajgunj')['rows'][0]['elements'][0]
        yellowcross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        dist_list=[redcross,whitecross,greencross,yellowcross]

        return render(request,'chart.html',{'dist_list': dist_list})

    def get_context_data(self, **kwargs):
        context  = super().get_context_data(**kwargs)
        context["qs"]= app.objects.all()
        return context

my url.py code

urlpatterns = [

    re_path(r'chart.html/$',views.chartView.as_view(),name="Charts"),
]
urlpatterns += staticfiles_urlpatterns()

chart.html code

{% for items in qs %}

    <canvas class="myChart"></canvas>

            {{items.name}}
            {{dist_list[0]['distance']}}
            {{dist_list[0]['duration']}}

{% endfor %}

and my error is

django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[0]['duration']' from 'dist_list[0]['duration']'
[19/Feb/2020 00:32:22] "GET /chart.html/ HTTP/1.1" 500 159883

Body:
        <th>{{dist_list[0]['duration']}}</th>

or

        <th>{{dist_list[0].get('duration')}}</th>

instead of

        <th>{{dist_list[0][duration]}}</th>

Also replace the calculate function as following:

class ChartView(TemplateView):
    template_name = 'chart.html'

    def get_context_data(self, **kwargs):
        context  = super().get_context_data(**kwargs)
        context["qs"]= app.objects.all()

        res=requests.get('https://ipinfo.io/')
        data=self.res.json()
        current_loc=self.data['city']
        gmaps = googlemaps.Client(key='****************************')
        my_dist = gmaps.distance_matrix(self.current_loc,'bhaktapur')['rows'][0]['elements'][0]
        # Printing the result
        #the variable name describes the distance and time for that bloodbank eg:-redcross,whitecross etc.
        redcross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'lalitpur')['rows'][0]['elements'][0]
        whitecross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'jorpati')['rows'][0]['elements'][0]
        greencross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        my_dist = gmaps.distance_matrix(self.current_loc,'maharajgunj')['rows'][0]['elements'][0]
        yellowcross={
        'distance':my_dist['distance']['text'],
        'duration':my_dist['duration']['text']
        }
        dist_list=[redcross,whitecross,greencross,yellowcross]
        context['dist_list'] = dist_list
        return context