Failed to discover available identity versions when contacting http://xxx.xxx.xxx.xxx:5000/v3

Question: I've searched high and low for a resolution to this, and it seems that most people are having issues with the service not running at all or not being able to connect, which I am not having a problem with.
I'm getting this error after following the Keystone installation guide for the Ussuri OpenStack release.
The full error is:
Failed to discover available identity versions when contacting http://xxx.xxx.xxx.xxx:5000/v3. Attempting to parse version from URL.
Unexpected exception for http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens: Failed to parse: http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens

It was caused by running this command: openstack domain create --description 'Example' example
If I curl the /v3 URL, I get:
{
  "version": {
    "id": "v3.14",
    "status": "stable",
    "updated": "2020-04-07T00:00:00Z",
    "links": [
      {
        "rel": "self",
        "href": "http://xxx.xxx.xxx.xxx:5000/v3/"
      }
    ],
    "media-types": [
      {
        "base": "application/json",
        "type": "application/vnd.openstack.identity-v3+json"
      }
    ]
  }
}

When I try to get the /v3/auth/tokens URL I get the response:
< HTTP/1.1 401 UNAUTHORIZED
< Date: Tue, 22 Sep 2020 17:21:26 GMT
< Server: Apache/2.4.37 (centos) OpenSSL/1.1.1c mod_wsgi/4.6.4 Python/3.6
< WWW-Authenticate: Keystone uri="http://xxx.xxx.xxx.xxx:5000/v3"
< Content-Length: 109
< Vary: X-Auth-Token
< x-openstack-request-id: req-3ac7aec3-1a0e-4fdd-a5ee-2ffecbd15151
< Content-Type: application/json
<
{"error":{"code":401,"message":"The request you have made requires authentication.","title":"Unauthorized"}}

In the keystone.log in /var/log/keystone/keystone.log there is a message that says the request you made requires authentication as well.
I get no errors in the logs in correspondence with running the openstack command.
Also this is the OpenStack environment variables that I have set:
export OS_USERNAME=admin
export OS_PASSWORD="***"
export OS_PROJECT_NAME=admin
export OS_USER_DOMAIN_NAME=Default
export OS_PROJECT_DOMAIN_NAME=Default
export OS_AUTH_URL="http://xxx.xxx.xxx.xxx:5000/v3"
export OS_IDENTITY_API_VERSION=3

The password does have a few punctuation characters in it, I thought maybe that was the issue, but I didn't want to have to restart the installation from scratch to test a long shot hypothesis.
Any help is greatly appreciated.
Here is the output of running the openstack command with the --debug flag:
START with options: domain create --debug --description Example example
options: Namespace(access_key='', access_secret='***', access_token='***', access_token_endpoint='', access_token_type='', application_credential_id='', application_credential_name='', application_credential_secret='***', auth_methods='', auth_type='', auth_url='http://xxx.xxx.xxx.xxx:5000/v3', cacert=None, cert='', client_id='', client_secret='***', cloud='', code='', consumer_key='', consumer_secret='***', debug=True, default_domain='default', default_domain_id='', default_domain_name='', deferred_help=False, discovery_endpoint='', domain_id='', domain_name='', endpoint='', identity_provider='', insecure=None, interface='public', key='', log_file=None, openid_scope='', os_beta_command=False, os_compute_api_version='', os_identity_api_version='3', os_image_api_version='', os_network_api_version='', os_object_api_version='', os_project_id=None, os_project_name=None, os_volume_api_version='', passcode='', password='***', profile='', project_domain_id='', project_domain_name='default', project_id='', project_name='admin', protocol='', redirect_uri='', region_name='', remote_project_domain_id='', remote_project_domain_name='', remote_project_id='', remote_project_name='', service_provider='', system_scope='', timing=False, token='***', trust_id='', user_domain_id='', user_domain_name='default', user_id='', username='admin', verbose_level=3, verify=None)
Auth plugin password selected
auth_config_hook(): {'api_timeout': None, 'verify': True, 'cacert': None, 'cert': None, 'key': None, 'baremetal_status_code_retries': '5', 'baremetal_introspection_status_code_retries': '5', 'image_status_code_retries': '5', 'disable_vendor_agent': {}, 'interface': 'public', 'floating_ip_source': 'neutron', 'image_api_use_tasks': False, 'image_format': 'qcow2', 'message': '', 'network_api_version': '2', 'object_store_api_version': '1', 'secgroup_source': 'neutron', 'status': 'active', 'auth': {'user_domain_name': 'default', 'project_domain_name': 'default', 'project_name': 'admin'}, 'verbose_level': 3, 'deferred_help': False, 'debug': True, 'default_domain': 'default', 'timing': False, 'auth_url': 'http://xxx.xxx.xxx.xxx:5000/v3', 'username': 'admin', 'password': '***', 'beta_command': False, 'identity_api_version': '3', 'region_name': '', 'auth_type': 'password', 'networks': []}
defaults: {'api_timeout': None, 'verify': True, 'cacert': None, 'cert': None, 'key': None, 'auth_type': 'password', 'baremetal_status_code_retries': 5, 'baremetal_introspection_status_code_retries': 5, 'image_status_code_retries': 5, 'disable_vendor_agent': {}, 'interface': None, 'floating_ip_source': 'neutron', 'image_api_use_tasks': False, 'image_format': 'qcow2', 'message': '', 'network_api_version': '2', 'object_store_api_version': '1', 'secgroup_source': 'neutron', 'status': 'active'}
cloud cfg: {'api_timeout': None, 'verify': True, 'cacert': None, 'cert': None, 'key': None, 'baremetal_status_code_retries': '5', 'baremetal_introspection_status_code_retries': '5', 'image_status_code_retries': '5', 'disable_vendor_agent': {}, 'interface': 'public', 'floating_ip_source': 'neutron', 'image_api_use_tasks': False, 'image_format': 'qcow2', 'message': '', 'network_api_version': '2', 'object_store_api_version': '1', 'secgroup_source': 'neutron', 'status': 'active', 'auth': {'user_domain_name': 'default', 'project_domain_name': 'default', 'project_name': 'admin'}, 'verbose_level': 3, 'deferred_help': False, 'debug': True, 'default_domain': 'default', 'timing': False, 'auth_url': 'http://xxx.xxx.xxx.xxx:5000/v3', 'username': 'admin', 'password': '***', 'beta_command': False, 'identity_api_version': '3', 'region_name': '', 'auth_type': 'password', 'networks': []}
compute API version 2.1, cmd group openstack.compute.v2
identity API version 3, cmd group openstack.identity.v3
image API version 2, cmd group openstack.image.v2
network API version 2, cmd group openstack.network.v2
object_store API version 1, cmd group openstack.object_store.v1
volume API version 3, cmd group openstack.volume.v3
neutronclient API version 2, cmd group openstack.neutronclient.v2
command: domain create -> openstackclient.identity.v3.domain.CreateDomain (auth=True)
Auth plugin password selected
auth_config_hook(): {'api_timeout': None, 'verify': True, 'cacert': None, 'cert': None, 'key': None, 'baremetal_status_code_retries': '5', 'baremetal_introspection_status_code_retries': '5', 'image_status_code_retries': '5', 'disable_vendor_agent': {}, 'interface': 'public', 'floating_ip_source': 'neutron', 'image_api_use_tasks': False, 'image_format': 'qcow2', 'message': '', 'network_api_version': '2', 'object_store_api_version': '1', 'secgroup_source': 'neutron', 'status': 'active', 'auth': {'user_domain_name': 'default', 'project_domain_name': 'default', 'project_name': 'admin'}, 'additional_user_agent': [('osc-lib', '2.0.0')], 'verbose_level': 3, 'deferred_help': False, 'debug': True, 'default_domain': 'default', 'timing': False, 'auth_url': 'http://xxx.xxx.xxx.xxx:5000/v3', 'username': 'admin', 'password': '***', 'beta_command': False, 'identity_api_version': '3', 'region_name': '', 'auth_type': 'password', 'networks': []}
Using auth plugin: password
Using parameters {'auth_url': 'http://xxx.xxx.xxx.xxx:5000/v3', 'project_name': 'admin', 'project_domain_name': 'default', 'username': 'admin', 'user_domain_name': 'default', 'password': '***'}
Get auth_ref
REQ: curl -g -i -X GET http://xxx.xxx.xxx.xxx:5000/v3 -H "Accept: application/json" -H "User-Agent: openstacksdk/0.46.0 keystoneauth1/4.0.0 python-requests/2.22.0 CPython/3.6.8"
Failed to discover available identity versions when contacting http://xxx.xxx.xxx.xxx:5000/v3. Attempting to parse version from URL.
Making authentication request to http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens
Unexpected exception for http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens: Failed to parse: http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens
Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/requests/models.py", line 379, in prepare_url
    scheme, auth, host, port, path, query, fragment = parse_url(url)
  File "/usr/lib/python3.6/site-packages/urllib3/util/url.py", line 398, in parse_url
    return six.raise_from(LocationParseError(source_url), None)
  File "<string>", line 3, in raise_from
urllib3.exceptions.LocationParseError: Failed to parse: http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/keystoneauth1/session.py", line 1004, in _send_request
    resp = self.session.request(method, url, **kwargs)
  File "/usr/lib/python3.6/site-packages/requests/sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "/usr/lib/python3.6/site-packages/requests/sessions.py", line 462, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/usr/lib/python3.6/site-packages/requests/models.py", line 313, in prepare
    self.prepare_url(url, params)
  File "/usr/lib/python3.6/site-packages/requests/models.py", line 381, in prepare_url
    raise InvalidURL(*e.args)
requests.exceptions.InvalidURL: Failed to parse: http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/cliff/app.py", line 393, in run_subcommand
    self.prepare_to_run_command(cmd)
  File "/usr/lib/python3.6/site-packages/osc_lib/shell.py", line 493, in prepare_to_run_command
    self.client_manager.auth_ref
  File "/usr/lib/python3.6/site-packages/osc_lib/clientmanager.py", line 202, in auth_ref
    self._auth_ref = self.auth.get_auth_ref(self.session)
  File "/usr/lib/python3.6/site-packages/keystoneauth1/identity/generic/base.py", line 208, in get_auth_ref
    return self._plugin.get_auth_ref(session, **kwargs)
  File "/usr/lib/python3.6/site-packages/keystoneauth1/identity/v3/base.py", line 184, in get_auth_ref
    authenticated=False, log=False, **rkwargs)
  File "/usr/lib/python3.6/site-packages/keystoneauth1/session.py", line 1131, in post
    return self.request(url, 'POST', **kwargs)
  File "/usr/lib/python3.6/site-packages/keystoneauth1/session.py", line 913, in request
    resp = send(**kwargs)
  File "/usr/lib/python3.6/site-packages/keystoneauth1/session.py", line 1024, in _send_request
    raise exceptions.UnknownConnectionError(msg, e)
keystoneauth1.exceptions.connection.UnknownConnectionError: Unexpected exception for http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens: Failed to parse: http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens
clean_up CreateDomain: Unexpected exception for http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens: Failed to parse: http://xxx.xxx.xxx.xxx:5000/v3/auth/tokens
END return value: 1

