How to start threads with a delay in python

Question: I created threads, added delay in the function, but all threads are executing at the same time. Instead i want threads to start one by one. Is that possible ?
Below is my code
from _thread import start_new_thread
import time

def mul(n):
    time.sleep(1)
    res = n * n
    return res

while 1:
    m = input("Enter number ")
    t = input("Enter the number of times the function should be executed:")
    max_threads = int(t)
    for n in range(0, max_threads):
        start_new_thread(mul, (m,))

    except:
        pass
        print("Please type only digits (0-9)")
        continue

    print(f"Started {max_threads} threads.")

Comment: What is `from _thread import start_new_thread`? You should be using the `threading` module
Comment: read in stack overflow, this does not require threads to close
Answer: First of all, you added the delay inside the thread, causing it to pause after it started. Thus, you are starting all the threads one by one without delay and when each thread starts it waits 1 second before continuing.
So if you want a specific delay - add after you start each thread, in the main thread.
If you want each thread to start after the previous thread finished, you can do the following:
import threading
.
.
.
for n in range(0, max_threads):
    t = threading.Thread(target = mul, args=(m,))
    t.start()
    t.join() # Waits until it is finished


iterate through SimpleXMLElement Object in php

Question: I can't iterate through this xml file. I'm using simplexml_load_file(). does anyone have a solution? Thanks for your time. I'm a newbie!
SimpleXMLElement Object
(
[ReferenceMember] => SimpleXMLElement Object
    (
        [Agency] => SimpleXMLElement Object
            (
                [ID] => xx
                [ActivityID] => xxxxx
                [ActivityReferenceID] => xxxxx
            )

    )

[Member] => SimpleXMLElement Object
    (
        [Agency] => SimpleXMLElement Object
            (
                [ID] => xx
                [ActivityID] => xxxx
                [ActivityReferenceID] => xxxx
            )

    )

[SubmissionID] => xxxx
[Company] => xxxxx

[Emails] => SimpleXMLElement Object
    (
        [Email1] => firstname.lastname@example.com
    )

[UploadedDate] => 24/11/14
)

this is what I've tried
$data = simplexml_load_file($file);

foreach ($data as $item) {

        foreach ($item->item as $entry) {
            $this->set_date($entry->UploadedDate);

        }

}

$array = array(
            "DATE" => $this->get_date()

        );

var_dump($array);

this is what i get
array(1) {
  ["DATE"]=>
  NULL
}

when i try to acces object value
var_dump($date->UploadedDate);

object(SimpleXMLElement)#9 (1) {
  [0]=>
  string(8) "24/11/14"
}

Comment: It's easier to reproduce examples if you provide the actual XML used, rather than a dump of the SimpleXML object.
Answer: According to the information you've given us, you don't need to loop at all, because you only want one answer, and you know exactly where to find it:
$data = simplexml_load_file($file);
$this->set_date( (string)$data->UploadedDate );