Also I have checked that the keystone wsgi instances are running.  Everything appears to be in place, though I'm sure I've missed something. I just can't find it.
Answer: Don't really know if this is connected, but there is an issue (closed) regarding such parsing issues.
See: https://github.com/psf/requests/issues/5476
I could reproduce the issue using
python3 -c "import requests; requests.get('https://google.com');"
with Python 3.6.8 [GCC 8.3.1 20191121] on CentOS 8, however when using Python 3.8.0 (requests installed via pip) it doesn't throw an exception.
Hope this helps.
Edit: Got it working when reinstalling python3-six python3-urllib3 using newer versions.
Source:
https://bugzilla.redhat.com/show_bug.cgi?id=1787227
Comment: Installing the python38 package and then using pip to install the openstackclient package worked for me.  Thanks for the pointer.


Why does the $0$-skeleton have discrete topology in CW complexes?

Question: I am reading about CW complexes. My book uses the following definitions.
Definition: A cell complex $X$ is a Hausdorff space which is the union of disjoint subspaces $e_{\alpha} (\alpha \in \mathcal{A})$ called cells satisfying:
a) To each cell we associate an integer $n \geq 0$ called its dimension. If $e_{\alpha}$ has dimension $n$ we often use the notation $e_{\alpha}^n$ for this cell. We write $X^n$ for the union of all cells $e_{\alpha}^k$ with $k \leq n$. $X^n$ is called the $n$-skeleton.
b) If $e_{\alpha}^n$ is an $n$-cell, there is a "characteristic map" $\chi_{\alpha}: (B^n, S^{n-1}) \to (X, X^{n-1}) $ such that $\chi_{\alpha} |_{B^n - S^{n-1}}$ is a homeomorphism from $B^n - S^{n-1}$ onto $e_{\alpha}^n$.
Definition: If $A \subset X$ is a subset of $X$, we define $K(A)$ to be the intersection of all subcomplexes containing $A$. If $A \subset B$, $K(A) \subset K(B)$. Hence if $p \in e, K(p) = K(e) =K(\overline{e})$. Thus $K(A)$ is a subcomplex.
Definition:
C: $X$ is said to be closure finite if for each cell $e_{\alpha}^n$, $K(e_{\alpha}^n)$ is a finite subcomplex.
W: $X$ is said to have the weak topology if for each subset $F \subset X$, $F$ is closed iff $F \cap \overline{e}_{\alpha}^n$ is compact for each cell $e_{\alpha}^n$.
A cell complex satisfying (C) and (W) is called a CW complex.
Question:
If you look at definition in Hatcher's book, where he defines cell complexes inductively, the first step is to start with a discrete set $X^0$. Therefore, in this case, the fact that $X^0$ has discrete topology is just because of the definition. However, in my case, I don't see why this is necessarily true. However, the result is used in proving certain results later, and I wonder how to show that it is true by my definition.
I was thinking that it has to do with the weak topology; my approach would be to show that every subset is closed, for which it suffices to show that intersection of that subset with every cell is closed. I'm not sure if that leads anywhere; I don't know how to proceed.
Answer: The characteristic map is a continuous map from a compact space to a Hausdorff space, hence it is closed (a classic result in point-set topology), meaning that it maps closed sets to closed sets, so that $e_{\alpha}^{0}$ is closed, so that $\overline{e_{\alpha}^{0}} = e_{\alpha}^{0}$. Then for any subset $F \subset X$, $F \cap \overline{e_{\alpha}^{0}} = F \cap e_{\alpha}^{0} = e_{\alpha}^{0}$, which is a single point, which is always compact, so $F$ is always closed, completing the proof.
Comment: Don't we need to verify that  $F \cap \overline{e}_{\alpha}^n$ is closed for all cells, of any dimension, not just for $0$-cells? Am I missing something? Perhaps, would it be possible to show that $F \cap \overline{e}_{\alpha}^n$ is always finite? (I'm not sure if this is true)
Comment: @Matthew The $0$-skeleton only has $0$-cells.


Permutations and cycles in integers

Question: I am interested in the integers between $100$ and $1000$ who are divisible by $6$. This problem is solvable. However if we add the following restriction the problem will be more complicated. Now we will only count the integers between $100$ and $1000$ who are divisible by 6 and exist of different numbers from the set $\{1, ..., 9\}$. For example, the integers $126$ and $612$ are the same.
How many integers are left between $100$ and $1000$?
Comment: Do you mean that $126$ and $612$ together count for one only?
Comment: Yes that is right! Only integers with different numbers counts. And $0$'s are not allowed.
Comment: And how about $666$? A possibility but with equal (not different) digits?
Comment: Correct, we do not count 666.
Answer: Hint:
The question is equivalent to this problem.
Choose three integers such that sum of these is dibisible by three and at least one of them is even.
Comment: Can you give some more explanation about 'at least one of them is even'. I do not see why this is true.
Comment: @iJup: Since a number is divisible by $6$ if it is even and divisible by $3$.
Answer: Correct me if I am wrong.
The sum of the numbers in the integer between $100$ and $1000$ has to be $0$ mod $3$.
We divide the set $\{1, ..., 9\}$ into $3$ different cosets.

A = $\{3;6;9\}$ - $0$ mod $3$
B = $\{1;4;7\}$ - $1$ mod $3$
C = $\{2;5;8\}$ - $2$ mod $3$

Possibilities are:

$0 + 0 +0$ - 1 possibility (936)
$1 + 1 +1$ - 1 possibility (714)
$2 + 2 +2$ - 1 possibility (528)
$0 + 1 +2$ - ends on a $2, 4, 6, 8$ will all bring $3 \cdot 3$ possibilities.

Total number of possibilities is $4 \cdot 9 + 3 \cdot 1$.
However it seems that we are still counting the same integer combinations. For example 648, 864 and 486. Finally we will count 35 integers.

Permutations and cycles in integers


SignalR Refused to connect to [url] because it violates the following Content Security Policy directive

Question: I've created a SignalR project in .NET 4.8.
I was using signalR correctly as described in the documentation. My two script tags:

I'm initializing the connection in the following way:
$.connection.hub.url = "https://mySignalRServer/signalr";
let screencasting = $.connection.screencastingHub;

$.connection.hub.qs = 'uuid=' + masterGuid + '&master=true';
$.connection.hub.logging = true;
screencasting.client.changeTransport = changeTransport;

$.connection.hub.start({ transport: 'webSockets' }).done(function () {
    console.log('---Connected to signalR server via WebSockets');
});

When the code hits the following line $.connection.hub.start() the following error occurs:

jquery.signalR-2.4.1.js:1871 Refused to connect to
  'wss://mySignalRServer/signalr/connect?transport=webSockets&clientProtocol=2.1&uuid=56b12321-1091-48aa-b52f-dc1407b3804a&master=true&connectionToken=WOP95HhCwdN7ogruYHpfrrsZofenOqo5kRDVLJh6S6zUH0AN74cUTEL44qORGBCRMWiGH5ei12826qLB%2BMHFa7YqaN1KeIYmG7dUaE%2B6DiF2CIwaNTl4dwbwR6t3Cxgx&connectionData=%5B%7B%22name%22%3A%22screencastinghub%22%7D%5D&tid=8'
  because it violates the following Content Security Policy directive:
  "connect-src https:".

Interestingly enough, this code was working fine. Could it be a sertificate error? How can I add this Content Security Policy (CSP). (enter link description here)
Is it added as header somewhere? In the html head?
Answer: After a lot of tests, this is the solution that worked out for me:
In Web.config file I've added the following line:
<httpProtocol>
      <customHeaders>
        <add name="Content-Security-Policy" value="default-src https:; connect-src https: wss:" />
      </customHeaders>
</<httpProtocol>

For more information, check this and that out.


Football - Who gets the match ball, if 2 or more players score hat-tricks in a game?

Question: In football, if a player scores a hat-trick, he usually takes the match ball with him as a souvenir.
But if 2 or more players score a hat-trick in a single game, then who gets to take the match ball with him?
Comment: @ThomasDB: the fact that you don't see (or recall) it doesn't mean it doesn't happen: here is a picture of Messi posing with all the balls he scored hat-tricks with (http://bit.ly/1E0Q6OZ), and here is one of Ronaldo doing the same (http://bit.ly/1KyvC52). A google search for "takes hat-trick goal" returns several images of hat-trick scorers leaving the field with the ball in their hands, or getting it signed by their teammates.
Comment: @ThomasDB - something being a little uncommon does not mean it is obsolete. I think it makes it more interesting on the other hand.
Comment: There is not the one match ball, so if they really both want one, the second one will have to pick one from a ball boy.
Comment: A reference to multiple balls being used in a game?
Comment: @ThomasDB - While what you say can be true, but could you help by providing some references. Thx.
Comment: I doubt there is anything mandating what would happen. This is more of a custom than a rule ... the normal one hat trick going to the scorer is just a gift he gets ...
Comment: References which show that these circumstances have happened.
Comment: I honestly do not think it ever happened at all, it's also not that common to take the match ball after a hattrick. I watch easily 10 games a week and have no recollection of a player taking/getting the ball after he has scored a hattrick. I was just trying to point out the sillyness of the possibility of two players fighting over a match ball if there are used more than one in a game. That's also why it's a comment, not an answer.
Comment: @Koldito, I was not saying that taking the ball does not happen. I was pointing out the uncommonness of it, which leads to the question being obsolete.
Comment: The players who scored a hat trick do not need to have the ball.
Answer: As usual, the very excellent The Knowledge series of The Guardian has an answer. The January 28, 2004 entry goes like this:

"On Sunday, Empoli drew 3-3 with Juventus, Tommaso Rocchi bagging a hat-trick for the home side, and David Trezeguet claiming all three goals for Juve," says Stuart Bruce. "With the scorers of hat-tricks traditionally claiming the match ball, who gets to take it home in a situation like this? Has there ever been a situation of three or more players all with a valid claim to the match ball in any one match?"
But, we have consulted with the FA stattos on this one and are told that though there are no rules, the convention would in all likelihood be that the first player to score a hat-trick would receive the match ball. Thus, as Rocchi completed his hat-trick in the 62nd minute, 14 minutes before Trezeguet made it 3-3, the Empoli striker should have be the one making space on his mantelpiece, which we hope is level or else the ball will keep rolling off it.
As far as your second question goes Stuart, there are in fact several examples of three players scoring a hat-trick in one game. The last instance - which, incidentally, is also the last instance of a team scoring 10 goals in an English league game - comes from November 7 1987, when Manchester City beat Huddersfield Town 10-1 in the old Second Division.
Answer: On Wednesday February 3rd, 2016, FC Barcelona vs Valencia, in the Copa Del Rey, Luis Suarez and Messi both scored a hat-trick. Suarez scored 4 goals, Messi scored 3 goals. At the end of the match, they both left with a football.
Sources:

Luis Suárez hits four, Lionel Messi three as Barcelona rout Valencia 7-0
Lionel Messi's 'great gesture' with Luis Suarez over match ball
Comment: I have added some links, so that the claims in this answer are not without any reference. I hope you do not mind.


Boost VS Drupal Cache

Question: I'm using Boost and Drupal internal cache on two different websites and i m remarking that the site with internal cache is more quickly than the site with the Boost module .
So I'm asking which between the two methodes are suitable ?
Thank  you very much
Comment: This needs more information. Boost, properly configured, skips a Drupal bootstrap (and actually avoids all PHP) entirely, so would always be faster than the built in cache. However, Boost is certainly not a drop-in module. It requires customizing the `.htaccess` file among other things.
Comment: i already well configured my boost module and edited my htacess file
Answer: Boost bypasses execution of Drupal's PHP and serves static files.  So unless you have other problems, it should always be much faster than the standard Drupal cache.  Be aware that it only works for anonymous users.
View source on your pages when running boost and make sure they have a comment at the end that says cached by boost.  Boost puts that comment there by default.  If you haven't disabled it, and it's not there, boost isn't working properly.  It's usually caused by incorrect or missing .htaccess rules.  If you don't see this comment, you won't see an error on the status page.  Your site will work normally, but is not being cached.
It looks like this:

Comment: Thank you very much but where exactly i have to see the boost comment? because i installed the module like it is indicated and the drupal status is fine, thank you
Comment: Added example to answer.  You may not see an error on the status page if your .htaccess rules are not correct.
Comment: Here is how i did: i copied the code generated by the boost module and i past it into the .htaccess file
Comment: Yes and on certain server configurations I've seen that not work.  Are you seeing the comments in the source?
Comment: Unfortunatley no
Comment: Ok, then the default htaccess rules aren't working for you.  I've seen this happen on some share hosts where the default paths are not correct.  There are a bunch of options you can try on the settings page.  Regenerate the rules and try again.  You'll need to log out and refresh the page at least once before you'll see the comment.
Comment: Please tell me if i'm wrong:For my boost configuration i am using for Servers URL or Name: %{HTTP_HOST} for Document Root: %{DOCUMENT_ROOT} In another way, i'm confused by what do you mean by the root of the web server :i'm hosting my website in a host company and i dropped my drupal files in the 'www' folder ,that mean that my index.php is at www/index.php . So should i modify the 'www/.htaccess ' file or the .htaccess situated at the same level as the www folder
Comment: Modify the one at www/.htaccess.  I'm not sure if HTTP_HOST or DOCUMENT_ROOT are correct.  It depends on the host.  On one host I use, I had to manually enter the path on their filesystem because none of the options were correct for mod_rewrite to work.
Comment: If you are using Cloudflare you will not see any comments in your source. That could make you think that boost is not working/configured properly. If you are using Cloudflare, visit your site in the direct subdomain assigned (without Cloudflare).

Boost VS Drupal Cache


SMTP hub or redirector, is this possible?