Note that I've used (string) here; this removes the SimpleXML magic from the found value, which will probably be what you want later. echo does this for you, so echo $data->UploadedDate; would show what you expect.
Comment: Thanks a lot for your answer. it works like this. however when i trye to change date format `$this->date = date("Y-m-d", $date);` i get this date : "1970-01-01". let me know if you have an idea on this issue. Thanks again!
Comment: @S.B `date()` expects a timestamp - an integer representing the number of seconds since 1970 - not a preformatted string. The easiest way to convert from one format to another is using `$timestamp = strtotime($formatted_date); echo date('Y-m-d', $timestamp);` or `$dateObject = new DateTime($formatted_date); echo $dateObject->format('Y-m-d');` (None of which has anything to do with this question, so if you're still stuck, search for or ask a new question.)


Should the Update Manager module be uninstalled when installing with Composer?

Question: Drupal 8 is installed with Composer and I use it to update. So I uninstalled the Update Manager module provided by the core.
Now when I go to /admin/reports/status, I have the following warning.

Should the Update Manager module be uninstalled when Drupal is installed with Composer?
Answer: Personally, I have Update Manager installed on all my live sites.
While I use composer to manage all of my sites, I am do not blindly composer update and push out.  I like to read changelogs and make sure I regression test thoroughly.
So, I have email notifications for updates turned on for all of my sites.  Most are set for daily notification for all updates, but a handful of internal-only sites (as in behind the firewall) set for security updates only.
Then I can test and plan what updates go out when during my maintenance windows.  Or for security updates, triage how critical they are to go out outside the normal windows.
Comment: Thank you, I monitor the update with RSS feed modules installed on my site and Thunderbird. If I reinstall the Update module, it does not work anymore https://imgur.com/a/oa9dkkA


How to create a new request

Question: I have a method that accepts a request
public function createUser(Request $request)
{
    ...
}

I want to call it from another method
public function someMethod(){
    $array = [...];

    return $this->createUser($array); <----
}

and how can I pass a new request to it with the array I need?
Comment: How about instead of trying to call a controller method, you move the logic to create a user to a service class and then use the service class in your `createUser` and `someMethod` methods?
Comment: @bassxzero Can you show me an example of this approach?
Answer: How about instead of trying to call a controller method, you move the logic to create a user to a service class and then use the service class in your createUser and someMethod methods?
UserService.php
class UserService
{

    public function __construct() { }

    public function createUser(array $userData)
    {
        // TODO use $userData to create a user here

        return $newUser;
    }
}

SomeController.php
public function createUser(Request $request)
{
    $this->userService->createUser($request->all());
}

public function someMethod(){
    $array = [...];

    return $this->userService->createUser($array);
}

How to create a new request


Why the CHC (Montreal Candiens) logo at an F1 Grand Prix race?

Question: During the 1991 British Grand Prix race weekend at Silverstone, U.K., someone was flying a flag with the Ferrari logo that had an additional, shorter flag attached to its edge, as shown in this frame from around 1:18:30 in the the 2021 documentary Schumacher:

I can't be sure, but it looks as if this may be an "official" flag put up by the venue or the race management, as it's attached to the structure of the stands (note that the pole, extending from the stands rail, also carries what looks like a loudspeaker).
The design on this second flag appears to be the "CHC" logo of the Montreal Canadiens ice hockey team, particularly as used on the home game uniform:

What's going on here? Does this logo also have some significance in racing, or for this particular race? Or is this just a fan randomly sewing flags together?
Answer: It won't be an official flag.  I have no source but I'm 100% confident that even back then venues would only erect signage for sponsors or their own advertising.
From first hand experience, back in the 90s the organisation of Grands Prix was less restrictive (I remember Belgian GP as late as 1998 having fan-constructed makeshift grandstands up near Les Combes). As a result, I fully believe that these are fan flags that have commandeered any available anchor to celebrate their favourite teams. In this case you likely have an ice hockey fan in the crowd too.
I don't believe that there was any overt link with Canada in 91 beyond the Canadian GP and a historic affection for the late Giles Villeneuve.


Verificar se intervalo de horario está dentro de outro intervalo

Question: Preciso saber se foi trabalhado dentro de um intervalo fixado
<code>$entrada_padrao = strtotime('08:00');//fixo como parametro
$saida_padrao = strtotime('18:00');//fixo como parametro

$entrada_trabalho = strtotime('09:00');//apontamento no relogio de ponto
$saida_trabalho = strtotime('20:50');//apontamento no relogio de ponto
</code>
Neste exemplo tem que me retornar TRUE
Já tentei esta lógica abaixo, mas não funciona porque tanto ele pode entrar antes de $entrada_padrao quanto pode sair após $saida_padrao ou ambos
<code>if(($entrada_trabalho <= $entrada_padrao) && ($saida_trabalho >= $entrada_padrao)){
    echo "True";
}else{
    echo "False";
}
</code>
Comment: qual o "intervalo fixado"? `$entrada_padrao` ou `$entrada_trabalho`? fiquei na dúvida em relação a isto, no entanto, sugiro que você [**edite**](https://pt.stackoverflow.com/posts/523809/edit) sua pergunta e especifique isso. Antes de mais nada, veja como criar um [mre].
Comment: editado, a entrada_padrao e saida_padrao é fixo como padrao. O usuario  apontará o horario trabalhado e irei comparar se ele trabalhou dentro do horario padrao, independente da hora que ele entrou ou saiu
Answer: No caso, deve retornar true apenas se ele chegar antes ou no horário de início e sair no horário de fim ou após. Nesse caso, a entrada de trabalho deve ser menor ou igual a entrada padrão. Enquanto a saida trabalho deve ser maior ou igual a saida padrão. Deve-se fazer essa correção.
<code>$entrada_trabalho <= $entrada_padrao && $saida_trabalho >= $saida_padrao
</code>
Answer: Temporariamente montei esta solução
<code>$valor = 100;//valor a pagar de bônus
$entrada_padrao = strtotime('08:00');//fixo como parâmetro
$saida_padrao = strtotime('18:00');//fixo como parâmetro

$entrada_trabalho = strtotime('09:00');//horário de entrada no trabalho
$saida_trabalho = strtotime('19:50');//horário de saída no trabalho

function calcBonus($ep, $sp, $et, $st, $v){
    if ($et >= $ep && $et <= $sp) {//se entrou dentro do horário padrão
        return $v;
    }else
    if ($et < $ep && ($st <= $sp && $st >= $ep)) {//se entrou antes do horário padrão, saiu antes da saída padrão mas não antes da entrada padrão
        return $v;
    }else
    if ($et < $ep && $st > $sp) {//entrou antes da entrada padrão e sai após o horario padrão
        return $v;
    }else {
        return 0;
    }
}

var_dump(calcBonus($entrada_padrao,$saida_padrao,$entrada_trabalho,$saida_trabalho,$valor));
</code>
Se o período trabalhado estiver passado dentro do período padrão ele me retorna o valor a pagar.
Sugestões de melhorias também são bem vindas.


Kernel crashes when I use tensorflow

Question: I created my anaconda environment and installed a few modules on it (see below full list) notably tensorflow and matplotlib
(FreeCodeCampML) C:\Users\abelm>conda list
# packages in environment at C:\Users\abelm\anaconda3\envs\FreeCodeCampML:
#
# Name                    Version                   Build  Channel
_tflow_select             2.3.0                       mkl
absl-py                   1.4.0              pyhd8ed1ab_0    conda-forge
aiohttp                   3.8.1           py310he2412df_1    conda-forge
aiosignal                 1.3.1              pyhd8ed1ab_0    conda-forge
anyio                     3.5.0           py310haa95532_0
appdirs                   1.4.4              pyhd3eb1b0_0
argon2-cffi               21.3.0             pyhd3eb1b0_0
argon2-cffi-bindings      21.2.0          py310h2bbff1b_0
asttokens                 2.0.5              pyhd3eb1b0_0
astunparse                1.6.3              pyhd8ed1ab_0    conda-forge
async-timeout             4.0.2              pyhd8ed1ab_0    conda-forge
attrs                     22.1.0          py310haa95532_0
babel                     2.11.0          py310haa95532_0
backcall                  0.2.0              pyhd3eb1b0_0
beautifulsoup4            4.11.1          py310haa95532_0
blas                      1.0                         mkl
bleach                    4.1.0              pyhd3eb1b0_0
blinker                   1.5                pyhd8ed1ab_0    conda-forge
bottleneck                1.3.5           py310h9128911_0
brotli                    1.0.9                h2bbff1b_7
brotli-bin                1.0.9                h2bbff1b_7
brotlipy                  0.7.0           py310h2bbff1b_1002
bzip2                     1.0.8                he774522_0
ca-certificates           2022.12.7            h5b45459_0    conda-forge
cached-property           1.5.2                hd8ed1ab_1    conda-forge
cached_property           1.5.2              pyha770c72_1    conda-forge
cachetools                5.3.0              pyhd8ed1ab_0    conda-forge
certifi                   2022.12.7          pyhd8ed1ab_0    conda-forge
cffi                      1.15.1          py310h2bbff1b_3
charset-normalizer        2.0.4              pyhd3eb1b0_0
click                     8.1.3           win_pyhd8ed1ab_2    conda-forge
colorama                  0.4.6           py310haa95532_0
comm                      0.1.2           py310haa95532_0
cryptography              38.0.4          py310h21b164f_0
cycler                    0.11.0             pyhd3eb1b0_0
debugpy                   1.5.1           py310hd77b12b_0
decorator                 5.1.1              pyhd3eb1b0_0
defusedxml                0.7.1              pyhd3eb1b0_0
entrypoints               0.4             py310haa95532_0
executing                 0.8.3              pyhd3eb1b0_0
fftw                      3.3.9                h2bbff1b_1
flatbuffers               2.0.0                h6c2663c_0
flit-core                 3.6.0              pyhd3eb1b0_0
fonttools                 4.25.0             pyhd3eb1b0_0
freetype                  2.12.1               ha860e81_0
frozenlist                1.3.3           py310h2bbff1b_0
gast                      0.4.0              pyh9f0ad1d_0    conda-forge
giflib                    5.2.1                h8d14728_2    conda-forge
glib                      2.69.1               h5dc1a3c_2
google-auth               2.16.0             pyh1a96a4e_1    conda-forge
google-auth-oauthlib      0.4.6              pyhd8ed1ab_0    conda-forge
google-pasta              0.2.0              pyh8c360ce_0    conda-forge
grpcio                    1.42.0          py310hc60d5dd_0
gst-plugins-base          1.18.5               h9e645db_0
gstreamer                 1.18.5               hd78058f_0
h5py                      3.7.0           nompi_py310h00cbb18_100    conda-forge
hdf5                      1.12.1          nompi_h2a0e4a3_100    conda-forge
icc_rt                    2022.1.0             h6049295_2
icu                       58.2                 ha925a31_3
idna                      3.4             py310haa95532_0
importlib-metadata        6.0.0              pyha770c72_0    conda-forge
intel-openmp              2021.4.0          haa95532_3556
ipykernel                 6.19.2          py310h9909e9c_0
ipython                   8.8.0           py310haa95532_0
ipython_genutils          0.2.0              pyhd3eb1b0_1
ipywidgets                7.6.5              pyhd3eb1b0_1
jedi                      0.18.1          py310haa95532_1
jinja2                    3.1.2           py310haa95532_0
jpeg                      9e                   h2bbff1b_0
json5                     0.9.6              pyhd3eb1b0_0
jsonschema                4.16.0          py310haa95532_0
jupyter                   1.0.0           py310haa95532_8
jupyter_client            7.4.9           py310haa95532_0
jupyter_console           6.4.4           py310haa95532_0
jupyter_core              5.1.1           py310haa95532_0
jupyter_server            1.23.4          py310haa95532_0
jupyterlab                3.5.3           py310haa95532_0
jupyterlab_pygments       0.1.2                      py_0
jupyterlab_server         2.16.5          py310haa95532_0
jupyterlab_widgets        1.0.0              pyhd3eb1b0_1
keras                     2.10.0          py310haa95532_0    anaconda
keras-preprocessing       1.1.2              pyhd3eb1b0_0
kiwisolver                1.4.4           py310hd77b12b_0
lerc                      3.0                  hd77b12b_0
libbrotlicommon           1.0.9                h2bbff1b_7
libbrotlidec              1.0.9                h2bbff1b_7
libbrotlienc              1.0.9                h2bbff1b_7
libclang                  12.0.0          default_h627e005_2
libcurl                   7.87.0               h86230a5_0
libdeflate                1.8                  h2bbff1b_5
libffi                    3.4.2                hd77b12b_6
libiconv                  1.16                 h2bbff1b_2
libogg                    1.3.5                h2bbff1b_1
libpng                    1.6.37               h2a8f88b_0
libprotobuf               3.20.3               h23ce68f_0
libsodium                 1.0.18               h62dcd97_0
libssh2                   1.10.0               h680486a_2    conda-forge
libtiff                   4.5.0                h6c2663c_1
libvorbis                 1.3.7                he774522_0
libwebp                   1.2.4                h2bbff1b_0
libwebp-base              1.2.4                h2bbff1b_0
libxml2                   2.9.14               h0ad7f3c_0
libxslt                   1.1.35               h2bbff1b_0
lxml                      4.9.1           py310h1985fb9_0
lz4-c                     1.9.4                h2bbff1b_0
markdown                  3.4.1              pyhd8ed1ab_0    conda-forge
markupsafe                2.1.1           py310h2bbff1b_0
matplotlib                3.5.3           py310h5588dad_2    conda-forge
matplotlib-base           3.5.3           py310hd77b12b_0
matplotlib-inline         0.1.6           py310haa95532_0
mistune                   0.8.4           py310h2bbff1b_1000
mkl                       2021.4.0           haa95532_640
mkl-service               2.4.0           py310h2bbff1b_0
mkl_fft                   1.3.1           py310ha0764ea_0
mkl_random                1.2.2           py310h4ed8f06_0
multidict                 6.0.2           py310h2bbff1b_0
munkres                   1.1.4                      py_0
nbclassic                 0.4.8           py310haa95532_0
nbclient                  0.5.13          py310haa95532_0
nbconvert                 6.5.4           py310haa95532_0
nbformat                  5.7.0           py310haa95532_0
nest-asyncio              1.5.6           py310haa95532_0
notebook                  6.5.2           py310haa95532_0
notebook-shim             0.2.2           py310haa95532_0
numexpr                   2.8.4           py310hd213c9f_0
numpy                     1.23.5          py310h60c9a35_0
numpy-base                1.23.5          py310h04254f7_0
oauthlib                  3.2.2              pyhd8ed1ab_0    conda-forge
openssl                   1.1.1t               h2bbff1b_0
opt_einsum                3.3.0              pyhd8ed1ab_1    conda-forge
packaging                 22.0            py310haa95532_0
pandas                    1.5.2           py310h4ed8f06_0
pandocfilters             1.5.0              pyhd3eb1b0_0
parso                     0.8.3              pyhd3eb1b0_0
pcre                      8.45                 hd77b12b_0
pickleshare               0.7.5           pyhd3eb1b0_1003
pillow                    9.3.0           py310hd77b12b_2
pip                       22.3.1          py310haa95532_0
platformdirs              2.5.2           py310haa95532_0
ply                       3.11            py310haa95532_0
pooch                     1.4.0              pyhd3eb1b0_0
prometheus_client         0.14.1          py310haa95532_0
prompt-toolkit            3.0.36          py310haa95532_0
prompt_toolkit            3.0.36               hd3eb1b0_0
protobuf                  3.20.3          py310hd77b12b_0
psutil                    5.9.0           py310h2bbff1b_0
pure_eval                 0.2.2              pyhd3eb1b0_0
pyasn1                    0.4.8                      py_0    conda-forge
pyasn1-modules            0.2.7                      py_0    conda-forge
pycparser                 2.21               pyhd3eb1b0_0
pygments                  2.11.2             pyhd3eb1b0_0
pyjwt                     2.6.0              pyhd8ed1ab_0    conda-forge
pyopenssl                 22.0.0             pyhd3eb1b0_0
pyparsing                 3.0.9           py310haa95532_0
pyqt                      5.15.7          py310hd77b12b_0
pyqt5-sip                 12.11.0         py310hd77b12b_0
pyrsistent                0.18.0          py310h2bbff1b_0
pysocks                   1.7.1           py310haa95532_0
python                    3.10.9               h966fe2a_0
python-dateutil           2.8.2              pyhd3eb1b0_0
python-fastjsonschema     2.16.2          py310haa95532_0
python-flatbuffers        23.1.21            pyhd8ed1ab_0    conda-forge
python_abi                3.10                    2_cp310    conda-forge
pytz                      2022.7          py310haa95532_0
pyu2f                     0.1.5              pyhd8ed1ab_0    conda-forge
pywin32                   305             py310h2bbff1b_0
pywinpty                  2.0.2           py310h5da7b33_0
pyzmq                     23.2.0          py310hd77b12b_0
qt-main                   5.15.2               he8e5bd7_7
qt-webengine              5.15.9               hb9a9bb5_5
qtconsole                 5.4.0                    pypi_0    pypi
qtpy                      2.2.0           py310haa95532_0
qtwebkit                  5.212                h3ad3cdb_4
requests                  2.28.1          py310haa95532_0
requests-oauthlib         1.3.1              pyhd8ed1ab_0    conda-forge
rsa                       4.9                pyhd8ed1ab_0    conda-forge
scipy                     1.10.0          py310hb9afe5d_0
send2trash                1.8.0              pyhd3eb1b0_1
setuptools                65.6.3          py310haa95532_0
sip                       6.6.2           py310hd77b12b_0
six                       1.16.0             pyhd3eb1b0_1
snappy                    1.1.9                h82413e6_1    conda-forge
sniffio                   1.2.0           py310haa95532_1
soupsieve                 2.3.2.post1     py310haa95532_0
sqlite                    3.40.1               h2bbff1b_0
stack_data                0.2.0              pyhd3eb1b0_0
tensorboard               2.10.0          py310haa95532_0
tensorboard-data-server   0.6.1           py310haa95532_0
tensorboard-plugin-wit    1.8.1              pyhd8ed1ab_0    conda-forge
tensorflow                2.10.0          mkl_py310hd99672f_0
tensorflow-base           2.10.0          mkl_py310h6a7f48e_0
tensorflow-estimator      2.10.0          py310haa95532_0
termcolor                 2.2.0              pyhd8ed1ab_0    conda-forge
terminado                 0.17.1          py310haa95532_0
tinycss2                  1.2.1           py310haa95532_0
tk                        8.6.12               h2bbff1b_0
toml                      0.10.2             pyhd3eb1b0_0
tomli                     2.0.1           py310haa95532_0
tornado                   6.2             py310h2bbff1b_0
traitlets                 5.7.1           py310haa95532_0
typing-extensions         4.4.0           py310haa95532_0
typing_extensions         4.4.0           py310haa95532_0
tzdata                    2022g                h04d1e81_0
urllib3                   1.26.14         py310haa95532_0
vc                        14.2                 h21ff451_1
vs2015_runtime            14.27.29016          h5e58377_2
wcwidth                   0.2.5              pyhd3eb1b0_0
webencodings              0.5.1           py310haa95532_1
websocket-client          0.58.0          py310haa95532_4
werkzeug                  2.2.2              pyhd8ed1ab_0    conda-forge
wheel                     0.37.1             pyhd3eb1b0_0
widgetsnbextension        3.5.2           py310haa95532_0
win_inet_pton             1.1.0           py310haa95532_0
wincertstore              0.2             py310haa95532_2
winpty                    0.4.3                         4
wrapt                     1.14.1          py310he2412df_0    conda-forge
xz                        5.2.10               h8cc25b3_1
yarl                      1.7.2           py310he2412df_2    conda-forge
zeromq                    4.3.4                hd77b12b_0
zipp                      3.13.0             pyhd8ed1ab_0    conda-forge
zlib                      1.2.13               h8cc25b3_0
zstd

When I run my code (see just below), I got the following error: "Canceled future for execute_request message before replies were done
The Kernel crashed while executing code in the the current cell or a previous cell. Please review the code in the cell(s) to identify a possible cause of the failure. Click here for more info. View Jupyter log for further details."
model = models.Sequential()
model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(32, 32, 3)))  #32 represents number of filters and (3,3) the size of the filters
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(64, (3,3), activation='relu'))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(64, (3,3),activation='relu'))