Question: Situation:
I need to be able to set one SMTP server set of details into some software that sends out emails. However, the software sends emails from many different sender domains, all hosted on different Microsoft tenants. There might be over 10,000 emails going through this per day across all 50+ sender domains combined.
Proposed solution:
I assume what I need is to point the software SMTP settings to a service (let's call it an SMTP HUB) which then redirects the SMTP to the appropriate SMTP server (Microsoft tenant) for the sender address, for each email that comes through. I then simply need to get the Microsoft tenants to trust this SMTP hub as a sending source by IP address (email connector in exchange admin portal).
Knowledge I am missing:
Can you tell me my options for the "SMTP HUB" part of the equation?
I can easily run up a Linux or windows host server to run this, is there a turnkey solution for this?
Thank you in advance, for even reading this far.
Michael A.
Comment: Are your requirements really just that: receiving authenticated mail and relaying? Almost any mail server software can do that. If you need to enforce any non-trivial restrictions, e.g. specifying which domains exactly you want to relay for, you probably want to use Postfix as its configuration syntax for such purposes is clear and well documented.
Comment: How about the anonymous relay on Exchange server?
Comment: I will look into PostFix. Are you sure it will forward to the relevant SMTP server based on sender domain?
Answer: How about the Exchange server?
But if you are not familiar with Exchange, it will take a long time to learn it.
Comment: Are you sure Exchange server can do this? Might be more expensive than an alternative, and I have worked with it before, but I didn't realise it could. If so, I wonder if exchange online can do it then, I cannot see a way to set this up there on office 365


Why does the author define these "logical notations" for set logic with "if then" and &?

Question: In Section 1.1 of "Set Theory for Computer Science", the author defines
$ \forall x \in X. P(x) $ and $ \exists x \in X.P(x) $ as shorthand for
$ \forall x.(x \in X \Rightarrow P(x)) $ and $ \exists x.(x \in X \space \& \space P(x)) $, respectively.
The author's explanation of these shorthand notations in English ("for all x in X, P(x)") make sense to me, but I'm not really sure where the "if-then" $ \Rightarrow $ and "and" $ \& $ come in.
Comment: It's not $\forall x\in X\implies P(x)$, it's $\forall x. x\in X\implies P(x)$. For all $x$, if $x\in X$ then $P(x)$. Same goes for the other one.
Comment: Your copied it wrong.
Comment: @Thomas: More accurately, it's not a legal construct in a minimalist version of formal logic, although it is legal in more user-friendly versions (e.g. by making the definition the OP is asking about!). Actually, in some versions of formal set theory, *unbounded* quantification is strictly illegal: all quantifiers must be bound. i.e. it is legal to write $\forall x \in X: P(x)$ but not $\forall x: x \in X \implies P(x)$.
Comment: To be even clearer, I've added parentheses: $$\forall x\in X.P(x)$$ is shorthand for $$\forall x.(x\in X\implies P(x))$$
Comment: The main reason for the shorthand is that it is very common form, and it makes things clearer.
Comment: For example, humans tends to say, "Every $x$ in collection $X$ has property $P$." But that isn't a legal construct in formal logic. It can be formalized as "For every $x$, if $x$ is in $X$ then $x$ has property $P$." That's a longer sentence, and obscures the intuitive meaning, so we prefer the shorter sentence.
Comment: Fixed incorrect figures - thanks.
Answer: Remember that quantifiers are taken over the entire universe of discourse. So to limit the quantifier to a certain set you need to somehow "filter" out the set of objects being quantified.
When you quantify with $\forall x$, then you want to say given any $x$, then I don't care if $x\notin X$, but if $x\in X$ then I want to assure that $P(x)$. This is exactly to say $\forall x(x\in X\rightarrow P(x))$, and that's why this is defined to be the meaning of $\forall x\in X.P(x)$.
When you quantify with $\exists x$, then you want to say that there exists an object $x$ satisfying $P$ which happens to be an element of $X$ as well. And this happens to be exactly the meaning of $\exists x(x\in X\land P(x))$. So this is how we define $\exists x\in X. P(x)$.
Comment: The other places you will see this is, say, $\forall x\neq \emptyset\dots$ or $\forall d\mid n\dots$ or other conditionals that start with the variable. We don't otherwise write $\forall Q(x):P(x)$, because it is less clear what variable is being referenced.
Comment: This makes sense. I had (somehow) forgot the whole point of these shorthands was to filter down the universe to a specified set. Thanks guys.
Answer: This is math's version of "typed" versus "untyped" objects.
In set theory, an unbound variable is essentially an untyped object. Or if you prefer, an object of type Set, the type "everything" has. Compare with the type Object from java.
But we can bind variables to other types; the most typical case is when we have a set, and we want to bind the object to a set. e.g we say "let $x$ be a real number" to introduce a new variable $x$ that is bound to the set $\mathbb{R}$. We might say that $\mathbb{R}$ is the type of $x$.
Quantifiers like $\forall x$ introduce variables, but this form introduces an unbound variable (or a variable of type Set, if you prefer). The notation $\forall x \in X$ introduces the variable $x$ and binds it to $X$ at the same time.
And it turns that $\forall x \in X : P(x)$ and $\forall x : x \in X \implies P(x)$ have the same semantics, so it is not unreasonable to define the former as meaning the latter.
As an aside, those who prefer typed logic might prefer to write $\forall x \in \mathbf{Set}: P(x)$ rather than $\forall x: P(x)$.


Pandas - Changing column sequence using index value of column stored in a variable

Question: I have a Dataframe as below:
  col_1 col_2 col_3
0    1    3     2
1    3    5     3
2    3    4     3

I am trying to have the sequence in which the columns are displayed using the index value of the header.
I have the index value of column stored in a variable called val. Set value of val = 1
I have tried the below:
cols = list(df.columns.values)
cols.pop(cols.index(val))
df = df[[val] + cols]

Expected output:
  col_2 col_1 col_3
0    3    1     2
1    5    3     3
2    4    3     3

I however see the sequence has not changed.
Answer: val = 1
cols = list(df.columns.values)
extracted =cols.pop(val)
cols.insert(0,extracted)
df = df[cols]

output
 col_2  col_1   col_3
0   3   1   2
1   5   3   3
2   4   3   3


Angular model getter "is not a function" error

Question: My model:
export class User {

   public username: string;
   private email: string;

   constructor() {
       this.username = undefined;
       this.email = undefined;
   }

   public getUsername(): string {
       return this.username;
   }

In my view I have:
import {User} from '../../models/usermodel';

export classs ... {

   user: Observable<User | null>
   userCollection: AngularFirestoreCollection<User>;
   userLoadedFromFirestore: User[];

   this.userCollection = this.afs.collection('users', ref => ref.where('email', '==', this.sessionData.getUser().getEmail()));
   this.userCollection.valueChanges().subscribe((item => {
       this.userLoadedFromFirestore = item;
       this.userLoadedFromFirestore[0].getUsername();

For accessing getUsername() I get runtime error: is not a function. Why is that? When I do this.userLoadedFromFirestore[0].username instead, it works!
The IDE does not show any errors during compiling...
Answer: You set a type of userLoadedFromFirestore as a User[] type, but when data arrives, it doesn't guarantee that that object will be a User type. Thats why it is a good idea to set the type of incoming data:
subscribe(((item: User[]) => {
And in your case, most likely you need:
this.userLoadedFromFirestore[0].username;
Comment: yes, I mean it doesnt change the fact that the object comming from backend might not have the properties you defined in frontend. By defining types as I wrote, you just receive an error as soon as objects mismatch. Your `item` is not of type of `User[]`. Pleas explain you goal further as I it seams you want to create an instance of `User` with properties coming from database?
Comment: yep, I just later noticed you already tried `this.userLoadedFromFirestore[0].username;` :)
Comment: after doing `subscribe(((item: User[]) => {` I still get the same error
Comment: I would argue that setting parameter types on a method call is an anti-pattern. The return type should be implicitly set by the method returning the data, independent of its invokers (via the generic parameter ).
Comment: so you have a constructor function - instantiate new instance with `new` keyword - `new User` (also probably want to add some arguments to constructor function
Comment: @joh04667 but he didnt set parameter type on a method call. He just typed a variable (`userLoadedFromFirestore: User[];`) and later assign it a value of the incomming object with hope it will behave as an object of that type
Comment: never mind. Im just going with `this.userLoadedFromFirestore[0].username;`
Answer: In my case the solution was to organize the getter outside of the object.
export class UserData {

    public gid: string;

    //Error!
    public gidText(): string{
        return this.gid;
    }

}

Solution:
export class UserService {

    public gidText(): string{
       return this.userData.gid;
    }

    export class UserData {
        public gid: string;
    }
}


Is it ok to save users 70 privileges in the database users table?

Question: I'm currently developing my first serious web application (It's an ERP system). I'm now managing the privileges functionalities in the system and I'm planing to save the privileges along with the users data in the user table. But I'm having about more than 70 privileges that can be granted to users. I never encountered such a huge table before in my short experience and I don't know what could be the consequences later when I put the system in production, I also know if I did it wrong I will have very hard time editing the application later, so I thought It will be good If I asked here before I start doing it.
Is it OK to change table like this
CREATE TABLE `user` (
  `id` int(6) unsigned NOT NULL,
  `name` varchar(70) NOT NULL,
  `type` ENUM('admin','user'),
  PRIMARY KEY (`id`)
)

and adding about 70 columns like this
`p_insertSales` TINYINT(1) NOT NULL,
`p_insertPurchases` TINYINT(1) NOT NULL,
`p_insertCollections` TINYINT(1) NOT NULL,
`p_deleteSales` TINYINT(1) NOT NULL,
`p_deletePurchases` TINYINT(1) NOT NULL,
`p_manageInventory` TINYINT(1) NOT NULL,
`p_insertEntries` TINYINT(1) NOT NULL,
`p_manageAccountingSystem` TINYINT(1) NOT NULL,
`p_deleteEntries` TINYINT(1) NOT NULL,
`p_approveEntries` TINYINT(1) NOT NULL,
`p_seeFinancialReports` TINYINT(1) NOT NULL,
`p_seeLedger` TINYINT(1) NOT NULL,
`p_manageCashAccounts` TINYINT(1) NOT NULL,
`p_insertCurrentAccounts` TINYINT(1) NOT NULL,
`p_seeVisitorsMessages` TINYINT(1) NOT NULL,
`p_seePurchaseOrders` TINYINT(1) NOT NULL,

 -- ... more than 60 more privileges.

Is it OK to do that In terms of performance and software design?
Because I found doing it this way is easier for me to maintain since I'm loading the client data anyway at the beginning of the request processing in the front controller area I can change the privileges later (by adding new ones or removing) In one place.
Comment: That's probably more of a question for dba.stackexchange.com. You can either go that way, or add two other tables: one for roles/privileges, and a pivot table to match the two. The first way means adding columns any time you add a new privilege, the second just requires adding more data.
Comment: I guess it's *OK*, but it's not how I'd do it.
Comment: I highly highly recommend not doing it the way you are planning. Gordon's answer below is 100% right on. You may want to consider adding an extra layer in your user/privilege logic for "Role". A role would be defined with a bunch of privileges and then users would pick up roles. This makes assigning new users to roles (and gaining buckets of privileges) much easier down the road. For now though having a privilege table and a junction table between user/privilege is a great start.
Answer: Probably not a good idea.  You should have a table with one row per privilege:
create table Privileges (
    privilegeId int auto_increment primary key,
    name varchar(255)
);

And a junction table:
create table UserPrivileges (
    userId int not null,
    privilegeId not null,
    constraint fk_UserPrivileges_userid foreign key (userid) references users(userid),
    constraint fk_UserPrivileges_privileges id foreign key (privilegeid) references users(userid)
);

These tables can have other columns.  For instance, Privileges might have other information about the privilege.  UserPrivileges might have the insertion/update date and who made the change.
This structure will make it easy to:

Add new privileges
Remove existing privileges (as a class)
Add and remove privileges from an existing user
Comment: I was mid-answer with the same solution. This is good practice as, as G says, you can amend the list of priviledges. Personally, I would also add `validfrom` and `validto` into the `UserPriviledges` table to allow a history to be recorded
Comment: Note the default table engine should be innodb for references to work.. if your default engine is MyISAM you should add Engine = InnoDB to the create table statements explained here https://dev.mysql.com/doc/refman/5.7/en/using-innodb-tables.html
Answer: Another approach (possibly slower, possibly faster, but certainly more compact):
Group the permissions in some logical way.  (The only necessity is to get the number it perms in a single SET to be under 64.)  Then make a SET of granted/refused items:
CREATE TABLE ... (
    user_id SMALLINT UNSIGNED NOT NULL,
    insert_privs SET ('sales', 'purchases', 'collections', ...) NOT NULL,
    delete_privs SET ('sales', 'purchases', 'collections', ...) NOT NULL,
    ...

Or, the other way (if it is more logical or simplifies the app coding):
CREATE TABLE ... (
    user_id SMALLINT UNSIGNED NOT NULL,
    sales_privs     SET ('insert', 'delete', ...) NOT NULL,
    purchases_privs SET ('insert', 'delete', ...) NOT NULL,
    ...

(or whatever makes sense).
See FIND_IN_SET() as a handy tool for testing for a flag being set.
Also see boolean operators.
Comment: Thank you very much this nice and compact approach. This is the first time I see the `SET` column type but I will never forget about it.


double loop python with matrix

Question: I have a situation with a double loop in python3.6.
I have a matrix with string values, all the position in the matrix are not full. So I have many position with juste '' char. I want to take the first value of each line in the matrix. To do that I've tried a double comprehension list like this :
matrix = data[1:,6:68]
price = [[int(matrix[i,j]) if j!='' for j in matrix[i][j] ] for i in matrix[i]]

But when I run it, I receive this error :
price = [[int(matrix[i,j]) if j!='' for j in matrix[i][j] ] for i in matrix[i]]
                                            ^
SyntaxError: invalid syntax

And I don't understand why it doesn't work.
Could you help me please ?
C.
Comment: can you provide a sample data of 'data' ?
Comment: to your error.......price = [[int(matrix[i,j]) for j in matrix[i][j] if j!='' ] for i in matrix[i]]..........
Comment: Here, for i in matrix[i ] gives a list and when you use it as matrix[i][j] will throw error!!
Answer: The error here
     [[int(matrix[i,j]) if j!='' for j in matrix[i][j] ] for i in matrix[i]]
is, int(matrix[i,j]) if j!='' and then followed by
 matrix[i,j] where, the variable i is a list as a result of first list comprehension and hence will throw the following error..
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple

Therefore,
 [i for i in matrix] #gives each row of matrix!
[[j for j in i if j!=''][0] for i in matrix] #gives all elements in each row that is not null.

so,
[[j for j in i if j!=''][0] for i in matrix] #first element of each row that isn't null!

Sample IO:
>>> matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [[j for j in i if j!=''][0] for i in matrix]
[1, 4, 7]

Comment: If you feel that the answer is appropriate to your question, kindly accept it as shown [here](http://stackoverflow.com/tour)
Comment: Thank's sorry the time delay :-)
Answer: Usually in a comprehension the condition comes after the iterator. i.e.
matrix = data[1:,6:68]
price = [[int(matrix[i,j]) for j in matrix[i][j] if j!='' ] for i in matrix[i]]

Comment: Here, for i in matrix[i ] gives a list and when you use it as matrix[i][j] will throw error!!

double loop python with matrix


How do I create a loop checking app connectivity

Question: I'm trying to create a loop on my app to check Connectivity. So, when the app loads for the first time, the user must be connected to the internet, otherwise he cannot proceed on using the app.
However, I'm trying to create a function that while the user has no internet, the UIAlerView persists on the screen until find an internet connection, then it should be dismissed and another method be lunched. What would be the best way for me to do that?
<code>   let alert = UIAlertController(title: "Primeiro Uso", message: "Voce precisa estar conectado na internet", preferredStyle: UIAlertControllerStyle.alert)

                        // add the actions (buttons)
                        alert.addAction(UIAlertAction(title: "Estou Conectado", style: .default, handler: { action in

                            if Connectivity.isConnectedToInternet != true {

                             //How do I create a loop here until find a connection?
                             //I'd like to persist the UIAlerView until find a connection

                            }
                            //Once the user is connected, this code below should be
                            //lunched
                            getApiData { (cerveja) in
                                arrCerveja = cerveja
                                //Backup
                                do{
                                    let data = try JSONEncoder().encode(arrCerveja)

                                    UserDefaults.standard.set(data, forKey: "backupSaved")
                                    //
                                    self.tableView.reloadData()
                                }catch{print(error)
                                }

                            }}))

                        alert.addAction(UIAlertAction(title: "Cancelar", style: UIAlertActionStyle.cancel, handler: nil))

                        // show the alert
                        self.present(alert, animated: true, completion: nil)
                    }
</code>
Comment: Creating a loop is not a good idea. I would suggest using NSNotification for this. May be this will help https://stackoverflow.com/questions/27310465/detecting-network-connectivity-changes-using-reachability-nsnotification-and-ne
Comment: Hello dude, can you post as an answer?
Answer: you can use this answer
https://stackoverflow.com/a/3597085/2621857
in the appDelegate level of you application.
i think creating loop for checking internet, somehow will pressure the processor to memory leak so i suggest not using a kind of loop to check the internet.
i hope this will work for you .
Comment: Rather than simply linking to an existing answer you should create an answer for *this question*. Alternatively, add a comment to the question referencing the existing answer.  A `Timer` could be a good approach for periodically checking reachability.  There is no reason that a loop should cause a memory leak


Check if lead is known, then based on email address redirect to page

Question: Let me start by stating that I am a beginner in Javascript and I have tried to construct my own code from reading different similar solutions here.
I am creating a 2 step verification in marketo, step one check if the lead is known, step 2 If the lead is known then check if their email address is from an accepted domain to proceed (e.g only leads from the domain marketo.com are allowed to proceed.)
I started by creating a verification landing page, I created a form and hid the submit button, created a rich text field and set an error message (for unknown leads).
Then created a hidden Email field with prefill enabled
Then in the form settings I selected 'If lead is known' option and in the custom HTML, put the following logic

But its not working, Any known lead (using a marketo.com or any other recognised email in marketo) is going to the Invalid_Email page, any idea's?
Answer: It should be the opposite.
Right now, you are checking if @marketo. contains (for example) email@example.com.
You should check if email@example.com contains @marketo..
var allowedEmail = '@marketo.';
if (mktoPrefillFields.Email.indexOf(allowedEmail) != -1) {
    window.location.replace("http://www.example.com/Valid_Email.html");
}
else {
    window.location.replace("http://www.example.com/Invalid_Email.html");
}

Comment: I tried this code, and the page now does not redirect at all. (nothing happens)
Comment: Works fine for me. Tested it on a JSFiddle 30s ago. Replace your window.location by alert to see if it goes in any of the block (maybe your code crash before).
Comment: Just discovered there is a Typo in the prefill field - mktoPreFillFields.Email now works thanks!
Comment: Woops! Indeed, I made a dummy variable instead of this one for the test,didn't notice that typo, sorry! Glad your problem is solved.
Answer: I think k it should be (mktoPreFillFields.Email.indexOf(allowedEmails) != -1
Comment: var allowedEmail = "@marketo.";
if (mktoPrefilLFields.Email.indexOf(allowedEmail) != -1) {
    window.location.replace("http://www.example.com/Valid_Email.html");
}
else {
    window.location.replace("http://www.example.com/Invalid_Email.html");
}

tried this code, did not work, nothing happens


Why isn't BFGS and LBFGS implemented in more areas where gradient descent is applied?

Question: BFGS and LBFGS algorithms are often seen used as optimization methods for non-linear machine learning problems such as with neural networks back propagation and logistic regression.
My question is why arent they implemented in everything that gradient descent is even remotely related to, LINEAR regression for example?
is it simply a matter of overkill and an unnecessary piece of machinery in this case (but it would still theoretically improve training time) or is there an actual compatibility issue where BFGS and LBFGS needs non-linearity for them to work?
Comment: Closely related, possibly not a duplicate http://stats.stackexchange.com/questions/160179/do-we-need-gradient-descent-to-find-the-coefficients-of-a-linear-regression-mode/164164#164164
Answer: With linear regression, BFGS and LBFGS would be a major step backwards. That's because the solution can be directly written as
$\hat \beta = (X^T X)^{-1} X^T Y$
It's worth noting that directly using the above equation to calculate $\hat \beta$ (i.e. inverting $X^T X$ and then multiplying by $X^T Y$) is itself even a poor way to calculate $\hat \beta$.
Also, gradient descent is only recommended for linear regression in extremely special cases, so I wouldn't say gradient descent is "related" to linear regression.
Comment: @user3810748: gradient descent is a generic algorithm for a local critical point of a function (hopefully the minimum!). It can be used in the specific case of linear regression, but except for very extreme cases, it's relatively **very** inefficient in regards to total required computation time.
Comment: sorry, I think it was poor phrasing on my part.

I know it would be a major step back computationally, but my major concern would be whether or not it would still work (for educational purposes and semantic understanding)

the reason why know one uses is it is redundant to the point of being pointless, right? not due to some mathematical underlying incompatibility

yes?
Comment: @user3810748: yes, it would work.
Comment: also, can you elaborate on what you mean by

"Also, gradient descent is only recommended for linear regression in extremely special cases, so I wouldn't say gradient descent is "related" to linear regression."

do you mean that linear regression is weak compared to other better models
or do you mean that gradient descent should not be used to train linear regression???(im guessing the former due to the strangeness of the latter)
Comment: @CliffAB are there experiments/literature regarding the generally worse performance of gradient descent versus the analytical solution? I think that the (X^T X)^-1 operation could be very costly for moderately large X and in these cases LBFGS could be maybe faster.
Comment: @JacquesWainer: first off, as noted in the original answer, even though $(X^TX)^{-1} X^TY$ is the solution, it can be found *without* explicitly calculating $(X^TX)^{-1}$, although the solution still requires the same complexity. Also, to be clear, "large X" must refer to a very large number of predictors rather than number of samples (complexity will grow linearly with $n$). I'm not aware of any literature regarding evaluating efficiency of sub-optimal solutions. However, I can tell you right now it will be very dependent on the covariance of the predictors: for uncorrelated predictors, SGD..
Comment: ...and moreover LBFGS will do relatively well (since ignoring partials will be not so bad) while with heavy correlation they will do very poorly. Finding out the correlation of predictors will take as much time as finding the LS solution directly.


Break down a long string into multiple lists

Question: Is there a simple way to break down this string into multiple lists in Python so that I can then create a dataframe with those lists?
1|Mirazur|Menton, France|2|Noma|Copenhagen, Denmark|3|Asador Etxebarri|Axpe, Spain|4|Gaggan|Bangkok, Thailand|5|Geranium|Copenhagen, Denmark|6|Central|Lima, Peru|7|Mugaritz|San Sebastián, Spain|8|Arpège|Paris, France|9|Disfrutar|Barcelona, Spain|10|Maido|Lima, Peru|11|Den|Tokyo, Japan
I want to break it down so that it looks like:
[1, Mirazur, Menton, France]
[2, Noma, Copenhagen, Denmark]
and so on so forth.

I'm really new to all this, so any advice really appreciated. The more simple answer is possible, rather than any 'fancier' ones would be great so that I can understand the more basic concepts first!
Answer: Piece of cake. The basis is splitting on the | character; this will give you a flat list of all items. Next, split the list into smaller ones of a fixed size; a well-researched question with lots of answers. I chose https://stackoverflow.com/a/5711993/2564301 because it does not use any external libraries and returns a useful base for the next step:
print (zip(*[data.split('|')[i::3] for i in range(3)]))

This returns a zip type, as can be seen with
for item in zip(*[data.split('|')[i::3] for i in range(3)]):
    print (item)

which comes pretty close:
('1', 'Mirazur', 'Menton, France')
('2', 'Noma', 'Copenhagen, Denmark')
('3', 'Asador Etxebarri', 'Axpe, Spain')
etc.

(If you are wondering why zip is needed, print the result of [data.split('|')[i::3] for i in range(3)].)
The final step is to convert each tuple into a list of its own.
Putting it together:
import pprint

data = '1|Mirazur|Menton, France|2|Noma|Copenhagen, Denmark|3|Asador Etxebarri|Axpe, Spain|4|Gaggan|Bangkok, Thailand|5|Geranium|Copenhagen, Denmark|6|Central|Lima, Peru|7|Mugaritz|San Sebastián, Spain|8|Arpège|Paris, France|9|Disfrutar|Barcelona, Spain|10|Maido|Lima, Peru|11|Den|Tokyo, Japan'

data = [list(item) for item in zip(*[data.split('|')[i::3] for i in range(3)])]
pprint.pprint (data)

Result (nice indentation courtesy of pprint):
[['1', 'Mirazur', 'Menton, France'],
 ['2', 'Noma', 'Copenhagen, Denmark'],
 ['3', 'Asador Etxebarri', 'Axpe, Spain'],
 ['4', 'Gaggan', 'Bangkok, Thailand'],
 ['5', 'Geranium', 'Copenhagen, Denmark'],
 ['6', 'Central', 'Lima, Peru'],
 ['7', 'Mugaritz', 'San Sebastián, Spain'],
 ['8', 'Arpège', 'Paris, France'],
 ['9', 'Disfrutar', 'Barcelona, Spain'],
 ['10', 'Maido', 'Lima, Peru'],
 ['11', 'Den', 'Tokyo, Japan']]

Comment: Thank you SO much. I got as far as the splitting on | but then tried all sorts after and just couldn't get the separate rows. This makes so much sense now that I read it. Thanks a bunch again.


How does Chopin Op. 48 No.1 fit in with the remaining nocturnes? Any biographical reasons?

Question: I've played a couple Nocturnes over the years, but it's been a while since I  revisited Op. 48 No. 1.
And I'm again quite amazed by how technically challenging it is in comparison:
The wide arpeggios in the part beginning in bar 25, always p or pp, then the jumps after the chromatic double octave parts, and finally the reprise from bar 49 onward, with its pretty insane keys/s metric.
It appears to me that several properties of this Nocturne are extraordinary when compared to the others.

Mood: All Nocturnes have a lighter and heavier part, but none seem to possess the same level of drama as this one. In fact, I'd liken this one more to a ballad than a Nocturne, as far as mood is concerned.
Difficulty: As described above, I find this one to pose a major spike in difficulty when compared to the other Nocturnes.

So I'd just like to know your experiences with this piece, how you've perceived it difficulty- and mood-wise, and if anyone knows whether there are any reasons why it seems to stray somewhat from the Nocturne formula, e.g. biographical or other ones.
Answer:
...if anyone knows whether there are any reasons why it seems to stray somewhat from the Nocturne formula, e.g. biographical or other ones.

Wiki tells us much more about this nocturne - what you may probably know:
The Nocturne in C minor has been categorized as one of Chopin's greatest emotional achievements.[6][7] Theodor Kullak said of the piece, "the design and poetic contents of this nocturne make it the most important one that Chopin created; the chief subject is a masterly expression of a great powerful grief."[7] Jan Kleczyński, Sr. calls the nocturne "broad and most imposing with its powerful intermediate movement, a thorough departure from the nocturne style."[8] Some musical critics, including Charles Willeby and Frederick Niecks, do not think the piece deserves its fame and position; though James Huneker agrees with this assessment, he notes that the nocturne is still "the noblest nocturne of them all."[9] James Friskin found the music to have "the most imposing instrumental effect of any of the nocturnes," calling the crescendo and octaves "almost Lisztian."
https://en.wikipedia.org/wiki/Nocturnes,_Op.48(Chopin)
In another source we can read:
The two Nocturnes op. 48 were completed in the autumn of 1841.  They are dedicated to a favorite student of Chopin, Laure Duperré.  One of the composer's major works, Nocturne op. 48, No. 1 in C minor (Lento), is an impressive masterpiece of the tragic force of his power.  His gloomy and austere solemnity is associated with an intensity that is sometimes almost unbearable.
 It is one of the longest and most dramatic nocturnes.  It is a real diary of Chopin, in which one can guess the expression of intense pain. Chopin wanted the first measures to emerge as a thematic element.  As such, it accentuated the sound of the first three notes by playing with the third finger, the most sonorous finger on the piano.
 This first episode is "Lento" is followed by a new point "Poco più lento" with peeled and arpeggio chords that bring as hope, but gradually wins agitation, the volume increases, as numbers obsessed with triplets and sixteenth notes in octaves and  gradually accelerating towards the last passionate passage "Doppio movimento" feverish and desperate.  The theme is striking, on a low contour more romantic and tortured.  The night ends as a long lament.
http://www.c-expresso.fr/fr/fryderykchopin.php
In the article above we learn a lot of Chopin's biography, his love with the 16 years old Maria Wodzinski 1838, his illness 1838 and his relationship with George Sand and the dying of his father in May 1841.
But we find no evidence of influence to op. 48 written in October 1841.
Nocturne 1-10 have been composed before 1838, op. 55 and 62 1844 and 1846.


"forgetfulness" of the prior in the Bayesian setting?

Question: It is well-known that as you have more evidence (say in the form of larger $n$ for $n$ i.i.d. examples), the Bayesian prior gets "forgotten", and most of the inference is impacted by the evidence (or the likelihood).
It is easy to see it for various specific case (such as Bernoulli with Beta prior or other type of examples) - but is there a way to see it in the general case with $x_1,\ldots,x_n \sim p(x|\mu)$ and some prior $p(\mu)$?
EDIT: I am guessing it cannot be shown in the general case for any prior (for example, a point-mass prior would keep the posterior a point-mass). But perhaps there are certain conditions under which a prior is forgotten.
Here is the kind of "path" I am thinking about showing something like that:
Assume the parameter space is $\Theta$, and let $p(\theta)$ and $q(\theta)$ be two priors which place non-zero probability mass on all of $\Theta$. So, the two posterior calculations for each prior amount to:
$$p(\theta | x_1,\ldots,x_n) = \frac{\prod_i p(x_i | \theta) p(\theta)}{\int_{\theta} \prod_i p(x_i | \theta) p(\theta) d\theta}$$
and
$$q(\theta | x_1,\ldots,x_n) = \frac{\prod_i p(x_i | \theta) q(\theta)}{\int_{\theta} \prod_i p(x_i | \theta) q(\theta) d\theta}$$
If you divide $p$ by $q$ (the posteriors), then you get:
$$p(\theta | x_1,\ldots,x_n)/q(\theta | x_1,\ldots,x_n) = \frac{p(\theta)\int_{\theta} \prod_i p(x_i | \theta) q(\theta)d \theta}{q(\theta)\int_{\theta} \prod_i p(x_i | \theta) p(\theta)d \theta}$$
Now I would like to explore the above term as $n$ goes to $\infty$. Ideally it would go to $1$ for a certain $\theta$ that "makes sense" or some other nice behavior, but I can't figure out how to show anything there.
Comment: For some intuition, note that the likelihood scales with the sample size while the prior does not.
Comment: @Macro, thanks, I also had that intuition, but I couldn't push it further. See my edits above.
Comment: The first few chapters of Ghosh and Ramamoorthi's textbook *Bayesian Nonparametrics* fleshes out the sorts of things you are talking about (at first in a parametric setting, then a nonparametric one); it is available through Springer online for free if you are at an appropriate institution. There are multiple ways of formalizing the lack of dependence on the prior asymptotically, but of course there are a few regularity conditions.
Comment: Note that the posterior ratio is just proportional to the prior ratio, so the likelihood nor evidence ratio doesn't really influence this.
Answer: Just a rough, but hopefully intuitive answer.

Look at it from the log-space point of view:
$$
   -\log P(\theta|x_1, \ldots, x_n)
   = -\log P(\theta) -\sum_{i=1}^n \log P(x_i|\theta) - C_n
$$
where $C_n>0$ is a constant that depends on the data, but not on the parameter, and where your likelihoods assume i.i.d. observations. Hence, just concentrate on the part that determines the shape of your posterior, namely
$$
  S_n = -\log P(\theta) -\sum_{i=1}^n \log P(x_i|\theta)
$$
Assume that there is a $D>0$ such that $-\log P(\theta) \leq D$. This is reasonable for discrete distributions.
Since the terms are all positive, $S_n$ "will" grow (I'm skipping the technicalities here). But the contribution of the prior is bounded by $D$. Hence, the fraction contributed by the prior, which is at most $D/S_n$, decreases monotonically with each additional observation.

Rigorous proofs of course have to face the technicalities (and they can be very difficult), but the setting above is IMHO the very basic part.
Answer: I am somewhat confused by what the statements the "prior is forgetten" and "most of the inference is impacted by the evidence" are supposed to mean. I assume you mean as the amount of data increases, the (sequence of) estimator(s) approaches the true value of the parameter regardless of our prior.
Assuming some regularity conditions on the form of the posterior distribution, Bayes Estimators are consistent and asymptotically unbiased (see Gelman et al, chapter 4).  This means as the sample size increases the bayes estimator approaches the true value of the parameter.  Consistency means the bayes estimator converges in probability to the true parameter value and asymptotic unbiasedness means that, assuming $\theta_0$ is the true value of the parameter,
$$
\frac{E[\hat{\theta}|\theta_0]-\theta_0}{\sqrt{\mathrm{Var}(\hat{\theta})}}\overset{p}\rightarrow0
$$
The convergence does not depend on the specific form of the prior, but only that the posterior distribution obtained from the prior and the likelihood satisfy the regularity conditions.
The most important regularity condition mentioned in Gelman et al is that the likelihood be a continuous function of the parameter and the true value of the parameter be in the interior of the parameter space. Also, as you noted, the posterior must be nonzero in an open neighborhood of the true value of the true value of the parameter.  Usually, your prior should be nonzero on the entire parameter space.
Comment: thanks, very insightful. I was hoping actually for a result that would not even relate to the "true" parameter value. Just showing that technically, as you have more evidence, the posterior you are going to get is the same irregardless of the prior that you started with. I am going to make some edits to reflect that.
Comment: @bayesianOrFrequentist Take a look at the so-called *Bayesian central limit theorem*.


How to Authorize different login Url in MVC3?

Question: Hello everyone I have two login but how can I assign these login URLs with using authorize ?
Here is my webconfig :
 <location path="Home">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

 <authentication mode="Forms">
      <forms loginUrl="~/Home/Login" timeout="2880" />
    </authentication>

So how can I create second loginurl ?
Answer: You cannot have 2 logon urls in Forms Authentication. If you need to achieve this functionality you could write custom [Authorize] attributes and then override the HandleUnauthorizedRequest method where you could redirect to the corresponding logon url.
For example:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    private readonly string _controller;
    private readonly string _action;
    public MyAuthorizeAttribute(): this("account", "logon")
    {
    }

    public MyAuthorizeAttribute(string controller, string action)
    {
        _controller = controller;
        _action = action;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        var values = new RouteValueDictionary(new
        {
            controller = _controller,
            action = _action,
            returnurl = filterContext.HttpContext.Request.Url.PathAndQuery
        });
        filterContext.Result = new RedirectToRouteResult(values);
    }
}

and then:
public class SomeController
{
    [MyAuthorize]
    public ActionResult Foo()
    {
        return View();
    }

    [MyAuthorize("account", "someotherlogonaction")]
    public ActionResult Bar()
    {
        return View();
    }
}


Usar múltiplos loops javascript

Question: Existe alguma forma de rodar mais de um setInterval() ao mesmo tempo?
Nesse meu código, se eu rodar duas vezes a função "interval" o programa entra em loop infinito e no console fica tenho:
[1,2,3,4,5]
[1,2,3,4,5,6]
[1,2,3,4,5,6,7]
[1,2,3,4,5,6,7,8......] infinitamente

arraya = []
arrayb = []
function interval(array, length, count) {
    a = setInterval(function () {
        count++;
        array.push(count);
        if (array.length > length) {
            console.log(array.join(' '));
            clearInterval(a);
        }
    }, 150);;
}
interval(arraya, 4, 0);
// interval(arrayb, 9, 0)
Comment: Me pareceu uma duvida meio similar: http://pt.stackoverflow.com/questions/178944/existe-um-modo-de-criar-uma-execu%C3%A7%C3%A3o-paralela-usando-javascript
Answer: O problema no seu código é que a é uma variável global.Se você trocar por uma variável local tudo funciona direitinho.

arraya = []
arrayb = []
function interval(array, length, count) {
    var a = setInterval(function () {
        count++;
        array.push(count);
        if (array.length > length) {
            console.log(array.join(' '));
            clearInterval(a);
        }
    }, 150);;
}
interval(arraya, 4, 0);
interval(arrayb, 9, 0)
Comment: Funcionou :) muito obrigado pela ajuda! Vou testar em outros programas depois.
Comment: @anotherbeginner10 olá e bem vindo. Acho importante veres isto: https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta
Answer: o problema era que o a estava sendo jogado no contexto global, logo na segunda execução o identificador do primeiro setInterval era perdido e apenas o segundo parava, basta adicionar var antes de a para resolver isso

arraya = []
arrayb = []
function interval(array, length, count) {
    var a = setInterval(function () {
        count++;
        array.push(count);
        if (array.length > length) {
            console.log(array.join(' '));
            clearInterval(a);
        }
    }, 150);;
}
interval(arraya, 4, 0);
interval(arrayb, 9, 0)

Usar múltiplos loops javascript


Network Analysis using textnets - ValueError: negative dimensions are not allowed

Question: I am trying to perform network analysis on some text data after I did some sentiment analysis on it. I am using textnets documentation for reference. I am getting the above mentioned error after running the following line:
t = tn.Textnet(corpus.tokenized())

Here is my full Code:
import textnets as tn
tn.params["seed"] = 42

df = pd.read_csv(r"C:\Users\User\Downloads\archive\nltk_split.csv")
df.head()

df.drop(['Unnamed: 0.2', 'Unnamed: 0.1', 'Unnamed: 0', 'Unnamed: 15', 'Unnamed: 16', 'id', 'favorite_count', 'created_at', 'retweet_count', 'coordinates', 'score', 'neg', 'neu', 'pos', 'compound','created_at_date'], axis=1, inplace=True)
df.head()

corpus = tn.Corpus.from_df(df, doc_col='text')
t = tn.Textnet(corpus.tokenized())
t.plot(label_nodes=True,
       show_clusters=True)

The error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_19036\2509364554.py in <module>
----> 1 t = tn.Textnet(corpus.tokenized())

~\AppData\Roaming\Python\Python39\site-packages\textnets\network.py in __init__(self, data, min_docs, connected, remove_weak_edges, doc_attrs)
    353             self._matrix = data
    354         elif isinstance(data, (TidyText, pd.DataFrame)):
--> 355             self._matrix = _im_from_tidy_text(data, min_docs)
    356         if remove_weak_edges:
    357             pairs: pd.Series = self._matrix.stack()

~\AppData\Roaming\Python\Python39\site-packages\textnets\network.py in _im_from_tidy_text(tidy_text, min_docs)
    812         .set_index("label")
    813     )
--> 814     im = tt[tt["keep"]].pivot(values="term_weight", columns="term").fillna(0)
    815     return IncidenceMatrix(im)
    816

E:\anaconda\lib\site-packages\pandas\core\frame.py in pivot(self, index, columns, values)
   7883         from pandas.core.reshape.pivot import pivot
   7884
-> 7885         return pivot(self, index=index, columns=columns, values=values)
   7886
   7887     _shared_docs[

E:\anaconda\lib\site-packages\pandas\core\reshape\pivot.py in pivot(data, index, columns, values)
    518         else:
    519             indexed = data._constructor_sliced(data[values]._values, index=multiindex)
--> 520     return indexed.unstack(columns_listlike)
    521
    522

E:\anaconda\lib\site-packages\pandas\core\series.py in unstack(self, level, fill_value)
   4155         from pandas.core.reshape.reshape import unstack
   4156
-> 4157         return unstack(self, level, fill_value)
   4158
   4159     # ----------------------------------------------------------------------

E:\anaconda\lib\site-packages\pandas\core\reshape\reshape.py in unstack(obj, level, fill_value)
    489         if is_1d_only_ea_dtype(obj.dtype):
    490             return _unstack_extension_series(obj, level, fill_value)
--> 491         unstacker = _Unstacker(
    492             obj.index, level=level, constructor=obj._constructor_expanddim
    493         )

E:\anaconda\lib\site-packages\pandas\core\reshape\reshape.py in __init__(self, index, level, constructor)
    138             )
    139
--> 140         self._make_selectors()
    141
    142     @cache_readonly

E:\anaconda\lib\site-packages\pandas\core\reshape\reshape.py in _make_selectors(self)
    186
    187         selector = self.sorted_labels[-1] + stride * comp_index + self.lift
--> 188         mask = np.zeros(np.prod(self.full_shape), dtype=bool)
    189         mask.put(selector, True)
    190

ValueError: negative dimensions are not allowed

Answer: Your corpus is too large, causing pandas (which powers textnets) to run out of memory during the pivot operation.
I suggest filing a bug report at https://github.com/jboynyc/textnets/issues with some details about the size of your dataset.
Comment: It does not answer question. you can add it as comment.


Call method form custom module Class

Question: I  tried to call a function inside other class inside the same module on D8 but I have some error on the code. I got a Error: Class 'Drupal\hospitator\TimeTrackerController\TimeTracker' not found.
My main controller (HospitatorController.php):

namespace Drupal\hospitator\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\hospitator\TimeTrackerController\TimeTracker;

/**
 * Class HospitatorController.
 */
class HospitatorController extends ControllerBase {

  /**
   * Main Page Function.
   *
   * @return array
   *   Return main page.
   */
  public function mainPage() {
    $element = array(
        '#type' => 'markup',
        '#markup' => $this->t('Welcome to Hospitator!') . '
',
    );
    $test_controller = new TimeTracker;
    $test_text = $test_controller->start();

    return $element;
  }

}

My secondary class (TimeTracker.php):
<?php

namespace Drupal\hospitator\TimeTrackerController;

use Drupal\Core\Controller\ControllerBase;

/**
 * Class TimeTracker.
 */
class TimeTracker extends ControllerBase {

  /**
   * Test Time Trakcker.
   *
   * @return string
   *   Return test text.
   */
  public function start() {
    $element = 'Test';
    return $element;
  }

}

I have been 2 years without coding and my memory have some leaks. Can you help me? Tanhk you,
Comment: If `TimeTracker` is in your module's `src/Controller` directory, your namespace should be `Drupal\hospitator\Controller`, not `Drupal\hospitator\TimeTrackerController`.
Comment: The namespace used for a class must reflect the directory where the class file is located. Differently, PHP will not be able to find the class file and it will throw the error you see. As side note, a real controller is never created with `new` and it isn't simply a helper class you use for any purpose, but a class associated to a route defined from the module.
Comment: Thank you @kiamlaluno,
the class will be developed for time tracking decoding qr codes synchronized with random security tokens.
The TimeTracker class is located on src/Controller directory is it ok? Which namespace should I use? Thank you,
Answer: Since Drupal 8 supports PSR-4 namespaces, as described in the Drupal coding standards, in the Namespaces document page, Modules section, there must be a correspondence between namespace and directory structure. This means that, if Drupal\hospitator\TimeTrackerController is the namespace, then the class file must be placed in the hospitator/src/TimeTrackerController folder. Furthermore, if TimeTracker is the class name, then the file containing its code must be named TimeTracker.php.
I assume that hospitator is the machine name of the module. If the machine name is different, then hospitator must be replaced from the module machine name, in the namespace and in the folder name.
If the file containing the class code is in hospitator/src/Controller/TimeTracker.php, then the correct namespace is Drupal\hospitator\Controller, not Drupal\hospitator\TimeTrackerController. When you reference that class in a file that is using another namespace, you add use Drupal\hospitator\Controller\TimeTracker; on the top of that file, not use Drupal\hospitator\TimeTrackerController\TimeTracker;.
Also, if the HospitatorController and the TimeTracker classes are using the same namespace, which I assume is Drupal\hospitator\Controller, there is no need to add use Drupal\hospitator\Controller\TimeTracker; on the top of the file containing the HospitatorController class.
Comment: Thank you @kiamlaluno, your answer is very complete. I forgot the basics of classes.

Call method form custom module Class


What is the difference between a "learner" and "classifier" in supervised learning?

Question: This question stems from Pedro Domingos' excellent paper "A Few Useful Things to Know About Machine Learning." The paper is extremely clear and well-written, but I still have a clarification question. Namely, what is the difference between what Domingos describes on page 1 as a "learner" and a "classifier"? I have largely taken these to by synonymous. The sentence that threw me for a loop in the paper is (again, on page 1): "The test of the learner is whether this classifier produces the correct output yt for future examples xt." I thought this was simply the test of the classifier. Any clarification or further reading suggestions would be greatly appreciated.
Comment: A **Learner** or **Machine Learning Algorithm** is the program used to learn a machine learning model from data. Another name is "**inducer**" (e.g. "tree inducer").
Answer: I use to find this kind of difference mostly in the world of programmers interested in machine learning. This difference does not appear in the world of statisticians and researchers.
The idea is that a classifier is a program built by a learner. An illuminating intuition comes from one of the many definitions of machine learning which is programming with data. So, you have data (training set) and from that data using a computer program you build another program (for example a decision tree). The program which builds the decision tree from data is the learner. The decision tree is a classifier, because a classifier is a program which is able to predict, which takes only the input data and for each instance it produces the output data.
An alternative way to understand this is that a learner takes the input $x_1,x_2,..,x_p,y$ and produces a classifier. A classifier takes as input $x'_1,x'_2,..,x'_p$ and produces $y'$.
As I said, in research papers this distinction is hard to find. It seems that the researchers are interested only in how to describe the model. When they come to describe how to build that model, then they talk about a learner, and when they talk about how to predict with that model, then they talk about a classifier. So, a third alternative is a functional one. The function of fitting a model is the function of a learner, while the function of predicting values is a function of a classifier.
Note that a regressor is the same as a classifier, only the nature of the output is different.
Comment: Thanks @rapaio. Your functional description near the end finally made things click. Greatly appreciated.
Answer: I know this is an old post but I just had the same question as to the OP. Thanks to/based on @rapio's description, this is how I would say the same thing:
Both a learner and a classifier refer to the same thing: a machine learning model. It's just that an ML model has aspects to it while in the training phase which are hidden and taken away when the model is being used for inference.
For example, in the training phase, we have an optimizer that guides the backpropagation algorithm on how to update the model weights. Or the learning rate. These parts of the model are stripped away once the model is done training. In other words, the model that you'll have at inference is not exactly the same concept when you are training it. That's why in some literature, they are referred to by different names.
Basically, when you say "learner" you are putting an emphasis on the aspect of the model that exists only in the training phase. Personally, I wish people would stop nitpicking so much and just call it a model. In my opinion, this level of differentiation is not helping anyone.


Google Consent Manager Platform (CMP) is not showing everytime in debug mode

Question: Sharing following code, how am I calling for CMP dialog.
fun initDebugConsent(deviceId: String, onConsentResponse: OnConsentResponse) {
    this.onConsentResponse = onConsentResponse

    val debugSettings = ConsentDebugSettings.Builder(activity)
        .setDebugGeography(ConsentDebugSettings.DebugGeography.DEBUG_GEOGRAPHY_EEA)
        .addTestDeviceHashedId(deviceId)
        .build()

    val params = ConsentRequestParameters.Builder().setConsentDebugSettings(debugSettings).build()
    requestConsentInfo(params)
}

private fun requestConsentInfo(params: ConsentRequestParameters) {
    consentInformation.requestConsentInfoUpdate(activity, params, {
        if (consentInformation.isConsentFormAvailable && consentInformation.consentStatus == ConsentInformation.ConsentStatus.REQUIRED) {
            Log.d("ConsentManager", "initDebugConsent: Available & Required")
            loadForm()
        } else {
            Log.d("ConsentManager", "initDebugConsent: Neither Available or Required")
            onConsentResponse?.onResponse()
        }
    }, { error ->
        Log.e("ConsentManager", "initDebugConsent: $error")
        onConsentResponse?.onResponse(error.message)
    })
}

Note: It do show first time, but after consent I have to wait a lot for again testing.
Answer: I got by resetting consentInformation object only in debug mode, as it is recommended by google team.

Caution: This method is intended to be used for testing purposes only. You shouldn't call reset() in production code.

consentInformation.reset()


Why do skiers use poles in slalom and downhill?

Question: I'm watching the Olympics. The skiers in the "classic" events like giant slalom or the downhill carry poles. But they never seem to use them for anything. I don't see the poles touch the ground unless it's part of falling. Some of the slalom skiers seem to use the guard on the pole to push the gates aside, but a big rigid glove could maybe serve that purpose. There also seems to be a role in getting back up after falling, but that is not a normal part of a run.
Is it habit or tradition? Does it help them to balance, like the long pole a tightrope walker uses? Is it for the first few strides at the very beginning of the race?
I know that ski jumpers and arials don't use them, so it's certainly possible to get down a hill without poles. What value do they bring?
Comment: Did you watch them come out of the gate?
Comment: @Paparazzi that's what I was referring to with "the first few strides"
Comment: They help provide balance and stability.  If you watch the skiing events closely, you will notice that the skiers do drag their pole tips across the snow when making turns.
Answer: The key thing poles are used for in downhill is the launch through the gate. But poles also provide balance, and help them keep or get out of trouble.
Answer: The question is legitimate by a person who has never skied.
The poles help professional skiers during the races (as amateur skiers) to maintain a better balance. With the sticks you can move the weight (and so also the center of gravity) to right and left also allowing to support a higher speed
Comment: I think you first line belongs in comments on the question not in an answer


Does an offscreen canvas have as much "space" as a normal one?

Question: I have a situation similar to this question about copying data between canvases, but in my case I think I'm running into issues with the canvas engine itself and I'd like some understanding/guidance on what I might be doing wrong.
I'm creating an offscreen canvas with the same width and height as the onscreen canvas.
  @offscreenCanvas = document.createElement('canvas')

  # assign same dimensions as onscreen canvas
  @offscreenCanvas.width  = canvas.width
  @offscreenCanvas.height = canvas.height

Then I'm drawing from the offscreen canvas to the onscreen one like this:
# grab the width and height of the canvas
{ width, height } = @canvasElement
{ x, y } = offset

# copy image from layer into canvas
@context.drawImage
  @offscreenContext.canvas, -x, -y, width, height, -x, -y, width, height

The offset is also the argument into a function which translates the "live" canvas context before all this drawing takes place.
@context.save()
@context.translate(@offset.x,@offset.y)
@renderer.draw(world, @offset)
@context.restore()

In other words we're trying to grab the section of the offscreen context that corresponds to the translated offset of the on-screen context.
This has some issues. When the offset moves the 'camera' far from the origin, you encounter the 'edges' of the offscreen canvas.

Note that when I do the same rendering operations against the onscreen canvas, the elements are fine.
It seems like the offscreen canvas isn't quite as good about handling drawing off its "edges" the same way the canvas is (silently ignores drawing commands outside of its defined region.) In other words, the offscreen canvas doesn't seem to reflect any drawing I've done above or to the left of [0,0] (or alternatively, below or to the right of [width,height].) Are there ways of accommodating this?

Things I've tried:

adjusting up the width and height of the offscreen canvas (this unfortunately seems to have a hard-to-predict impact on coordinates)
Comment: Oops! I accidentally deleted my comment while trying to edit it. An in-memory canvas should behave the same as one visible in the window. How far are you offsetting to accommodate the camera position?
Comment: @markE I can see the issue even with a small offset, like (-5, -5) or (5,5). Note I'm setting up the offscreen canvas to have the same width and height as the onscreen one.
Answer: I've been able to address the issue by indicating a larger offscreen canvas size. The issue with coordinates seemed to be about Isomer's origin position (which you can override by passing in a different origin.)
A minor note: as per MDN's article on canvas optimization you need to ensure the coordinates and dimensions you pass to drawImage aren't floating point (i.e, call Math.floor on them.) I was running into odd antialiasing artifacts without this.


How to create service delagation to an existing subnet?

Question: Below code will create a service while creating subnet.
Is there anyway to create a delegation to existing subnet?
The main purpose is, below code will be create error for policy Deny-Subnet-Without-Nsg. So, creating this subnet directly in the vnet block.

resource "azurerm_subnet" "example" {

  virtual_network_name = azurerm_virtual_network.aksvnet.name
  name                 = "aks-postgres-subnet"
  resource_group_name  = azurerm_resource_group.aks_rg.name
  address_prefixes     = ["10.230.2.0/24"]
  service_endpoints    = ["Microsoft.Storage"]
  delegation {
    name = "fs"
    service_delegation {
      name = "Microsoft.DBforPostgreSQL/flexibleServers"
      actions = [
        "Microsoft.Network/virtualNetworks/subnets/join/action",
      ]
    }
  }
  depends_on = [azurerm_virtual_network.aksvnet, azurerm_network_security_group.example]
}

The below code don't have option to add service delegation.

resource "azurerm_virtual_network" "aksvnet" {

  name                = "aks-network"

  location            = azurerm_resource_group.aks_rg.location

  resource_group_name = azurerm_resource_group.aks_rg.name

  address_space       = ["10.0.0.0/8"]

  subnet {

    name           = "aks-default-subnet"

    address_prefix = "10.240.0.0/16"

    security_group = azurerm_network_security_group.example.id

  }

  subnet {

    name           = "aks-postgres-subnet"

    address_prefix = "10.230.2.0/24"

    security_group = azurerm_network_security_group.example.id

  }

}

So thought to create a subnet first like above and apply the service delegation after that.
How to do it?
Answer: A bit late to the party, but I just had to solve this issue myself and stumble across this post.
I solved it by utilizing the AzAPI Provider to patch the subnet.
In short: use the subnet data source to get the id and patch it:

data "azurerm_subnet" "subnet" {
  name                 = "my-subnet"
  virtual_network_name = "my-vnet"
  resource_group_name  = "network-rg"
}

/*
NB: Delegation isn't removed on destroy. It does however resolve delta if the delegation is manually removed from the subnet.
Beware of race condition with azurerm_subnet.delegation[] if it's managed by Terraform somewhere else -> in that case: lifecycle { ignore_changes = [ delegation ] }
*/
resource "azapi_update_resource" "patch" {
  type        = "Microsoft.Network/virtualNetworks/subnets@2022-05-01"
  resource_id = data.azurerm_subnet.subnet.id

  body = jsonencode({
    properties = {
      delegations = [
        {
          name = "aci-delegation"
          properties = {
            serviceName = "Microsoft.ContainerInstance/containerGroups"
            actions     = ["Microsoft.Network/virtualNetworks/subnets/action"]
          }
        }
      ]
    }
  })
}

Comment: Your answer have been very helpful, and solved my problem.
Answer: I don't know why Terraform doesn't allow you to add a delegation in a subnet when using the nested option, the ARM spec for this does include delegations so you might want to raise a bug with Terraform to add this.
That said, you can't have Terraform update a resource it created earlier, so the only way you can do this is use a local_exec block to run some PowerShell or Azure CLI to add the delegation.
The other option would be to use the ARM module in Terraform to have it run an ARM template which creates the vNet, but then you loose a lot of the benefit of Terraform.


Given $a,b,c$. Prove inequality

Question: Given $a,b,c$ are non-negative number. Prove that $$3(a^2+b^2+c^2)\ge\left(a+b+c\right)\left(\sqrt{ab}+\sqrt{bc}+\sqrt{ca}\right)+(a-b)^2+(b-c)^2+(c-a)^2\ge(a+b+c)^2$$

By C-S: $3(a^2+b^2+c^2)\ge(a+b+c)^2$
And prove $3\left(a^2+b^2+c^2\right)\ge\left(a+b+c\right)\left(\sqrt{ab}+\sqrt{bc}+\sqrt{ca}\right)+\left(a-b\right)^2+\left(b-c\right)^2+\left(c-a\right)^2$
Because $\left(a-b\right)^2+\left(b-c\right)^2+\left(c-a\right)^2\ge0$
Hence $3\left(a^2+b^2+c^2\right)\ge\left(a+b+c\right)\left(\sqrt{ab}+\sqrt{bc}+\sqrt{ca}\right)$
$\Rightarrow 3\left(a^2+b^2+c^2\right)\ge\left(a+b+c\right)^2$ (by C-s)
Also prove $\left(a+b+c\right)\left(\sqrt{ab}+\sqrt{bc}+\sqrt{ca}\right)+\left(a-b\right)^2+\left(b-c\right)^2+\left(c-a\right)^2\ge\left(a+b+c\right)^2\left(1\right) (*)$
Help me prove (*)
Answer: We need to prove that
$$(a^2+b^2+c^2)(ab+ac+bc)+\sum_{cyc}(a^2-b^2)^2\geq(a^2+b^2+c^2)^2$$ or
$$\sum_{cyc}(a^4+a^3b+a^3c-4a^2b^2+a^2bc)\geq0$$ or
$$\sum_{cyc}(a^4-a^3b-a^3c+a^2bc)+2\sum_{cyc}ab(a-b)^2\geq0,$$
which is true by Schur.
Done!
Comment: $(a^2+b^2+c^2)(ab+ac+bc)+\sum_{cyc}(a^2-b^2)^2\geq(a^2+b^2+c^2)^2$ why we need prove this ?
Comment: @Word Shallow It's just replacing $a\rightarrow a^2$, $b\rightarrow b^2$ and $c\rightarrow c^2$.
Answer: Setting $$a=x^2,b=y^2,c=z^2$$ then we have to prove that
$$3 \left(x^4+y^4+z^4\right)-(x y+x z+y z)
   \left(x^2+y^2+z^2\right)-\left(x^2-y^2\right)^2-\left(z^2-x^2\right)^2-\left(y^2-z^2\right)^2\geq 0$$
  and this is equivalent to $$\left(x^2+y^2+z^2\right) \left(x^2-x y-x z+y^2-y z+z^2\right)\geq 0$$ which is true.
The right-hand side is equivalent to
$$-\left(x^2+y^2+z^2\right)^2+(x y+x z+y z)
   \left(x^2+y^2+z^2\right)+\left(x^2-y^2\right)^2+\left(z^2-x^2\right)^2+\left(y^2-z^2\right)^2\geq 0$$
Setting $$y=x+u,z=x+u+v$$ we get
$$x^2 \left(5 u^2+5 u v+5 v^2\right)+5 u^2 v^2+x \left(4 u^3+6 u^2 v+14 u v^2+6 v^3\right)+5 u
   v^3+v^4\geq 0$$
which is true.

Given $a,b,c$. Prove inequality


Dynamic Highstock chart when no data at start

Question: I'm new at highstock charts and i have some problems with it. I have the following highstok chart.
Highcharts.stockChart('chart1', {
    chart: {
        events: {
            load: function () {
                var series = this.series[0];
                setInterval(function () {
                    var x = (new Date()).getTime(), // current time
                        y = Math.round(Math.random() * 100);
                    series.addPoint([x, y], true, true);
                }, 1000);
            }
        }
    },
    rangeSelector: {
        buttons: [{
            count: 1,
            type: 'minute',
            text: '1M'
        }, {
            count: 5,
            type: 'minute',
            text: '5M'
        }, {
            type: 'all',
            text: 'All'
        }],
        inputEnabled: false,
        selected: 0
    },
    title: {
        text: 'Random'
    },
    navigator: {
        enabled: true
    },
    exporting: {
        enabled: false
    },
    series: [{
        name: 'Random',
        data: [[]]
    }]
});

Eveything looks normal, but if we run https://jsfiddle.net/9pa5gjqw/17/ we can see strange behaviour. There is no graph at all, we can see only points adding. But if I add some data in 'series' everything is ok.
What should be added to chart configuration? May be I missed someting.
Answer: It looks strange because you are doing this:
series.addPoint([x, y], true, true);

With no points in the series. If we look at the addPoint() definition we have for the 3rd argument:

If true, a point is shifted off the start of the series as one is appended to the end.

So points are being removed just as they are added since there is 0 points in the series to begin with.
3 possible solutions, depending on what you want it to look like.

Don't shift the series, just add points. Fiddle example
Initialize the series with x number of values (I used 10 points) Fiddle example
Don't shift for first x elements added, then shift. (I used 10 points) Fiddle example
Comment: Thanks @ewolden! It helped me a lot


Canvas Layers (Z Index)

Question: I understand that Canvas is as ink dries and each item that is draw is on top.
I'm having a little problem, I have a list of sources of background images
<code>                var sources = {
                  bg: 'images/room-1/bg.png',
                  rightWall: 'images/room-1/wall-right.png',
                  leftWall: 'images/room-1/wall-left.png',
                  beam: 'images/room-1/beam-left.png',
                  sofa: 'images/room-1/sofa.png'
                };

                loadImages(sources, function(images) {
                  context.drawImage(images.bg, 0, 0, 760, 500);
                  context.drawImage(images.rightWall, 714, 0, 46, 392);
                  context.drawImage(images.leftWall, 0, 160, 194,322);
                  context.drawImage(images.beam, 0, 45, 143,110);
                  context.drawImage(images.sofa, 194, 280, 436,140);
                });
</code>
This is fine and they order how I like.
My issue is I have an image upload for a user to upload their image into the Canvas.
I am just using an upload box to test the theory, but the idea is the user will upload their image, crop, scale it, using JQuery / PHP and this saves the image. I will then grab this manipulated URL and pull this in, however the problem is that the Canvas is loaded so when i upload an image, it goes on top off the sources image.
I do not want to use multiple Canvas as I need to save this canvas as an image as a whole.
<code>            var imageLoader = document.getElementById('imageLoader');
                imageLoader.addEventListener('change', handleImage, false);

                function handleImage(e){
                    var reader = new FileReader();
                    reader.onload = function(event){

                        var img = new Image();
                        img.onload = function(){
                            canvas.width = 760;
                            canvas.height = 300;
                        }
                        img.src = event.target.result;
                        img.onload = function(){
                            context.drawImage(img, 0, 0);
                        };
                    }
                    reader.readAsDataURL(e.target.files[0]);
                }
</code>
Answer: Canvas does not have layers.
But you can still get 1 final image with both your background and your user's scaled/rotated foreground.
Since you want to let the user rotate/scale their image but you don't want to affect the background, you will need 2 canvases -- a background canvas and a user canvas.
<code>// HTML

<div id="container">
  <canvas id="background" class="subcanvs" width=760 height=300></canvas>
  <canvas id="canvas" class="subcanvs" width=760 height=300></canvas>
</div>

// CSS

#container{
  position:relative;
  border:1px solid blue;
  width:760px;
  height:300px;
}
.subcanvs{
  position:absolute;
}

// JavaScript

// a background canvas
var background=document.getElementById("background");
var bkCtx=background.getContext("2d");

// a foreground canvas the user can rotate/scale
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
</code>
Then when the user is done rotating/scaling, drawImage the users canvas to the background canvas.
<code>// combine the users finished canvas with the background canvas
bkCtx.drawImage(canvas,0,0);

// and save the background canvas (now it's combined) as an image
var imageURL=background.toDataURL();
</code>

Canvas Layers (Z Index)


Pegar Strings de outras Activitys

Question: Como faço para pegar uma String, ou mais, de uma outra Activity, e depois usa-la em outra Activity, alguém aí sabe me dizer?
Answer: Para transferir informações entre activities deve usar o proprio Intent, que tem vários métodos para adicionar e obter informação.
Para adicionar informação deve usar o método putExtra, que tem vários overloads sendo um deles precisamente para String. Quando o usa tem de associar um nome à String que está a enviar:
Activity1.java:
String minhaString = "algum texto nesta String";

Intent i = new Intent(Activity1.this, Activity2.class); //Activity1 abre a Activity2
i.putExtra("nomeAssociado", minhaString); //colocar a String na informação a enviar
startActivity(i); //abrir a Activity2

Para obter a informação guardada utilize o método getStringExtra na Activity que foi aberta e dentro do método onCreate.
Activity2.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.meu_layout);

    Intent intent = getIntent(); //obter o Intent enviado

    //apanhar a String enviada da Activity1 com base no nome associado
    String stringDaActivity1 = intent.getStringExtra("nomeAssociado");

Se o nome com que se baseia para ir buscar a String não estiver correto, ou o extra não existir, irá obter null,e por isso deve testar se conseguiu obter o valor pretendido antes de o utilizar.
Documentação para a classe Intent, para o putExtra, e getExtra

Pegar Strings de outras Activitys


f is analytic mapping of the unit disk into itself such that f(a) = 0. Show $|f(z)| \leq |\frac{z-a}{1-\bar{a}z}|$

Question: $f$ is analytic mapping of the unit disk into itself such that $f(a) = 0$. Show $|f(z)| \leq |\frac{z-a}{1-\bar{a}z}|$
I considered $F(z) =f(\phi_{-a}(z))$ where $\phi_a(z) = \frac{z-a}{1-\bar{a}z}$ maps unit disk to unit disk and $\phi_{-a}$ is the inverse of $\phi_a$
I get F is analytic mapping unit disk to unit disk, and $F(0) = 0$, so by Schwarz lemma I get $|F(z)|\leq |z|$ and $|F'(0)|\leq1$. And then I get stuck. I am not sure what I can do to get the final inequality. Or maybe I am thinking about the problem in a wrong way.
Answer: You're almost there. Now, let $\xi=\phi_{-a}(z)$. We get $F(z)=f(\phi_{-a}(z))=f(\xi)$, for  So the inequality would be, in this terms,
$$|f(\xi)|<|\phi_{a}(\xi)|=\left|\frac{\xi-a}{1-\bar a\xi}\right|$$
Comment: hehe, that was simple! Thanks a lot!
Comment: You can obtain another condition if you write $F'(0)$ using the chain rule, I think.