The first blocks of my code (which work fine) are as followed:
import tensorflow as tf

from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

#Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255, test_images

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']

IMG_INDEX = 69

plt.imshow(train_images[IMG_INDEX], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[IMG_INDEX][0]])
plt.show()

So I followed the instruction and tried to reinstall tensorflow. I also created a new environment to just have tensorflow and matplotlib as the modules I manually installed (fearing that other modules that I installed might interfere with the tensorflow one). I also used another environment with an older python version (3.9.16 instead of 3.10.9) Nothing worked
The instructions I followed come from github: "
If a kernel crashes when using tensorflow, this is indicative of tensorflow having been incorrectly installed into the Python Environment. Re-installing the package would resolve the issue.
If this does not work, it is also possible other dependent packages could cause the package to fall over, in such cases, its best to start out with a new environment.
Finally, when using Conda environments, please avoid using pip to install packages, instead use conda install.
Originally filed here https://github.com/microsoft/vscode-jupyter/issues/9283 and here https://github.com/microsoft/vscode-jupyter/issues/9157
Could you guys help ?
Comment: Has anyone an answer for this one?
Comment: Please ensure you have followed all the step by step instructions mentioned in this [link](https://www.tensorflow.org/install/pip) to install tensorflow in your system and you are accessing the jupyter notebook from the same created VirEnv. Attaching a similar [issue](https://stackoverflow.com/questions/74050233/canceled-future-for-execute-request-message-before-replies-were-done) here for your reference.
Answer: You could possibly be running out of memory. Try scanning the memory usage while running the cell. If it reaches 100%, add this to your notebook:
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

Comment: Also in your memory usage, check that you have adequate Swap space. Swap is basically disk drive used as cached ram. So if your notebook requires more ram than you have, it can use the hdd as ram
Comment: I will. Thanks for the tips. I appreciate it
Answer: Check if your CPU is like mine and only can do SSE 4A.
tensorflow 2 needs CPU with SSE 4.2
Tun cpux and look for SSE CPU type
MMX(+), 3DNOW!(+), SSE(1, 2, 3, 4A), AMD-V, x86-64
Try uninstall tensorflow 2 and use 1.15 if you can
pip install tensorflow==1.15

Kernel crashes when I use tensorflow


Pearl's Causal Inference In Statistics, equation 3.11 - Calculation of group specific causal effects

Question: In the book Causal Inference In Statistics by Pearl, page 63, while referring to the below DAG, it says -

Thus to compute the $w$-specific causal effect, written
$P(y|do(x),w)$, we adjust for $T$, and obtain
$P(Y=y|do(X=x),W=w)$ $=$ $\sum_t {P(Y=y|X=x,W=w,T=t)P(T=t|X=x,W=w)}$
(3.11)

I have the following queries -

Why does it say - "to compute the $w$-specific causal effect, written $P(y|do(x),w)$"? Given the definition of $do(x)$ presented here, it cannot be guaranteed that $P(y|do(x),w)$ calculates the respective causal effect, when conditioning on $w$ opens up a non-causal path (highlighted in pink in the figure). Am I understanding the definition of $do(x)$ incorrectly here?
In the equation if the summation on the right-hand side is performed,
$\sum_t {P(Y=y|X=x,W=w,T=t)P(T=t|X=x,W=w)}$
$=\sum_t {P(Y=y,T=t|X=x,W=w)}$
$=P(Y=y|X=x,W=w)$
which should not be the causal-effect as it seems to be including the association rising from the non-causal path. What am I missing here?
Answer: The $w$-specific causal effect of $X$ on $Y$ is quite distinct from the causal effect of $X$ on $Y.$ The causal effect of $X$ on $Y$ is just $P(y|do(x)).$ The $w$-specific causal effect of $X$ on $Y$ is as you've written: $P(y|do(x),w).$ Essentially, you are stratifying the causal effect of $X$ on $Y$ by values of $w.$ Now, in the particular case in question, there are backdoor or other non-causal paths opened up by conditioning on $w,$ so it is necessary to stop those up to get the true $w$-specific causal effect (just condition on $Z$ or $T$ as well to stop up the undesired path - hence the first formula in your question). I don't think you're necessarily misunderstanding the $do$ operator.
In your second question, you need to understand what's meant by "including the association rising from the non-causal path". You could include that association in more than one way. In this example, we're "including" that association by adjusting for it so that it does not bias our results.
Comment: $W$ is post-intervention because the arrow goes *from* $X$ *to* $W.$ $W$ is measured, so it should be in the data. It's not possible to adjust for unmeasured variables, unless you do something like the front-door adjustment.
Comment: In $P(y|do(x),w)$ is $W=w$ measured post-intervention? And in the final expression of the second query - $P(Y=y|X=x,W=w)$ - is $w$ here a measure from observational/pre-intervention data? I think it should be because we are only theoretically simulating the intervention, and hence, do not have actual access to post-intervention data.
Comment: Given the [Rule 2 in this query](https://stats.stackexchange.com/q/602856/331772), should it be $P(T=t|X=x,W=w)$ or $P(T=t|W=w)$ in equation 3.11? This is similar to the [this query](https://stats.stackexchange.com/q/530162/331772), where you supported the later expression. According to this [source](https://medium.data4sci.com/causal-inference-part-xiii-conditional-interventions-and-covariate-specific-effects-1c0126b8b996) it should be $P(T=t)$. Any idea which should be the correct one, and some solid source for it?
Comment: Found the following [reliable errata page from Pearl's own UCLA website](http://bayes.cs.ucla.edu/PRIMER/). The errata [here](http://bayes.cs.ucla.edu/PRIMER/pearl-etal-2016-primer-errata-pages-august2021.pdf) changes the figure to replace $W \leftarrow X$ to $W \leftarrow V \rightarrow X$ and also suggests $P(T=t|W=w)$. In fact an [earlier version of this same errata page](http://web.cs.ucla.edu/~kaoru/BIB5/pearl-etal-2016-primer-errata-pages-may2017.pdf) introduced $X=x$ in the first place. @AdrianKeister, do I need to edit the question accordingly?
Comment: Those are good questions. I'm not sure I can answer them fully - we probably need Carlos Cinelli for that (probably CrossValidated's best expert on causality). Off the top of my head, I'd say that some of those expressions are probably equivalent if the DAG has certain characteristics. For example, if $X$ and $Y$ are completely independent in the DAG, then you can say $P(Y|X)=P(Y).$ That sort of thing. But it requires detailed thinking to tease out all the possibilities.


Can you use linear regression to predict individual player performance from team performance?

Question: Imagine you have performance scores for each player on a soccer team using some sort of ranking system. You then group these player scores into the teams they play for, then average the player scores to calculate a "team performance" score (assuming here that better players mean a better team).
If you plot the individual performance on one axis and team performance on the other axis, a linear relationship is observed, and the data passes other assumptions of linear regression.
Is linear regression an appropriate modelling approach to use here, to predict individual performance from team performance?
I saw this approach in a paper (page 7) and was interested in this seemingly "circular" connection of the variables, how the dependent variable is so directly linked to the the independent variable. Is there a name for this type of approach?
Comment: [Perhaps related](https://stats.stackexchange.com/questions/592535/can-predictive-models-make-predictions-for-individuals-or-only-for-groups/592536)
Answer: Predicting individual performance on game A given team performance on game A doesn't seem like a predictive problem as much as solving a system of equations.
I don't see a problem using linear (or non-linear!) regression to predict individual performance on game A given team performance on game B, since your team's past performance is a function of your performance.
Whether the function you are trying to model is "aggregating things" or "individualizing things," there is nothing circular going on, you are simply modeling a function. The more directly linked your input variables are to your output variables, the better!
With all this said, in the paper you are referring to, I think team performance refers to "the quality of the team" not including the individual player. When you have good teammates, you play better (because there are better team dynamics, because you don't want to let them down, etc...). The team you play in can affect your performance, but it is not a function of your performance.
Reference from the article:

The first pool of variables represents the team quality. The first indicator (the average team rating except for the observed player) serves as a proxy for the team environment and can be a source to improve individual HC.
Comment: Great, thanks @pip.pip. This has helped me better articulate the question I want to ask: How does the performance of a team impact on a player, and the opposite, how does the performance of an individual impact on a team. Say your average team buys a superstar player, how can you show the impact of the player on the team (do they improve the performance) or the impact of the team on the player (does the team make the individual worse)?
Comment: With that said do you have any example systems of equations you think could be applicable in this situation?


Crud com Edição dentro da Própria tabela e busca de dados + banco de dados

Question: Alguém poderia me indicar uma forma de fazer um CRUD com edição pela própria tabela ? Detalhe essa tabela tem que estar lincada em um banco de dados, fiz ela em PHP com Busca, ficou show de bola, porem meu chefe não quis, ele quer algo mais simples ao usuário,
a pessoa entra na pagina onde os dados são exibidos clica na célula da tabela, edita o dado errado e PRONTO, salva o dado dela, não pode ter botões nem redirecionamento a outras paginas, tudo em uma pagina só...to quebrando a minha cabeça, tentei fazer em JQUERY mais vou ser sincero não sei linkar com o meu banco de dados e nem fazer a busca.
conheço um pouco de PHP, mais não foi o suficiente.
Alguém poderia me ensinar, me indicar um vídeo, me mostrar códigos qualquer coisa ajuda, emprego pode estar em jogo.
Answer: Existe uma lib chamada Bootstrap Table, eu uso em todos meus projetos, acho que é bem documentada e fácil de usar, existe uma extensão dela que tem exatamente oque você quer aqui. Vou deixar um exemplo da implementação da lib normal, nunca usei essa extensão de editar as informações direto das celulas.
Primeiro você cria uma table e dá um id pra ela:

                    ID

Esse data-field vai ser o nome do atributo que a table receberá. Por exemplo, você devolve um json com a lista de pessoas, e o objeto pessoa no seu php provavelmente terá um id, colocando data-field="id" você está dizendo que naquela coluna ficará o id da pessoa.
Java Scrpit:
$("#table").bootstrapTable({
  ajax: urlQueVaiDevolverAListaDeJson,
  search: true, // se true, cria cria um campo de busca, e implementa a busca sozinho
  sidePagination: "client",
  pageSize: 5, // quantidade de itens por pagina.
  pagination: true // se true, cria uma paginação por você
});

Enfim.. é isso.. esse é o básico sobre o bootstrap table, ela faz muita coisa por você.. busca.. paginação.. e etc. Sugiro que você estude ela, e a extensão que tem oque você quer.


View to display the comments of the curent user nodes

Question: Please how to create a simple view to display the comments of the curent user nodes, only comments,
Thank you.
Answer: When you add a new view (/admin/structure/views/add), you have the possibility to select Comments.
It will list all comments.
Then you need to set a Contextual Filter and a Relation in order to get the comments of the current logged in user.
Comment: Thank you Matt, i don't want  comments of curent user, but comments created by others (..of nodes created by curent user)
Comment: Then you will need to play around with the Relations: create a relation with your current logged in user, to link to all the nodes he created. Then list all comments of these nodes, and exclude those created by your user with a filter.


jQuery set child CSS attribute problem

Question: I have a child element of a div named "bob" that's class is '.divTitle'

Title

I am trying to set the background color of "divTitle" to red but for the life of me can't get this to work.  Right now I am trying two things...
$('#bob').children('.divTitle')[0].css('background-color', '#0f0'); // assuming children is returning an array...

and
$('#bob').children('.divTitle').css('background-color', '#0f0');

neither with any success... can anyone tell me what I am missing here?  Do I have to go deeper than ".children"?

EDIT

Unfortunately, I guess the important part of this question was omitted.  I was generating this div dynamically, and making reference to the class was just coming up empty.  So, instead of referencing the dynamically generated interior div by class type, I gave it a unique id and now can manipulate it as I wish...  I'm still giving the check mark to Keltex for pointing out a better direct reference method.
Comment: Other than you're setting it to green?
Comment: that's just clerical... i'd be happy if it turned ANY color...
Comment: You should try #f00 instead of #0f0...
Answer: Why not just:
$('#bob .divTitle').css('background-color', '#0f0');

Comment: The problem he's having is getting children() returns the actual DOM elements, whereas using the selector gives you back jQuery objects (which actually have a css method).  So you get my upvote :)
Answer: The second should work fine. Your problem lies somewhere else.
First thing: are you executing this code when the document is ready loading/populating the elements of interest?

    ...

...

If not, then do so, or move the script to after the DOM elements of interest.
...

Title

...

Comment: the div 'bob' is being generated dynamically after my document has loaded on a key press.  I am able to change the background color of 'bob' with no problem, I just can't figure out why I can't reach inside of bob and manipulate child elements...
Answer: $('#bob').children('.divTitle')[0] <-- this is returning the dom object rather than the jQuery object which is why this one doesn't work.
The second one should work for you though, I've done what you have above as an example.

jQuery set child CSS attribute problem


How to call Dot net webservice with with (x-www-form-urlencoded) format ASMX on Android

Question:
How to call Dot net webservice with with (x-www-form-urlencoded)
format ASMX on Android
Answer: Hope this will be helpful for you
http://androidexample.com/Dot_Net_Webservice_Call_-_Android_Example/index.php?view=article_discription&aid=100&aaid=122


How to change the transform property with selenium WebDriver

Question: I am trying to change the transform property on this particular website: https://www.weltsparen.de/etf-portfolio/WI04
I'm trying to set the first translate parameter to 0 instead of 275 with the selenium WebDriver and then probably run the website again, because I want to get another values from the graph showed in the figure bellow, and this parameters in the translate are the positions of the values.
Graph:

HTML:
<g class="Indicatorstyles__indicator--3lFtS" display="block" transform="translate(275,370)">

Is it possible?
Answer: You can easily set the first translate parameter to 0 instead of 275 using setAttribute() at the client-side using Selenium. However this change won't be updated to the server-side.
Hence, when you would run the website again i.e. refresh() or invoke get() the changes would be lost.

References
You can find a couple of relevant detailed discussions in:

Change value field in html input tag using selenium in python
How to send a date directly as text to a calendar control with readonly attribute using Selenium through Python?


Count Recursively on a collection in MongoDB

Question: I have a list of documents in MongoDB with a tree structure. I want a single aggregation query which returns the count of all nested children, given an _id property.
Structure:
{
  '_id': '1',
  'parentId': null,
},
{
  '_id': '2',
  'parentId': '1',
},
{
  '_id': '3',
  'parentId': '1',
},
{
  '_id': '4',
  'parentId': '3',
}

Aggregation result: (given: _id='1')
{
  total_children: 3
}

I understand that this probably requires a $graphLookup stage, and this question is very similar to Recursive search on a collection in MongoDB but is backwards in a sense.
Answer: You can use below aggregation query.
Recursive lookup to locate all the children for a given _id followed by $size to count the chidren.
db.col.aggregate([
  {"$match":{"_id":"1"}},
  {"$graphLookup":{
    "from":col,
    "startWith":"$_id",
    "connectFromField":"_id",
    "connectToField":"parentId",
    "as":"children"
  }},
  {"$project":{"total_children":{"$size":"$children"}}}
])

Comment: This might be a dumb question, but what is `col` in the $graphLookup stage? edit: nevermind, that is my collection. Thank you!


how does http proxy work?

Question: I searched the web for something about http-proxy.
I read wiki-articles about proxy server.
But I still don't understand how http proxy works, stupid me.
Here is my assumption about how http proxy works:
If I set the http-proxy to a specific one, say Proxy_A, then when I start up the chrome/IE, type in a specific URL, say URL_A, does the chrome/IE send the request directly to Proxy_A,
then the Proxy_A sends the request to the real server of URL_A?
Comment: Yes, mostly then Proxy_A sends the response back to you. Pretty simple eh
Comment: http://www.amazon.com/HTTP-Definitive-Guide-David-Gourley/dp/1565925092/ref=sr_1_1?ie=UTF8&qid=1314064943&sr=8-1 has a whole chapter on http proxy
Comment: even if the client is just doing HTTP GET - if the server/backend is secured (SSL), then client must initiate the connection by doing HTTP CONNECT method first to establish the connection first with the backend - due to encryption.
then comes the other HTTP methods like the GET.
Comment: This question is barely relevant to stackoverflow.
Comment: If your question is still unanswered, maybe provide more details what you need to know ?
Comment: I think its important to clarify the difference between a "HTTP proxies" or "Web proxies", and other types of proxies; You send the HTTP request directly to the proxy (along with an absolute URL so it knows where to forward the message, which is not required if you make the request directly to the server). Other kinds of proxies some of sometimes erroneously called "web proxies" work at network layer and have no knowledge of HTTP.
Comment: this is a [great resource](https://parsiya.net/blog/2016-07-28-thick-client-proxying---part-6-how-https-proxies-work/) on the topic
Answer: A HTTP proxy speaks the HTTP protocol, it's especially made for HTTP connections but can be abused for other protocols as well (which is kinda standard already)
The browser (CLIENT) sends GET http://SERVER/path HTTP/1.1 to the PROXY
Now the PROXY will forward the actual request to the SERVER.
The SERVER will only see the PROXY as connection and answer to the PROXY just like to a CLIENT.
The PROXY receives the response and forwards it back to the CLIENT.
It is a transparent process and nearly like directly communicating with a server so it's just a tiny overhead for the browser to implement a HTTP proxy.
There are some additional headers that can be sent to identify the client, reveal that he's using a proxy.
Proxies sometimes change/add content within the data stream for various purposes.
Some proxies for example include your real IP in a special HTTP HEADER which can be logged server-side, or intercepted in their scripts.
CLIENT <---> PROXY <---> SERVER

Update:
Related to using proxies as a security/privacy feature
As you can see in the ascii above, there is no direct communication between CLIENT and SERVER. Both parties just talk to the PROXY between them.
In modern worlds the CLIENT often is a Browser and the SERVER often is a Webserver (Apache for example).
In such an environment users often trust the PROXY to be secure and not leak their identity.
However there are many possible ways to ruin this security model due to complex software frameworks running on the browser.
For example Flash or Java applets are a perfect example how a proxy connection can get broken, Flash and Java both might not care much about the proxy settings of their parent application (browser).
Another example are DNS requests which can reach the destination nameserver without PROXY depending on the PROXY and the application settings.
Another example would be cookies or your browser meta footprint (resollution, response times, user-agent, etc.) which might both identify you if the webserver knows you from the past already (or meets you again without proxy).
And in the end, the proxy itself needs to be trusted as it can read all the data that goes through it and on top it might even be able to break your SSL security (read up on man in the middle)
Where to get proxies from
Proxies can be bought as a service, scanned for or simply run by yourself.
Public proxies
These are the most often used proxies and the usual term "public" is quite misleading.
The better term would be "open proxies". If you run a proxy server without firewall or authentication anyone in the world can find it and abuse it.
The large majority of companies selling proxies just scan the internet for such proxies or they use hacked windows computers (botnets) and sell them for mostly illegal/spam activity.
Most modern countries can see the use of an open proxy without authorization as abuse, it's a very common thing but can actually lead to prison time.
It's possible to scan for proxies by searching the internet for open ports, a typical free program would be https://nmap.org
As a word of caution: Larger scaled scanning will almost certainly get your internet connection banned by your ISP.
Paid proxies
Here we have 4 types of proxies:
1) Paid public (open) proxies
Basically these sellers sell or resell huge lists of proxies that are regularly refreshed to remove dead ones.
The proxies are abused on a massive scale and usually blacklisted on most sites, including Google.
Additional those proxies are usually very unstable and very slow.
The large majority of these proxies are simply abusing wrongly configured servers.
It's a very competitive "market", Google will lead to many examples.
2) Paid hacked (botnet) proxies
These are abusing computers, mostly internet-of-things or windows desktops as proxy hosts. The attackers use them in large scale for various illegal purposes.
Sellers usually call them "residential proxies" to hide the illegal nature of them.
Using such a proxy is without doubt illegal and the abused user can easily log "your" IP if you connect to it, including the possibility to hijack your connection to the destination.
Depending on the source those IPs are not blacklisted, so the "quality" is much better than public proxies.
3) Paid shared proxies
These are datacenter proxies, usually legal and potential with a fast uplink.
Due to the fact that there is so much e-commerce spam going on those IPs are massively abused and usually found in blacklists.
A typical use would be circumvention of craigslist restrictions or geo-restrictions.
4) Paid private/dedicated proxies
"private" means dedicated. If the operator is professional it means your proxy is not shared among other people.
These are often used for more professional and legal activity, especially when the proxy IP is rented for alonger period.
A well known operator would be https://us-proxies.com
Own proxies
Running an own proxy is possible as well, there are various open-source projects available.
The mostly used proxy server is https://squid-cache.org
Comment: So how is the original URL send to the proxy?
Comment: Had same question as @edwin. Had to re-read several times. Maybe what confused me was in the example I thought "host.tld" was PROXY when in fact it was SERVER.  The answer is accurate, but for uninitiated could use some refinement so a single read through would be sufficient.  Possibly as simple as removing the host.tld reference e.g. "sends something like `GET http://SERVER/path HTTP/1.1` to the PROXY".  Or ... something.
Comment: @John - if the SERVER sees the Proxy as the "client", then how are things like cookies handled?  In otherwords, what prevents the cookies from being dropped on the proxy vs on the actual CLIENT?
Comment: The proxy is just transmitting the data, cookies are part of the HTTP header so it's transmitted just like any other meta data.
Everything the browser sends to the proxy is passed over to the destination and everything from the destination is passed back to the proxy. (Let's ignore the fact that some proxies can modify data)
Comment: Hi John (or any other future visitor), I have a question: so IIUC, a proxy server hides the client's true ID from the recipient server (i.e. the server of http://host.tld/), but it cannot hide it from the ISP's server right? If so, is there a way to hide from the ISP?
Comment: Look for TOR or cloakfish in Google.
Comment: John your answer to the question "So how is the original URL send to the proxy?" is inadequate. It doesn't answer why that request get routed to the proxy, it's clearly targeting something else.
Comment: No actually my answer is precise but it seems like you did not understand it ?
Maybe read my original answer and my comment once more.
Comment: Any example? I was try something like `GET http://SERVER/path HTTP/1.1` but proxy server only response `HTTP/1.1 200 OK`
Comment: @John You mentioned an issue where flash application might not respect browser's proxy setting. I don't really udnerstand that. Isn't proxy set on OS level? Doesn't all network traffic go through proxy?
Comment: @Loreno Proxies are at application level and browsers never cared that much about security, especially when it comes to plugins.
Flash uses your real IP and your browser doesn't care about it.
A VPN can prevent that, though even here you are not 100% secure but a lot more.
Comment: @John So what is the use of OS-level proxy setting? (/etc/environment in linux for example). After all any connection that is made is managed by the OS - shouldn't the OS then ALWAYS stick to its proxy settings? How can Flash app go around that?
Comment: There is kernel level and application level proxying.
What you describe is application level, which means that applications can use those settings if they support it. Nothing forces them
Comment: Hi everyone, could some one help me how to identify in Chrome Network Tab if the request is being proxied and forwarded ? Thank you...
Answer: To add to John's great answer above, one important step is the initial CONNECT handshake between PROXY and CLIENT. From the Websocket RFC
CONNECT example.com:80 HTTP/1.1
Host: example.com

This is the same request that a CLIENT uses to open an SSL tunnel, which essentially uses a proxy
Comment: No actually that's not true Ivan
trik just described the CONNECT method but the question was about http-proxies.
CONNECT is used to open a unviversal TCP/IP tunnel while GET as you'll find in my answer is used for a specific tunnel. HTTP.

For SSL you need a raw tunnel due to encryption, that's why CONNECT is being used.
Comment: I feel like this is the complex part of the answer and the accepted answer is rather trivial without this. You've answered the important bit: _how_ does the proxying happen. Or at least you've give a lead to more information.
Comment: Thanks, without this part explained, we would ask, in https how can the proxy server know the desired destination if every thing is encrypted! that is why a `CONNECT` request in plain text is first sent to the proxy before the browser starts to speak to the website, while the proxy is just forwarding encrypted data between them.
Comment: @John Is it possible to make use of HTTP CONNECT for plain HTTP requests as well?
Comment: @omjego CONNECT is for proxies, not for web servers. They use GET/POST/PUT etc.
CONNECT is just a codeword, it's called "connect" so people understand it's a request to  connect somewhere else while GET or POST means to talk to the server you just connected
Comment: Oh I meant is it possible to use CONNECT to access HTTP server via proxy?  So that I can access the server over tunnel created by proxy.

how does http proxy work?


WCF service hosted in IIS7 with administrator rights?

Question: How do I grant administrator rights to a running WCF service hosted in IIS7?
The problem is, my code works fine in a test console application runned as an administrator, but the same code used from WCF service in IIS7 fails.
When I run the same console test application without admin rights, code fails.
So, how do I grant admin rights to a WCF service hosted in IIS7?
Do I grant admin rights to IIS7 service? Can I grant rights to a specific WCF service? How do I do 'Run as an administrator' on IIS7 or specific website?
Thanks!
(That's the question, here is a more detailed description of a situation:
I am trying to capture frames from a webcam into a jpg file using Touchless library, and I can do that from a console application with admin rights.
When I run that same console app without admin rights I cannot access a webcam in code. Same thing happens in a WCF service with the same code.)
Answer: The permissions that your WCF service is running under is most likely the application pool identity.  First, be careful with granting admin rights to an app pool.  I would separate this service to it's own app pool if you can to minimize the footprint of what needs admin rights.
Visit the app pool and go to advanced settings in the Actions pane.  You can set your own custom admin user there.
Also, there's a chance that part of the service runs as the anonymous user's account.  To change that edit the site and then authorization -> anonymous.  Set it to use the app pool identity.  That way everything will run under the identity set in the app pool.
Comment: Thnks Scott. I'm sorry, but I didn't quite understand what to edit, where to set identity. I can edit sites Basic Settings and Connect as specific user (as opposed to connecting as Application user), or I can edit .NET Authorization Rules, or I can edit IIS Authentication. Which one did you mean?
Comment: Hi Allan.  There's another section in IIS7, up at the top level, called Application Pools.  First, at your website level, click on "Basic Settings" in the Actions pane.  That will tell you which App pool your site is in.  Then click on Application Pools and select your site's app pool.  Then click "Advanced Settings..." from the Actions pane.  In there under Process Model -> Identity, you can change the identity of the app pool.  Also at the site level, authentication icon, edit the Anonymous Authentication option. Set it to "Application pool identity"


Universal covering of a connected sum

Question: Maybe it's an easy question: How can we find the universal covering of the connected sum of tori or projective planes? Is there a general method?
Comment: See [this](http://mathoverflow.net/questions/93282/homotopy-groups-of-connected-sums/93285#93285) answer by Ryan Budney.
Comment: For the surfaces of genus $g > 0$ the universal cover is the hyperbolic plane, this is a classical result. I know that this is not really an answer to your question so I stated it as a comment.
Comment: Have you a reference?
Answer: Let $X_1$ (resp. $X_2$) be a sphere and $D_1$, $D_1'$ (resp. $D_2$, $D_2'$) two diametrically opposed disks on $X_1$ (resp. $X_2$). Then, set $\tilde{X}_1= X_1 \backslash (D_1 \cup D_1')$ and $\tilde{X}_2=X_2 \backslash (D_2 \cup D_2')$. Finally, define $\tilde{X}$ by $(\tilde{X}_1 \coprod \tilde{X}_2 )/ \sim$, where $\sim$ identifies $D_1$ with $D_2$, and $D_1'$ with $D_2'$.
Then, $X_i$ is the universal covering of a projective plane (and the projection is given by identifying two diametrically opposed points on $X_i$) so $\tilde{X}$ is a $2$-sheeted covering space of the connected sum of two projective planes. But it is easy to see that $\tilde{X}$ is homeomorphic to $\mathbb{T}$, so the universal covering of the sum of two projective planes is homeomorphic to $\mathbb{R}^2$. (In fact, the result doesn't depend on the number of projective planes we add.)
However, the projection from $\mathbb{R}^2$ onto the connected sum is difficult to explicit because the homeomorphism between $\tilde{X}$ and the torus is itself difficult to explicit. But this method shows that the fundamental group of the connected sum of two projective plans contains a subgroup of index $2$ isomorphic to $\mathbb{Z}^2$.
It seems to be more difficult for a connected sum of tori, because the universal covering has infinitely many sheets.
Added: From John Lee's beautiful book Geometry of surfaces, we are able to prove

Theorem: Let $S \neq \mathbb{S}^2, \ \mathbb{R}^2P, \ \mathbb{T}^2$ be a connected compact surface and let $\Pi \subset \mathbb{H}^2$ denote a regular $4n$-gon such that $S$ is homeomorphic to some identification space $S_{\Pi}$. Then there exists a regular tesselation of $\mathbb{H}^2$ by $\Pi$ inducing a covering $\mathbb{H}^2 \to S$.

A proof follows from the theorems at pages 37, 123 and 129.

Universal covering of a connected sum


C++ map - expression must be an integral constant expression

Question: <code>#include <map>
#include <string>

std::map<std::string, int> foo;
foo["bar"] = 1;
</code>
Why do I get the error "expression must be an integral constant expression" in visual studio 12?
I can't work this one out...
Comment: @juanchopanza: Just a nit, but, while it's true that a statement must go in a funciton, that's because if it's in a function it's regarded syntactically as a statement. And so one can't use the *syntactical form* as a criterion for where something is admitted. In particular, a declaration of a variable is a statement (an example of a block declaration) when it's inside a function, but it's just a declaration (and permitted) outside of a function --  thus if you look at its syntactic form and say "hey, that's a statement, must be inside a function" you get the wrong conclusion.
Comment: Compiles perfectly fine for me. VS2013.
Comment: [Works with gcc](http://coliru.stacked-crooked.com/a/7ef2da95029f6919).
Comment: @Steve Then your compiler is broken. Statements must go in functions.
Comment: @Steve gcc isn't broken. `foo["bar"] = 1;` is a statement and it must go in a function.
Comment: @juanchopanza: I really do think we should resurrect the terminology from BCPL, the ancestor of C which is ancestor of C++, where non-declaration statements were called **commands**. That term was very useful in pre-C99 C, because declarations had to come before commands in blocks. And it's still very useful for discussing the issue at hand: *commands have to be in functions*. :)
Comment: @juanchopanza I added a main function ... The comment isn't helpful.
Comment: @Cheersandhth.-Alf That's a good point and I do find the current C and C++ terminology lacking in this respect. Thanks for nit-picking, it is good to step back and think of these things carefully every now and then.
Answer: You need to place the code inside a function.
<code>#include <map>
#include <string>

void xyz()
{
   std::map<std::string, int> foo;
   foo["bar"] = 1;
}
</code>
I verified VS 2013 has a problem otherwise, but it works when inside a function. As others have noted, most statements aren't allowed outside of a function.


What is the job title of someone who comes up with lyrics and a beat, but not instrumentation?

Question: In a songwriting session, if I'm the one who came out with the lyrics and the beat of the song but didn't make the musical instrumental (can't play any musical instrument). What am I?
Comment: A lyricist-beatman ;D
Comment: Assuming it's an 'ordinary, regular' song, then you are a lyricist., The rhythm ('beat') of the words is often dictated by the phrases themselves, so are part of the lyrics. Try singing 'Happy Birthday' in 4/4, starting on beat one, and you'll appreciate what I mean.
Comment: Did you come up with the melody for the lyrics?
Comment: Is this a rap song?
Comment: I would say, regarding credits, you definitely get "Words by Syukri" in the song credits and you have a case to make for "Music by Syukri and (whoever else comes up with music)". The other people who contribute to music and/or lyrics are people you want to negotiate with about credits, if that's what this question is about. Hopefully you can all agree on what is appropriate and fair attribution.
Answer: That is a very logical question.  It is quite common for folks who are good at writing lyrics to partner with other folks who are good at creating melodies!  Some folks strengths may lie in different areas and pooling those relative strengths can lead to much greater results than either partner working alone might hope to achieve.  There is not a requirement that you are able to do both.  In fact there are many very successful songwriting teams who employed this very strategy.
One of the most accomplished and well known such teams consisted of Burt Bacharach and Hal David. Hal David wrote the lyrics and Burt Bacharach composed (wrote) the music.  Together they wrote tons of hit pop songs and may still be writing to this day.
As the writer of the lyrics, you are the lyricists.  The person who adds the main melody would be the composer.  Both are "writers" of the song (songwriters).  You will often see published sheet music where the writing credits are listed as "Words (or Lyrics) by X, Music by Y".
Lyrics without a melody is nothing more than poetry or "spoken word" (which is often put to music).  Even a monotone song if intended to be sung over a beat would have a "melody".  If you write a poem, you own the rights to those words unless you convey those rights to someone else.
To make a "song" from your words - you must also have a melody (so you can "sing" the song).  Once you match lyrics with a melody, you have a song (although you can have a song with no lyrics).
Once you have lyrics and a melody, a composer, or producer can become an "arranger" and add supporting instrumentation to bring the song to life.  Creating an arrangement may be done by someone other than the person who "wrote" or composed the melody.  The arrangement would entail the rhythm and the other supporting instrumentation and background vocals (if desired).  The arranger would decide if the song needs a violin, a trumpet, a lead guitar, a banjo, a saxophone and so on.  The arranger would also decide where and how those instruments play a part in the overall musical composition.
Often the individual musicians will be tasked with creating their own accompanying part (in terms of which notes they actually play) that fits in with the melody.  For example, the lead guitar player (studio musician or session guitarist) may offer several options for lead guitar solos if the arranger decides such a solo is appropriate.  The selection of which version of a lead solo makes the final cut may be the result of a collaborative discussion among several of the musical contributors - coupled with trial and error.
How much each party contributes to the end result will vary greatly in every situation.  As the songs lyricist, you may want some input into the arrangement or melody because you have a strong connection with the emotions behind the lyrics.  Ideally the melody and overall arrangement will contribute to and support the emotions you wanted to convey with the lyrics.
There are a number of different rights that arise out of the writing and production of a song.  I am only familiar with how things work in the USA.  If the song becomes a "hit" and is able to generate revenue - the song writers and composers and arrangers and producers may all be entitled to some remuneration.
The rights to remuneration from the production of a hit song fall into three general categories.  There are "writers royalties" that go to the songs writer or co-writers.  There are publishing royalties that go to the song's publisher.  And there are mechanical royalties which arise out of sales of records (either digital recordings sold on line or physical mediums such as a CD).
Whenever several people collaborate on the writing of and production of a "song" - there should be a written agreement which outlines the percentage of all the different anticipated and potential royalties which may be payable as a result of the song realizing some degree of commercial success.  If you are writing just for fun and have no desire to ever see any money from your efforts and have no intention of promoting your song in a manner that could result in financial rewards, then a written agreement may not be needed.  But what happens if one of the other "co-writers" decides to promote it and the song gets sold to a major artist or label and becomes a huge commercial success?
So all listed "co-writers" may want to claim a portion of any rights to any future valuable consideration that may arise from the creation of the song.
Your "job" is to create compelling lyrics that convey meaning and emotion.  Your "title" in that process can be either of "co-writer" or "lyricist".  Regardless of what you choose to call yourself, as the writer of the lyrics, you are a vital, important and integral part of the "songwriting team".
EDIT: Since you are also dictating the groove and rhythm by creating the "beat" you could also be considered "co-arranger".
Have fun writing and good luck with your songs.
Answer: Disclaimer: this answer does not address the legal issues involved in songwriting/composing/preforming credits in terms of copyright.  It only addresses the common language aspects of the question.

If you literally just provided the words -- you'd be the "lyricist".
If you also constructed the melody that goes with those words you'd be the "song-writer".
If you came up with the words and someone else came up with the melody, the two of you "co-wrote the song".

Usually, the people who came up with the musical accompaniment might be considered arrangers (in that they developed an arrangement of the song), if they're called out at all.  In pop music the key central core of a work is usually defined as just the "lyrics+melody", most other aspects of a song, the chord changes, backing rhythm etc. are considered aspects of a specific arrangement and not part of the core identity of the song.  However, sometimes aspects
of the musical accompaniment is deemed central enough to the work that the people who created them are designated as part of the songwriter team.
(Since the Pharrell/Thicke copyright suit, I've started to hear murmurings that using "lyrics+melody" as the core identity of a work is no longer applicable to much contemporary popular music, but I haven't heard of a generally accepted alternative.)
Answer: In hip-hop and contemporary pop that is based on tracks and beats, the person who creates the beats, by which I mean the person who composes the rhythms and sounds, physically samples the samples, programs the drum machine, plays the instruments, and records and mixes the performances, is called the DJ or the producer.
In forms of music other than hip-hop and contemporary pop, the person who writes the instrumental part of the song, including the chords and the melody, is called the composer.
In hip-hop and contemporary pop that is based on tracks and beats, the person who composes the melody and the lyrics and adds them onto the already-composed beats is called the topliner. (This is a relatively new use of this term, which can also mean other things in fields other than composing music.) Another term is topline writer.
If you only compose the lyrics, you are a lyricist.
So you are telling us that you are a bit of a DJ/producer and a bit of a lyricist, but not a topliner because you didn't write the melody.
But all this is interactive. Some songs have several composers/authors who share authorship and performed different roles.
The important thing is that when the copyright for the song is registered, and especially if you are under contract to a music publishing company, that the legal document for copyright registration lists your name as one of the co-writers of the song. Otherwise you cannot collect any royalty checks over the years when the song earns money by being performed, played on the radio, streamed online, or licensed for use in motion pictures and video games, etc.
We don't give legal advice here on this site, but understand that unless you get legal proof of your participation in composing the song, you may be losing all your rights to earn income from this song in the future.
How to register copyright for a song, and how to get a contract with and deal with a music publishing company, or the need to join a performing rights organization, are way outside the scope of what is permitted to discuss on this site.
Comment: Your definition of "DJ/producer" is really the "performer." Just because he's not playing a so-called musical instrument doesn't change that definition.   Next, you ought to add the definition of "arranger,"  who is the person that takes the composer's melody and orchestrates it (writes parts for all the instruments, and quite probably expands the themes).  Most "classical" composers were their own arrangers, but in many cases piano compositions were arranged for orchestra -- or the common  "Variations on a them by Bob," written by Joe.
Comment: @CarlWitthoft you make some good points.  But EDM is a new art form that involves the use of "music" and the definitions are still evolving in the social community surrounding that type of production.  One term that is common is "spinning" which can also involve arranging or re-mixinging.  So the term DJ has taken on new meaning in recent times as it relates to certain forms of entertainment and "music".
Comment: Sorry Wheat, but I have to take issue with your definition of the "composer" for "older" forms of music.  I would really suggest editing that to say "traditional" because music composition as opposed to "songwriting"  is still a very substantial part of newly created music today in thriving areas such as orchestra and choral music.
Comment: @KristinaLopez, duly noted and revised. I hope you understand that I'm a classical musican myself. I was just trying to tailor my writing to the intended audience. And next time please give me a comment and suggest a revision first, and refrain from down-voting me until I've had a chance to respond to you.
Comment: Furthermore my answer is about hip-hop and contemporary pop because that is what the original questioner wants to know about. My answer is already over-long and I don't need to pad it out further by comparing and contrasting beat-making and hip-hop with classical music. I'm trying to provide a concise useful answer here, not to write a book. An answer to a question like this can't be expected to cover every kind of composition and songwriting under the sun throughout all time.
Comment: Last I checked, votes are anonymous so you might want to not jump to conclusions. ;-)  I hear you on all your points.  Good edit!
Answer: I see some very very long answers above me. But the answer to your question: "What am i?"
You are lyricist / co-songwriter.
Answer: Oh lyricist/songwriter is not something that can be given to a broad spectrum of artists some  like NF, he is a Lyricist and songwriter but then there's others that are just lyricist poetic writers. It becomes a rap when there's an audible accompanying  The Lyricist writings that's why people beatbox prior to starting their poem which is then transformed into a rap, to get your attention and express a personal point of view of life experience whether you like it or not it's that person's personal experience it is not a song by the way it's far from it it has its own special category and way of moving someone or connecting with someone so it does not diminish it by not calling it a song because I think the other would be diminishing it, it's special and it should be treated that way. and when I use the word it I'm referring to rap!
Comment: Welcome to Music.SE! Would you mind editing in some punctuation and perhaps line breaks? As it is, it's a little difficult to parse that wall of text.
Comment: Hi Troy, it is tricky to understand what you are trying to say. Please read the existing answers, and if you have something additional, please edit your post to make it clear. If what you want to say has already been said, it's simplest to just upvote their post :-)


Trouble passing PHP variables to JS using "attach"

Question: Module-noob here. I've seen plenty of threads on this topic in general but haven't found any concerning use of "attach." I'm working on a fairly simple module that applies some JavaScript to every page on the site. It was working fine, but pareview told me not to use drupal_add_js() in hook_page_build(), instructing me to use attach instead. I can't figure out how to get my PHP variables over to my JS using this method.
The JS file itself is loading, but it is not receiving the data from the PHP variables. From what I have read, I understand that the following is the way to accomplish what I am trying to do, but obviously I've got something wrong somewhere. Here is my code:
mymodule.module:
function mymodule_page_build() {

  $page['#attached']['js'] = array(
    array(
      'data' => drupal_get_path('module', 'mymodule') . '/mymodule.js',
      'options' => array(
        'preprocess' => TRUE,
        'every_page' => TRUE,
      ),
    ),
    array(
      'data' => array(
        'mymodule_status' => variable_get('mymodule_status', 0),
      ),' => 'setting',
    ),
  );
}

mymodule.js:
(function ($) {
  "use strict";
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      var moduleStatus = Drupal.settings.mymodule.mymodule_status;
      var milk = 'milk';
      $(document).ready(function () {
        // Debug:
        console.log('first');      // works
        console.log(milk);         // works
        console.log(moduleStatus); // Says mymodule is undefined
    }
  };
})(jQuery);

Thank you for any help you can offer.
Answer: Have a look on this page
For getting the value of a variable that has been set in the module you have to use like this Drupal.settings.<modulename>.<variablename>
In your module file
function mymodule_page_build() {
  $status = variable_get('mymodule_status', 0);
  drupal_add_js(array('MODULENAME' => array('mymodule_status' => $status)), 'setting');

  $page['#attached']['js'] = array(
    array(
      'data' => drupal_get_path('module', 'mymodule') . '/mymodule.js',
      'options' => array(
        'preprocess' => TRUE,
        'every_page' => TRUE,
      ),
    ),
  );
}

So in your case it should be
Drupal.settings.mymodule.mymodule_status
Comment: Hmm, it's telling me that Drupal.settings.mymodule is undefined. Any idea why that might be?
Comment: have you tried Drupal.settings.mymodule. this? not to mention please clear cache once.
Comment: Yes I tried Drupal.settings.mymodule.myvariable, as well as Drupal.settings.mymodule['myvariable'] just to be safe. Each time it said it couldn't get property 'myvariable' of undefined. So then I tested it out in the console with just Drupal.settings.mymodule, and it's just returning undefined. I also checked out the page you linked, but it doesn't seem to have instructions for using the attach method. Edit: Also, yes I've cleared the cache each time.
Comment: Then I doubt on your module, variable is not assigning to the js
Comment: It looks like it isn't recognizing Drupal.settings.mymodule at all. Am I maybe not attaching it correctly?
Comment: my answer updated. please have a look now
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/38341/discussion-between-rrr45-and-nagarjuna).
Answer: It turns out there were two problems.
First, I needed to be using function mymodule_page_build(&$page). I was originally leaving out the &$page.
Second, it turns out that to use #attached on the page itself, you have to access the 'content' property of the page.
So, instead of:
$page['#attached']['js']
It should be:
$page['content']['#attached']['js']


Getting the MavenProjectHelper in GMaven script without session.lookup

Question: I have found this example about how to attach Maven side artifact with Groovy scriptlet. I have seen that the MavenSession.lookup is deprecated, and I should use dependency injection. Lets suppose to have the following POM.xml part:
<plugin>
    <groupId>org.codehaus.gmaven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <version>1.5</version>
    <executions>
        <execution>
            <id>attach-config-artifacts</id>
            <phase>package</phase>
            <goals><goal>execute</goal></goals>
            <configuration>
                <source>
                    def helper = session.lookup("org.apache.maven.project.MavenProjectHelper")

                    new File('${basedir}').eachFileMatch( ~/.[^\.]*.cfg$/ ) { configFile ->
                        println configFile + " attached as artifact."
                        helper.attachArtifact( project, "cfg", configFile.name, configFile )
                    }
                </source>
            </configuration>
        </execution>
    </executions>
</plugin>

How can I have the MavenProjetHelper to be injected into my scriptlet? Is it possible? I do not want to create a Mojo or Groovy Mojo, I want to have it inline in the POM.
UPDATE:
In case if it is not clear: the example above works perfectly, but uses a deprecated API (MavenSession.lookup). The question is only if it possible to inject anything into a gmaven scriptlet.
Answer: You can use ContainerHelper.lookup:
def projectHelper = container.lookup("org.apache.maven.project.MavenProjectHelper")
def artifactFile = new File(project.build.directory, "artifact.zip")
projectHelper.attachArtifact(project, "zip", null, artifactFile)

Comment: At least with org.codehaus.gmaven:gmaven-plugin:1.5 it does not work: groovy.lang.MissingPropertyException: No such property: container for class: script1417691777869 . Which plugin did you use?
Comment: I used `org.codehaus.gmaven:groovy-maven-plugin:2.0` ([artifact on Central](http://search.maven.org/#artifactdetails%7Corg.codehaus.gmaven%7Cgroovy-maven-plugin%7C2.0%7Cmaven-plugin))
Answer: In this particular case, it might be simpler to just use the Build Helper plugin.
But assuming you don't want to go that route for whatever reason, with GMaven, you have to reference all objects through the properties object (as shown here).  Also, GMaven isn't maintained anymore.  I suggest this instead
<plugin>
  <groupId>org.codehaus.gmavenplus</groupId>
  <artifactId>gmavenplus-plugin</artifactId>
  <version>1.2</version>
  <executions>
    <execution>
      <id>attach</id>
      <configuration>

        </scripts>
      </configuration>
      <goals>
        <goal>execute</goal>
      </goals>
      <phase>prepare-package</phase>
    </execution>
  </executions>
  <dependencies>
    <dependency>
      <groupId>org.codehaus.groovy</groupId>
      <artifactId>groovy-all</artifactId>
      <version>2.3.3</version>
    </dependency>
  </dependencies>
</plugin>

You'll notice I changed the phase to prepare-package instead of package.  This is because goals attached to a phase happen after all the default goals have been run for that phase.  Hence attaching it to the package phase would add it to the list of artifacts after the package had already been created (which I assume was not what you wanted).
EDIT:
In the light of your edit.  This is actually a problem I hadn't considered before.  It looks like there is no way without calling through the session (you can call session.container.lookup, but session.getContainer() is deprecated too).  What you really want to do is get access to the Plexus container to get to this object and there's no good way to do that without the plugin itself wiring it up for you (and in fact this is what the Build Helper plugin does).  You can add objects to the list of things that it's bound to, but I don't think there's a Maven expression you can use to get ahold of the object you need.  GMavenPlus 1.3 will include this functionality.  I've added it to the 1.3-SNAPSHOT if you'd like to give it a shot (it's in the Codehaus repo but it might be a day before it's in Maven Central).  Here's what it'd look like
<plugin>
  <groupId>org.codehaus.gmavenplus</groupId>
  <artifactId>gmavenplus-plugin</artifactId>
  <version>1.3-SNAPSHOT</version>
  <executions>
    <execution>
      <id>attach</id>
      <configuration>

        </scripts>
      </configuration>
      <goals>
        <goal>execute</goal>
      </goals>
      <phase>prepare-package</phase>
    </execution>
  </executions>
  <dependencies>
    <dependency>
      <groupId>org.codehaus.groovy</groupId>
      <artifactId>groovy-all</artifactId>
      <version>2.3.4</version>
    </dependency>
  </dependencies>
</plugin>

If you have time, lemme know if this solves your problem.  Also, if I've totally misunderstood your question again, let me know :)
Comment: Sorry for resurrecting a dead thread.  I totally missed how old this was.  I thought it was June 28 of this year for some reason.
Comment: Apart from the interesting fact, that GMaven is dead, and you have a project called gmavenplus, I have to say, that your answer has exactly nothing to do with my question. I know, that build helper can attach artifacts, but it is not possible as far as I know to attach dynamic list of artifacts with build helper, which is done by my script. The question is simply about the possibility of dependency injection.
Comment: I mentioned build helper because I wasn't sure if you knew you using regex to match you artifacts for convenience but actually knew what they were in advance.  If that's not the case, ignore the first paragraph of my answer.

As for the second part of my answer, I must not be understanding the original question.  My understanding was that you didn't understand why your script wasn't working (I didn't try running  your example).  The example I posted should do the same thing as your example, and I've verified that it works.  If I've misunderstood your intent, please clarify and I'll try again.


Collisions in Zelle graphics.py

Question: I am trying to make my circle bounce off of my rectangle using Zelle graphics.py. Once the circle bounces off of the rectangle I wanted it to keep moving randomly. Here is my code so far, and it's working!
Also I know that each circle graphics technically can use the points of the smallest possible square that would fit around the circle to do the collision but I'm having trouble with doing that.
from graphics import *
import random

def delay(d):
    for i in range(d):
        for i in range(50):
            pass
#-------------------------------------------------
def main():

    win=GraphWin("Moving Circle",500,400)
    win.setBackground('white')
    pt= Point(100,200)
    cir=Circle(pt,30)
    #changes the color of the circle for each game
    r = random.randrange(256)
    b = random.randrange(256)
    g = random.randrange(256)
    color = color_rgb(r, g, b)
    cir.setFill(color)
    cir.draw(win)
#rectangle
    rec = Rectangle(Point(450,450), Point(275, 425))
    rec.draw(win)
    rec.setFill('black')
#-------------------------------------------------
    pt5 = Point(250,30)
    instruct1=Text(pt5, "click multiple times to start(rectangle can take multiple clicks to move)")
    instruct1.setTextColor('black')
    instruct1.draw(win)

#-------------------------------------------------
    p=cir.getCenter()
    p2=win.getMouse()

    dx=1
    dy=1

    keepGoing=True

    while keepGoing:
        d = 100
        delay(d)
        cir.move(dx,dy)
        p=cir.getCenter()
        p2=win.checkMouse()
        instruct1.setText("")

#rectanlge
        isClicked= win.checkMouse()
        if isClicked:
            rp = isClicked
            rc = rec.getCenter()
            rdx = rp.getX() - rc.getX()
            rdy = rp.getY() - rc.getY()
            rec.move(rdx,rdy)

#circle
        if((p.getX()-30)<=0.0) or ((p.getX()+30)>=500):
            dx= -dx

        if((p.getY()-30)<=0.0) or ((p.getY()+30)>=400):
            dy=-dy
        p3=win.checkMouse()

main()

Answer:
I know that each circle graphics technically can use the points of the
  smallest possible square that would fir around the circle to do the
  collision

I'm playing with an alternate idea -- we could consider a circle around the rectangle instead of a square around the circle.  The issue for me is that we not only need to detect collision, but come out with a sense of which way to move away from the other object.  It's not just True and False but rather a (dx, dy) type of result.
Obviously, a circle around the rectangle is too crude, but suppose it were lots of smaller circles making up the rectangle and we measure circle center to center distance to detect a hit:

A hit on just a central (green) rectangle circle means reverse the vertical direction of the big circle.  A hit on just the end (red) circle means reverse the horizontal direction of the big circle.  And we can detect both kinds of hits and reverse the big circle completely.
Here's my rework of your code with the above in mind -- I also fixed your multiple clicking issue and made lots of style changes:
from random import randrange
from graphics import *

WIDTH, HEIGHT = 500, 400

RADIUS = 30

def delay(d):
    for _ in range(d):
        for _ in range(50):
            pass

def distance(p1, p2):
    return ((p2.getX() - p1.getX()) ** 2 + (p2.getY() - p1.getY()) ** 2) ** 0.5

def intersects(circle, rectangle):

    dx, dy = 1, 1  # no change

    center = circle.getCenter()

    rectangle_radius = (rectangle.p2.getY() - rectangle.p1.getY()) / 2
    rectangle_width = rectangle.p2.getX() - rectangle.p1.getX()

    y = rectangle.getCenter().getY()

    for x in range(int(rectangle_radius * 2), int(rectangle_width - rectangle_radius * 2) + 1, int(rectangle_radius)):
        if distance(center, Point(rectangle.p1.getX() + x, y)) <= rectangle_radius + RADIUS:
            dy = -dy  # reverse vertical
            break

    if distance(center, Point(rectangle.p1.getX() + rectangle_radius, y)) <= rectangle_radius + RADIUS:
            dx = -dx  # reverse horizontal
    elif distance(center, Point(rectangle.p2.getX() - rectangle_radius, y)) <= rectangle_radius + RADIUS:
            dx = -dx  # reverse horizontal

    return (dx, dy)

def main():
    win = GraphWin("Moving Circle", WIDTH, HEIGHT)

    circle = Circle(Point(WIDTH / 5, HEIGHT / 2), RADIUS)

    # change the color of the circle for each game
    color = color_rgb(randrange(256), randrange(256), randrange(256))
    circle.setFill(color)

    circle.draw(win)

    # rectangle
    rectangle = Rectangle(Point(275, 425), Point(450, 450))  # off screen
    rectangle.setFill('black')
    rectangle.draw(win)

    dx, dy = 1, 1

    while True:
        delay(100)
        circle.move(dx, dy)

        # rectangle
        isClicked = win.checkMouse()

        if isClicked:
            point = isClicked
            center = rectangle.getCenter()
            rectangle.move(point.getX() - center.getX(), point.getY() - center.getY())

        # circle
        center = circle.getCenter()

        if (center.getX() - RADIUS) <= 0.0 or (center.getX() + RADIUS) >= WIDTH:
            dx = -dx

        if (center.getY() - RADIUS) <= 0.0 or (center.getY() + RADIUS) >= HEIGHT:
            dy = -dy

        # collision bounce

        x, y = intersects(circle, rectangle)
        dx *= x
        dy *= y

main()

Not perfect, but something to play around with, possibly plugging in a better intersects() implementation.
Comment: Thank you! This was very helpful!

Collisions in Zelle graphics.py


Missing commands in drush 9.3

Question: I have installed drush 9 as dependency of my drupal 8 project as explained in: http://docs.drush.org/en/master/install/
cd ${D8_PROJECT}
composer require drush/drush

Then, I have installed drush launcher as explained in: https://github.com/drush-ops/drush-launcher (ubuntu)
wget -O drush.phar https://github.com/drush-ops/drush-launcher/releases/download/0.6.0/drush.phar
chmod +x drush.phar
sudo mv drush.phar /usr/local/bin/drush

Everything is working fine except that some command are missing. Here is the list of command I have:
Drush Commandline Tool 9.3.0

Run `drush help [command]` to view command-specific help.  Run `drush topic` to read even more documentation.

 Available commands:
 _global:
   help                                 Display usage details for a command.
   list                                 List available commands.
   browse                               Display a link to a given path or open link in a browser.
   runserver (rs, serve)                Runs PHP's built-in http server for development.
   updatedb (updb)                      Apply any database updates required (as with running update.php).
   version                              Show Drush version.
   generate (gen)                       Generate boilerplate code for modules/plugins/services etc.
   drupal:directory (dd)                Return the filesystem path for modules/themes and other key folders.
   user:login (uli)                     Display a one time login link for user ID 1, or another user.
   entity:updates (entup)               Apply pending entity schema updates.
   updatedb:status (updbst)             List any pending database updates.
   config:pull (cpull)                  Export and transfer config from one environment to another.
   pm:security (sec)                    Check Drupal Composer packages for pending security updates.
 cache:
   cache:get (cg)                       Fetch a cached object and display it.
   cache:clear (cc)                     Clear a specific cache, or all Drupal caches.
   cache:set (cs)                       Cache an object expressed in JSON or var_export() format.
   cache:rebuild (cr, rebuild)          Rebuild a Drupal 8 site.
 core:
   core:status (status, st)             An overview of the environment - Drush and Drupal.
   core:init (init)                     Enrich the bash startup file with bash aliases and a smart command prompt.
   core:rsync (rsync)                   Rsync Drupal code or files to/from another server using ssh.
   core:execute (exec, execute)         Execute a shell command. Usually used with a site alias.
   core:edit (conf, config)             Edit drushrc, site alias, and Drupal settings.php files.
   core:topic (topic)                   Read detailed documentation on a given topic.
 php:
   php:eval (eval, ev)                  Evaluate arbitrary php code after bootstrapping Drupal (if available).
   php:script (scr)                     Run php a script after a full Drupal bootstrap.
 site:
   site:ssh (ssh)                       Connect to a Drupal site's server via SSH.
   site:set (use)                       Set a site alias that will persist for the current session.
   site:alias (sa)                      Show site alias details, or a list of available site aliases.
   site:alias-convert (sa-convert, sac) Convert legacy site alias files to the new yml format.
   site:install (si, sin)               Install Drupal along with modules/themes/configuration/profile.
 sql:
   sql:connect                          A string for connecting to the DB.
   sql:create                           Create a database.
   sql:drop                             Drop all tables in a given database.
   sql:cli (sqlc)                       Open a SQL command-line interface using Drupal's credentials.
   sql:query (sqlq)                     Execute a query against a database.
   sql:dump                             Exports the Drupal DB as SQL using mysqldump or equivalent.
   sql:sync                             Copy DB data from a source site to a target site. Transfers data via rsync.

Where are the user-create, role-create and other commands?
... and what is really weird, is the fact that yesterday I did use the drush locale-update command... and today this command is also gone.
Comment: This should better be asked on [GitHub](https://github.com/drush-ops/drush-launcher/issues).
Comment: According to the Docs, it is user:create for Drush 9: https://drushcommands.com/drush-9x/user/user:create/ Same for locale:update: https://drushcommands.com/drush-9x/locale/locale:update/ Do those commands work?
Comment: Under aliases it says `drush user-create`, how do you explain that?
Comment: I missed that to be honest, but OP didn't say that `drush user-create` doesn't work, only that it doesn't show up in the list of commands.  And looking at the list of commands, `user:create` might show up but not `user-create`.
Answer: I finally understood my problem.
Looking at the @M.Schmitt comment, I could find that both syntax are working: user:create and user-create. A lot of commands are not available when there is no connection to the database. When I ran drush on a multisite installation without default site, I get the small list of commands; when I ran drush @alias, I get all the commands.

Missing commands in drush 9.3