问:
How to encrypt large file using Python?
I'm trying to encrypt file that is larger than 1GB. I don't want to read it all to memory. I chose Fernet (cryptography.fernet) for this task, because it was most recommended (faster than asymetric solutions).

I generated the key. Then I've created a script to encrypt:

    key = Fernet(read_key())

    with open(source, "rb") as src, open(destination, "wb") as dest:
        for chunk in iter(lambda: src.read(4096), b""):
            encrypted = key.encrypt(chunk)
            dest.write(encrypted)
```
<p>and for decryption:</p>
<pre class="lang-py prettyprint-override"><code>    key = Fernet(read_key())

    with open(source, "rb") as src, open(destination, "wb") as dest:
        for chunk in iter(lambda: src.read(4096), b""):
            decrypted = key.decrypt(chunk)
            dest.write(decrypted)
</code>```

Encryption works - no surprise, but decryption is not.
Firstly I thought that it might work, but it's not. I guess chunk size increases when encrypted, and then when I'm reading 4096 bytes, it's not a whole encrypted chunk. I've got an error trying to decrypt:

```<code>Traceback (most recent call last):
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/fernet.py", line 119, in _verify_signature
    h.verify(data[-32:])
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/hazmat/primitives/hmac.py", line 74, in verify
    ctx.verify(signature)
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/hazmat/backends/openssl/hmac.py", line 75, in verify
    raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/redacted/path/main.py", line 63, in <module>
    decrypted = key.decrypt(chunk)
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/fernet.py", line 80, in decrypt
    return self._decrypt_data(data, timestamp, time_info)
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/fernet.py", line 137, in _decrypt_data
    self._verify_signature(data)
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/fernet.py", line 121, in _verify_signature
    raise InvalidToken
cryptography.fernet.InvalidToken
</code>```

Is there's a way to solve this? Maybe there's a better (simpler) approach with different solution than fernet?

答:
I just ran into the same issue - I feel your pain brother.

There are some issues with Fernet that make it incompatible with your approach:

Fernet spits out urlsafe_base64 encoded data. This means that for every 3 bytes of unencrypted data consumed, Fernet will spit out 4 bytes of encrypted data.

This prevents you from using the same "chunk size" when encrypting and decrypting, as the decryption chunk size must necessarily be bigger. Unfortunately, treating the data with urlsafe_b64decode/urlsafe_b64encode also doesn't do the trick because:

Fernet seems to add some sort of digest/checksum/metadata somewhere in the encrypted data.

There probably is a straightforward way to work out how big this digest is and adjusting the decryption chunk size to accommodate this - but I wanted to avoid doing stuff with "magic constants" as that felt quite gross.

The solution I settled on actually ended up being quite elegant. It works as follows:

Encryption:

Read n bytes of data (raw_chunk)

Encrypt n bytes with Fernet to create an m bytes chunk (enc_chunk).

Use len(enc_chunk).to_bytes(4, "big") to write the size of the encrypted chunk to the file

Write the encrypted chunk to the file

Break when I read a b""

Decryption:

Read 4 bytes of data (size)

Break if the data is a b""

Convert those 4 bytes into an integer using int.from_bytes(size, "big") (num_bytes)

Read num_bytes of encrypted data

Decrypt this data with Fernet with no problems

Title: How to encrypt large file using Python?

Body:
I'm trying to encrypt file that is larger than 1GB. I don't want to read it all to memory. I chose Fernet (cryptography.fernet) for this task, because it was most recommended (faster than asymetric solutions).

I generated the key. Then I've created a script to encrypt:

    key = Fernet(read_key())

    with open(source, "rb") as src, open(destination, "wb") as dest:
        for chunk in iter(lambda: src.read(4096), b""):
            encrypted = key.encrypt(chunk)
            dest.write(encrypted)

and for decryption:

    key = Fernet(read_key())

    with open(source, "rb") as src, open(destination, "wb") as dest:
        for chunk in iter(lambda: src.read(4096), b""):
            decrypted = key.decrypt(chunk)
            dest.write(decrypted)

Encryption works - no surprise, but decryption is not.
Firstly I thought that it might work, but it's not. I guess chunk size increases when encrypted, and then when I'm reading 4096 bytes, it's not a whole encrypted chunk. I've got an error trying to decrypt:

Traceback (most recent call last):
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/fernet.py", line 119, in _verify_signature
    h.verify(data[-32:])
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/hazmat/primitives/hmac.py", line 74, in verify
    ctx.verify(signature)
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/hazmat/backends/openssl/hmac.py", line 75, in verify
    raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/redacted/path/main.py", line 63, in <module>
    decrypted = key.decrypt(chunk)
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/fernet.py", line 80, in decrypt
    return self._decrypt_data(data, timestamp, time_info)
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/fernet.py", line 137, in _decrypt_data
    self._verify_signature(data)
  File "/redacted/path/venv/lib/python3.7/site-packages/cryptography/fernet.py", line 121, in _verify_signature
    raise InvalidToken
cryptography.fernet.InvalidToken

Is there's a way to solve this? Maybe there's a better (simpler) approach with different solution than fernet?


来源: stackexchange

问:
Why am I getting a type mismatch error in this code?
The Firebase UserCredential interface has a field called user that is of type User. I have a method that accepts a parameter of type User, but when I call the method, I get the following error:

The argument type 'User?' can't be assigned to the parameter type 'User'.

I am fetching my UserCredential by awaiting signInAnonymously() which returns a Promise<UserCredential>, so I'm not sure how userCredential.user is being typed as User?.

Here is my code:

```<code>loginAno() async {
    UserCredential userCredential =
        await FirebaseAuth.instance.signInAnonymously();
    onSignInAno(userCredential.user); // Problem Is Here
}
</code>```

Why am I getting this error? userCredential.user is a User, not a User?.

答:
The userCredential.user field may be null, so it is declared as User?.

Since your onSignInAno expects a User, you should only call it when userCredential.user is not null. So:

```<code>loginAno() async {
    UserCredential userCredential =
        await FirebaseAuth.instance.signInAnonymously();
    if (userCredential.user !== null) {
        onSignInAno(userCredential.user);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The Firebase UserCredential interface has a field called user that is of type User. I have a method that accepts a parameter of type User, but when I call the method, I get the following error:

The argument type 'User?' can't be assigned to the parameter type 'User'.

I am fetching my UserCredential by awaiting signInAnonymously() which returns a Promise<UserCredential>, so I'm not sure how userCredential.user is being typed as User?.

Here is my code:

loginAno() async {
    UserCredential userCredential =
        await FirebaseAuth.instance.signInAnonymously();
    onSignInAno(userCredential.user); // Problem Is Here
}

Why am I getting this error? userCredential.user is a User, not a User?.

Body:
The userCredential.user field may be null, so it is declared as User?.

Since your onSignInAno expects a User, you should only call it when userCredential.user is not null. So:

loginAno() async {
    UserCredential userCredential =
        await FirebaseAuth.instance.signInAnonymously();
    if (userCredential.user !== null) {
        onSignInAno(userCredential.user);
    }
}


问:
Python Pandas: How to find element in a column with a matching string object of other column
I have this string object:

```<code>code = '1002'
</code>```

And i also have the following Pandas Data Frame:

```<code>pd.DataFrame({'Code':['1001','1002','1003','1004'],
              'Place':['Chile','Peru','Colombia','Argentina']})
</code>```

What i need is to match the code i hace as a stirng with the column 'Code' and get the element in the same row from the column 'Place'.

答:
You can use set_index first, if you want to get the actual value:

```<code>>>> df.set_index('Code').loc['1002', 'Place']
'Peru'
</code>```

Body:
I have this string object:

code = '1002'

And i also have the following Pandas Data Frame:

pd.DataFrame({'Code':['1001','1002','1003','1004'],
              'Place':['Chile','Peru','Colombia','Argentina']})

What i need is to match the code i hace as a stirng with the column 'Code' and get the element in the same row from the column 'Place'.

Body:
You can use set_index first, if you want to get the actual value:

>>> df.set_index('Code').loc['1002', 'Place']
'Peru'


问:
Woocommerce CSS changes not applying to site
I tried to change some design things in my wordpress page in css/woocommerce.css.
When I inspect the element I want to hide, chrome says that the class is in that file, but when I change the mentioned class it does not change anything in the frontend, not on the website and not in the chrome inspector.
I cleared all my caches and if I change other CSS files the changes apply just as they should. Just not on woocommerce.css....

Any ideas?

Code of woocommerce.css:

```<code>.blockUI.blockOverlay {
        position: relative;
        display: none !important;
    }
    .blockUI.blockOverlay:before,
    .loader:before {
        /*height: 1em;
        width: 1em;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-left: -.5em;
        margin-top: -.5em;*/
        display: none !important;
        /*content: "";
        animation: spin 1s ease-in-out infinite;
        background: url(https://www.afreenuts.com/wp-content/uploads/nuss50.gif) center center;
        background-size: cover;
        line-height: 1;
        text-align: center;
        font-size: 2em;
        color: rgba(0, 0, 0, .75);*/
    }
    .woocommerce .blockUI.blockOverlay:before, .woocommerce .loader:before, .woocommerce-page .blockUI.blockOverlay:before, .woocommerce-page .loader:before {
        display: none !important;
    }
</code>```

Code on Google inspector:

Click here
As you can see the display:none; on admin.css applies, but my change son woocommerce.css don't.

答:
For anyone else experiencing this problem: Check that your Hosting Company isn't automatically caching your website.

For instance: GoDaddy's Managed Wordpress automatically cache's WordPress sites to make them faster for users.

Thankfully they make clearing your cache quick and easy. Follow the instructions here: https://www.godaddy.com/help/clear-your-cache-12444

This is what my very similar problem ended up being.

Body:
I tried to change some design things in my wordpress page in css/woocommerce.css.
When I inspect the element I want to hide, chrome says that the class is in that file, but when I change the mentioned class it does not change anything in the frontend, not on the website and not in the chrome inspector.
I cleared all my caches and if I change other CSS files the changes apply just as they should. Just not on woocommerce.css....

Any ideas?

Code of woocommerce.css:

.blockUI.blockOverlay {
        position: relative;
        display: none !important;
    }
    .blockUI.blockOverlay:before,
    .loader:before {
        /*height: 1em;
        width: 1em;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-left: -.5em;
        margin-top: -.5em;*/
        display: none !important;
        /*content: "";
        animation: spin 1s ease-in-out infinite;
        background: url(https://www.afreenuts.com/wp-content/uploads/nuss50.gif) center center;
        background-size: cover;
        line-height: 1;
        text-align: center;
        font-size: 2em;
        color: rgba(0, 0, 0, .75);*/
    }
    .woocommerce .blockUI.blockOverlay:before, .woocommerce .loader:before, .woocommerce-page .blockUI.blockOverlay:before, .woocommerce-page .loader:before {
        display: none !important;
    }

Code on Google inspector:

Click here
As you can see the display:none; on admin.css applies, but my change son woocommerce.css don't.


问:
assign cluster membership to new data using kmodes
Looking at this code from here:

```<code>import numpy as np
from kmodes.kmodes import KModes

# random categorical data
data = np.random.choice(20, (100, 10))

km = KModes(n_clusters=4, init='Huang', n_init=5, verbose=1)
clusters = km.fit_predict(data)

# Print the cluster centroids
print(km.cluster_centroids_)
</code>```

Does anyone happen to know how to save the "clustering model" and apply it to new data? Or in other words cluster previously unseen data? Thanks.

答:
You can use pickle for this task.

```<code>import pickle

with open('cluster_model.pickle', 'wb') as n:
    pickle.dump(km, n)
</code>```

When you want to use it on new data, simply:

```<code>with open('cluster_model.pickle', 'rb') as f:
    km = pickle.load(f)

# If your new data is called "new_data", you can:
new_clusters = km.predict(new_data)
</code>```

Body:
Looking at this code from here:

import numpy as np
from kmodes.kmodes import KModes

# random categorical data
data = np.random.choice(20, (100, 10))

km = KModes(n_clusters=4, init='Huang', n_init=5, verbose=1)
clusters = km.fit_predict(data)

# Print the cluster centroids
print(km.cluster_centroids_)

Does anyone happen to know how to save the "clustering model" and apply it to new data? Or in other words cluster previously unseen data? Thanks.

Body:
You can use pickle for this task.

import pickle

with open('cluster_model.pickle', 'wb') as n:
    pickle.dump(km, n)

When you want to use it on new data, simply:

with open('cluster_model.pickle', 'rb') as f:
    km = pickle.load(f)

# If your new data is called "new_data", you can:
new_clusters = km.predict(new_data)


问:
Best way to safely store Python tuple of strings and integers in memcached?
So I have a webapp where I want to store current rankings of posts based on an algo every minute. To render the updated posts, I would like to avoid the db and get the data (e.g. post title, author, rank, etc.) from memcached (faster, right?).

One idea is (I'm using Django btw) for the view to convert a serialized string from memcached back to python (using pickle) and then rendering a template displaying the posts in the correct order. However, it may be unsafe because the user-submitted data (post title, etc.) may contain characters that may be parsed in an undesirable way.

1) Is the best solution to just clean all data when these objects are saved or is there another solution?

2) If cleaning the data is an option, what characters should be excluded in the various fields of my Post model?

3) Does pickle.dump require a file to write to, or can I just get a string as output?

Thanks guys.

An example of what needs to be stored:

```<code>((post.id, post.title, post.upvotes, post.author.username), (,,,)... )
</code>```

(say 25 posts repeating like this)

答:
Why not just let django.core.cache take care of that for you? I'm doing this from a django project that has memcached hooked up as the cache backend:

```<code>$ python manage.py shell
In [1]: from django.core.cache import cache

In [2]: cache.set('woot', (3, 'blah', 590))

In [3]: cache.get('woot')
Out[3]: (3, 'blah', 590)
</code>```

It works for any python object that can be pickled.

Also, why not just cache the output, with HTML and everything? Django provides good per-view caching and template fragment caching.

ContentLicense: CC BY-SA 3.0

Body:
So I have a webapp where I want to store current rankings of posts based on an algo every minute. To render the updated posts, I would like to avoid the db and get the data (e.g. post title, author, rank, etc.) from memcached (faster, right?).

One idea is (I'm using Django btw) for the view to convert a serialized string from memcached back to python (using pickle) and then rendering a template displaying the posts in the correct order. However, it may be unsafe because the user-submitted data (post title, etc.) may contain characters that may be parsed in an undesirable way.

1) Is the best solution to just clean all data when these objects are saved or is there another solution?

2) If cleaning the data is an option, what characters should be excluded in the various fields of my Post model?

3) Does pickle.dump require a file to write to, or can I just get a string as output?

Thanks guys.

An example of what needs to be stored:

((post.id, post.title, post.upvotes, post.author.username), (,,,)... )

(say 25 posts repeating like this)

Body:
Why not just let django.core.cache take care of that for you? I'm doing this from a django project that has memcached hooked up as the cache backend:

$ python manage.py shell
In [1]: from django.core.cache import cache

In [2]: cache.set('woot', (3, 'blah', 590))

In [3]: cache.get('woot')
Out[3]: (3, 'blah', 590)

It works for any python object that can be pickled.

Also, why not just cache the output, with HTML and everything? Django provides good per-view caching and template fragment caching.


问:
Efficiently store an N-dimensional array of mostly zeros in Matlab
I implemented a finite differences algorithm to solve a PDE.

The grid is a structured 2D domain of size [Nx, Nz], solved Nt times.

I pre-allocate the object containing all solutions:

```<code>sol = zeros(Nx, Nz, Nt, 'single') ;
</code>```

This becomes very easily too large and I get a 'out of memory' error.
Unfortunately sparse doesn't work for N-dimensional arrays.

For the sake of the question it's not important to know the values, it goes without saying that the RAM usage grows exponentially with decreasing the grid spacing and increasing the simulation time.

I am aware that I do not need to store each time instant for the purpose of the advancement of the solution. It would be sufficient to just store the previous two time steps. However, for post-processing reasons I need to access the solution at all time-steps (or at least at a submultiple of the total number).It might help to specify that, even after the solution, the grid remains predominantly populated by zeros.

Am I fighting a lost battle or is there a more efficient way to proceed (other type of objects, vectorization...)?

Thank you.

答:
You could store the array in sparse, linear form; that is, a column vector with length equal to the product of dimensions:

```<code>sol = sparse([], [], [], Nx*Nz*Nt, 1); % sparse column vector containing zeros
</code>```

Then, instead of indexing normally,

```<code>sol(x, z, t),
</code>```

you need to translate the indices x, z, t into the corresponding linear index:

For scalar indices you use

```<code>sol(x + Nx*(z-1) + Nx*Nz*(t-1))
</code>```

You can define a helper function for convenience:

```<code>ind = @(sol, x, y, t) sol(x + Nx*(z-1) + Nx*Nz*(t-1))
</code>```

so the indexing becomes more readable:

```<code>ind(sol, x, z, t)
</code>```

For general (array) indices you need to reshape the indices along different dimensions so that implicit expansion produces the appropriate linear index:

```<code>sol(reshape(x,[],1,1) + Nx*(reshape(z,1,[],1)-1) + Nx*Nz*(reshape(t,1,1,[])-1))
</code>```

which of course could also be encapsulated into a function.

Check that the conversion to linear indexing works (general case, using non-sparse array to compare with normal indexing):

```<code>Nx = 15; Nz = 18; Nt = 11;
sol = randi(9, Nx, Nz, Nt);
x = [5 6; 7 8]; z = 7; t = [4 9 1];
isequal(sol(x, z, t), ...
    sol(reshape(x,[],1,1) + Nx*(reshape(z,1,[],1)-1) + Nx*Nz*(reshape(t,1,1,[])-1)))
</code>```

gives

```<code>ans =
  logical
   1
</code>```

Body:
I implemented a finite differences algorithm to solve a PDE.

The grid is a structured 2D domain of size [Nx, Nz], solved Nt times.

I pre-allocate the object containing all solutions:

sol = zeros(Nx, Nz, Nt, 'single') ;

This becomes very easily too large and I get a 'out of memory' error.
Unfortunately sparse doesn't work for N-dimensional arrays.

For the sake of the question it's not important to know the values, it goes without saying that the RAM usage grows exponentially with decreasing the grid spacing and increasing the simulation time.

I am aware that I do not need to store each time instant for the purpose of the advancement of the solution. It would be sufficient to just store the previous two time steps. However, for post-processing reasons I need to access the solution at all time-steps (or at least at a submultiple of the total number).It might help to specify that, even after the solution, the grid remains predominantly populated by zeros.

Am I fighting a lost battle or is there a more efficient way to proceed (other type of objects, vectorization...)?

Thank you.

Body:
You could store the array in sparse, linear form; that is, a column vector with length equal to the product of dimensions:

sol = sparse([], [], [], Nx*Nz*Nt, 1); % sparse column vector containing zeros

Then, instead of indexing normally,

sol(x, z, t),

you need to translate the indices x, z, t into the corresponding linear index:

For scalar indices you use

sol(x + Nx*(z-1) + Nx*Nz*(t-1))

You can define a helper function for convenience:

ind = @(sol, x, y, t) sol(x + Nx*(z-1) + Nx*Nz*(t-1))

so the indexing becomes more readable:

ind(sol, x, z, t)

For general (array) indices you need to reshape the indices along different dimensions so that implicit expansion produces the appropriate linear index:

sol(reshape(x,[],1,1) + Nx*(reshape(z,1,[],1)-1) + Nx*Nz*(reshape(t,1,1,[])-1))

which of course could also be encapsulated into a function.

Check that the conversion to linear indexing works (general case, using non-sparse array to compare with normal indexing):

Nx = 15; Nz = 18; Nt = 11;
sol = randi(9, Nx, Nz, Nt);
x = [5 6; 7 8]; z = 7; t = [4 9 1];
isequal(sol(x, z, t), ...
    sol(reshape(x,[],1,1) + Nx*(reshape(z,1,[],1)-1) + Nx*Nz*(reshape(t,1,1,[])-1)))

gives

ans =
  logical
   1


问:
When can I delete old pg_wal files and old archive files from postgres database, i have two different directory for both of them
i have postgres 12 database with master slave configuration. the space of backup is near by 70%, i want to create some space for smooth functioning of DB.
i  can moved backup of db in different location, but it is not sufficient. there is lots of space taken by pg_wal files and archive files.
i have wo different directories for both of them.
can i delete some of them?
last pg_wal file is 0000000100000004000000D9 on date of 07-10-2021 and latest on is 0000000100000007000000D8 on date of 10-02-2022.
same as last archive file is 0000000100000004000000DE on date of 01-05-2021 and latest is 0000000100000007000000D7 on date of 10-02-2022.
can i delete some of them like til previous month.</p>

答:
Files in pg_wal are deleted by the system, you should figure out why it is not doing so (for 4 months!)

Files in the archive can be deleted when they are no longer needed.  That is a matter of your policy.  Do you still need them for PITR? I don't know, you need to tell us.  Does the replica still need them to get caught up? I assume it is not that far behind, or you would have said something to start with.  Maybe you have two replicas and one got forgotten about.  Maybe you don't care about PITR and are only interested in streaming for the replica, and your archive isn't needed at all and was set up by mistake.

By the way, WAL files usually compress very well. xz will often shrink them by >90%.  So if you need more time to think about what your policy is, you can compress the archived files to free up some space while you do so.  Don't compress the ones in pg_wal though, just the archive.


问:
Creating a JSON response using Django and Python
I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.

This is the server-side script:

```<code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];

/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$arrayToJs[1] = $validateError;

if($validateValue =="Testuser"){  // Validate??
    $arrayToJs[2] = "true";       // RETURN TRUE
    echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';  // RETURN ARRAY WITH success
}
else{
    for($x=0;$x<1000000;$x++){
        if($x == 990000){
            $arrayToJs[2] = "false";
            echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';   // RETURNS ARRAY WITH ERROR.
        }
    }
}
</code>```

And this is the converted code

```<code>def validate_user(request):
    if request.method == 'POST':
        vld_value = request.POST.get('validateValue')
        vld_id = request.POST.get('validateId')
        vld_error = request.POST.get('validateError')

        array_to_js = [vld_id, vld_error, False]

        if vld_value == "TestUser":
            array_to_js[2] = True
            x = simplejson.dumps(array_to_js)
            return HttpResponse(x)
        else:
            array_to_js[2] = False
            x = simplejson.dumps(array_to_js)
            error = 'Error'
            return render_to_response('index.html',{'error':error},context_instance=RequestContext(request))
    return render_to_response('index.html',context_instance=RequestContext(request))
</code>```

I'm using simplejson to encode the Python list (so it will return a JSON array). I couldn't figure out the problem yet. But I think that I did something wrong about the 'echo'.

答:
This way the json contents can be downloaded as a file with a specific filename.</p>
```<code>import json
from django.http import HttpResponse

def download_json(request):
    data = {'some': 'information'}

    # serialize data obj as a JSON stream
    data = json.dumps(data)
    response = HttpResponse(data, content_type='application/json charset=utf-8')

    # add filename to response
    response['Content-Disposition'] = 'attachment; filename="filename.json"'
    return response
</code>```

Body:
I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.

This is the server-side script:

/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];

/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$arrayToJs[1] = $validateError;

if($validateValue =="Testuser"){  // Validate??
    $arrayToJs[2] = "true";       // RETURN TRUE
    echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';  // RETURN ARRAY WITH success
}
else{
    for($x=0;$x<1000000;$x++){
        if($x == 990000){
            $arrayToJs[2] = "false";
            echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';   // RETURNS ARRAY WITH ERROR.
        }
    }
}

And this is the converted code

def validate_user(request):
    if request.method == 'POST':
        vld_value = request.POST.get('validateValue')
        vld_id = request.POST.get('validateId')
        vld_error = request.POST.get('validateError')

        array_to_js = [vld_id, vld_error, False]

        if vld_value == "TestUser":
            array_to_js[2] = True
            x = simplejson.dumps(array_to_js)
            return HttpResponse(x)
        else:
            array_to_js[2] = False
            x = simplejson.dumps(array_to_js)
            error = 'Error'
            return render_to_response('index.html',{'error':error},context_instance=RequestContext(request))
    return render_to_response('index.html',context_instance=RequestContext(request))

I'm using simplejson to encode the Python list (so it will return a JSON array). I couldn't figure out the problem yet. But I think that I did something wrong about the 'echo'.

Body:
This way the json contents can be downloaded as a file with a specific filename.

import json
from django.http import HttpResponse

def download_json(request):
    data = {'some': 'information'}

    # serialize data obj as a JSON stream
    data = json.dumps(data)
    response = HttpResponse(data, content_type='application/json charset=utf-8')

    # add filename to response
    response['Content-Disposition'] = 'attachment; filename="filename.json"'
    return response


问:
Use IntersectionObserver To Trigger Event AFTER Element Completely Passes Threshold
I have a few IntersectionObserver's set up. observer toggles new boxes to be made as the user scrolls down the page. lastBoxObserver loads new boxes as this continuous scrolling happens.

What I would like to do is change the color of a box once it leaves the threshold set in the first observer (observer - whose threshold is set to 1). So, once box 12 enters the viewport, it passes through the observer, and once it has completely passed outside of the threshold for this observer and box 13 enters the observer, box 12's background changes from green to orange, perhaps.

Is there a way to make this happen? Maybe by adding an additional observer, or adding code to observer? Any help is greatly appreciated.

Codepen: https://codepen.io/jon424/pen/NWwReEJ

JavaScript

 const boxes = document.querySelectorAll(".box");
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          entry.target.classList.toggle("show", entry.isIntersecting);
          if (entry.isIntersecting) observer.unobserve(entry.target);
        });
      },
      {
        threshold: 1,
      }
    );

    const lastBoxObserver = new IntersectionObserver((entries) => {
      const lastBox = entries[0];
      if (!lastBox.isIntersecting) return;
      loadNewBoxes();
      lastBoxObserver.unobserve(lastBox.target);
      lastBoxObserver.observe(document.querySelector(".box:last-child"));
    }, {});

    lastBoxObserver.observe(document.querySelector(".box:last-child"));

    boxes.forEach((box) => {
      observer.observe(box);
    });

    const boxContainer = document.querySelector(".container");

    function loadNewBoxes() {
      for (let i = 0; i < 1000; i++) {
        const box = document.createElement("div");
        box.textContent = `${i + 1}`;
        box.classList.add("box");
        observer.observe(box);
        boxContainer.appendChild(box);
      }
    }

```
<p><strong>HTML</strong></p>
<pre class="lang-html prettyprint-override"><code>   <div class="container">
      <div class="box">0</div>
    </div>
</code>```

CSS

 .container {
      display: flex;
      flex-direction: column;
      gap: 1rem;
      align-items: flex-start;
    }

    .box {
      background: green;
      color: white;
      font-size: 4rem;
      text-align: center;
      margin: auto;
      height: 100px;
      width: 100px;
      border: 1px solid black;
      border-radius: 0.25rem;
      padding: 0.5rem;
      transform: translateX(100px);
      opacity: 0;
      transition: 150ms;
    }

    .box.show {
      transform: translateX(0);
      opacity: 1;
    }

    .box.show.more {
      background-color: orange;
    }
```

答:
```<code><!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title></title>

    </head>

    <body>
        <style>
            .container {
                  display: flex;
                  flex-direction: column;
                  gap: 1rem;
                  align-items: flex-start;
                }

                .box {
                  background: green;
                  color: white;
                  font-size: 4rem;
                  text-align: center;
                  margin: auto;
                  height: 100px;
                  width: 100px;
                  border: 1px solid black;
                  border-radius: 0.25rem;
                  padding: 0.5rem;
                  opacity: 0;

                }

                .box.show {
                  opacity: 1;
                }

                .box.show.more {
                  background-color: orange;
                }

                .mytest{
                    border:solid 10px #000;
                    background-color: orange;
                }
        </style>
        <div class="container">
            <div class="box">0</div>
            <div class="sentinel"></div>
        </div>

  <script>
   /* https://stackoverflow.com/questions/70994897/use-intersectionobserver-to-trigger-event-after-element-completely-passes-thresh/71054028#71054028 */
   const observer = new IntersectionObserver(

     (entries) => {
       entries.forEach((entry) => {

         if (entry.isIntersecting) {
            entry.target.classList.add("show");
        }
         if (entry.boundingClientRect.top < entry.rootBounds.top) {
           /* entry is above viewport */
           entry.target.classList.add("mytest");
           observer.unobserve(entry.target);
         }

       });

     },
     {
       threshold: 0, /* top is 200 below top of viewport - something for the box to scroll into*/
       rootMargin: "-200px 0px 0px 0px"
     }
   );

   /* last div sentinel indicates last box */
   const mysentinel = new IntersectionObserver((entries) => {
     var entry = entries[0];
     if (entry.isIntersecting) {
       loadNewBoxes();
     }
   },{
        threshold: 0
   });

      const boxContainer = document.querySelector(".container");
      const sentinel = document.querySelector(".sentinel");
      /* setup - create extra boxes, sentinel is last after boxes */

      loadNewBoxes();

      mysentinel.observe(sentinel);

   function loadNewBoxes() {

     for (let i = 0; i < 10; i++) {
       const box = document.createElement("div");
       box.textContent = `${i + 1}`;
       box.classList.add("box");
       box.classList.add("show");
       observer.observe(box);
       boxContainer.appendChild(box);
     }

     boxContainer.appendChild(sentinel);

   }

        </script>
    </body>

</html>
</code>```

IntersectionObserver callback is async, if you scroll fast enough then some boxes will be missed. I've simplified your code. If the box/observed target is above the root top then I add a class and unobserve it. If the box is transitioning I add a class to show the box. I use sentinel to indicate the last box and to add more boxes when the sentinel hits the viewport.

Body:
I have a few IntersectionObserver's set up. observer toggles new boxes to be made as the user scrolls down the page. lastBoxObserver loads new boxes as this continuous scrolling happens.

What I would like to do is change the color of a box once it leaves the threshold set in the first observer (observer - whose threshold is set to 1). So, once box 12 enters the viewport, it passes through the observer, and once it has completely passed outside of the threshold for this observer and box 13 enters the observer, box 12's background changes from green to orange, perhaps.

Is there a way to make this happen? Maybe by adding an additional observer, or adding code to observer? Any help is greatly appreciated.

Codepen: https://codepen.io/jon424/pen/NWwReEJ

JavaScript

 const boxes = document.querySelectorAll(".box");
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          entry.target.classList.toggle("show", entry.isIntersecting);
          if (entry.isIntersecting) observer.unobserve(entry.target);
        });
      },
      {
        threshold: 1,
      }
    );

    const lastBoxObserver = new IntersectionObserver((entries) => {
      const lastBox = entries[0];
      if (!lastBox.isIntersecting) return;
      loadNewBoxes();
      lastBoxObserver.unobserve(lastBox.target);
      lastBoxObserver.observe(document.querySelector(".box:last-child"));
    }, {});

    lastBoxObserver.observe(document.querySelector(".box:last-child"));

    boxes.forEach((box) => {
      observer.observe(box);
    });

    const boxContainer = document.querySelector(".container");

    function loadNewBoxes() {
      for (let i = 0; i < 1000; i++) {
        const box = document.createElement("div");
        box.textContent = `${i + 1}`;
        box.classList.add("box");
        observer.observe(box);
        boxContainer.appendChild(box);
      }
    }

HTML

0

CSS

 .container {
      display: flex;
      flex-direction: column;
      gap: 1rem;
      align-items: flex-start;
    }

    .box {
      background: green;
      color: white;
      font-size: 4rem;
      text-align: center;
      margin: auto;
      height: 100px;
      width: 100px;
      border: 1px solid black;
      border-radius: 0.25rem;
      padding: 0.5rem;
      transform: translateX(100px);
      opacity: 0;
      transition: 150ms;
    }

    .box.show {
      transform: translateX(0);
      opacity: 1;
    }

    .box.show.more {
      background-color: orange;
    }

Body:
<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title></title>

    </head>

    <body>
        <style>
            .container {
                  display: flex;
                  flex-direction: column;
                  gap: 1rem;
                  align-items: flex-start;
                }

                .box {
                  background: green;
                  color: white;
                  font-size: 4rem;
                  text-align: center;
                  margin: auto;
                  height: 100px;
                  width: 100px;
                  border: 1px solid black;
                  border-radius: 0.25rem;
                  padding: 0.5rem;
                  opacity: 0;

                }

                .box.show {
                  opacity: 1;
                }

                .box.show.more {
                  background-color: orange;
                }

                .mytest{
                    border:solid 10px #000;
                    background-color: orange;
                }
        </style>
        <div class="container">
            <div class="box">0</div>
            <div class="sentinel"></div>
        </div>

  <script>
   /* https://stackoverflow.com/questions/70994897/use-intersectionobserver-to-trigger-event-after-element-completely-passes-thresh/71054028#71054028 */
   const observer = new IntersectionObserver(

     (entries) => {
       entries.forEach((entry) => {

         if (entry.isIntersecting) {
            entry.target.classList.add("show");
        }
         if (entry.boundingClientRect.top < entry.rootBounds.top) {
           /* entry is above viewport */
           entry.target.classList.add("mytest");
           observer.unobserve(entry.target);
         }

       });

     },
     {
       threshold: 0, /* top is 200 below top of viewport - something for the box to scroll into*/
       rootMargin: "-200px 0px 0px 0px"
     }
   );

   /* last div sentinel indicates last box */
   const mysentinel = new IntersectionObserver((entries) => {
     var entry = entries[0];
     if (entry.isIntersecting) {
       loadNewBoxes();
     }
   },{
        threshold: 0
   });

      const boxContainer = document.querySelector(".container");
      const sentinel = document.querySelector(".sentinel");
      /* setup - create extra boxes, sentinel is last after boxes */

      loadNewBoxes();

      mysentinel.observe(sentinel);

   function loadNewBoxes() {

     for (let i = 0; i < 10; i++) {
       const box = document.createElement("div");
       box.textContent = `${i + 1}`;
       box.classList.add("box");
       box.classList.add("show");
       observer.observe(box);
       boxContainer.appendChild(box);
     }

     boxContainer.appendChild(sentinel);

   }

        </script>
    </body>

</html>

IntersectionObserver callback is async, if you scroll fast enough then some boxes will be missed. I've simplified your code. If the box/observed target is above the root top then I add a class and unobserve it. If the box is transitioning I add a class to show the box. I use sentinel to indicate the last box and to add more boxes when the sentinel hits the viewport.


问:
Why does integer division round down in many scripting languages?
In the languages I have tested, - (x div y ) is not equal to -x div y; I have tested // in Python, / in Ruby, div in Perl 6; C has a similar behavior.

That behavior is usually according to spec, since div is usually defined as the rounding down of the result of the division, however it does not make a lot of sense from the arithmetic point of view, since it makes div behave in a different way depending on the sign, and it causes confusion such as this post on how it is done in Python.

Is there some specific rationale behind this design decision, or is just div defined that way from scratch? Apparently Guido van Rossum  uses a coherency argument in a blog post that explains how it is done in Python, but you can have coherency also if you choose to round up.

(Inspired by this question by PMurias in the #perl6 IRC channel)

答:
This answer addresses a sub-part of the question that the other (excellent) answers didn't explicitly address.  You noted:

you can have coherency also if you choose to round up.

Other answers addressed the choice between rounding down (towards -∞) and truncating (rounding towards 0) but didn't compare rounding up (towards ∞).

  (The accepted answer touches on performance reasons to prefer rounding down on a two's-complement machine, which would also apply in comparison to rounding up.  But there are more important semantic reasons to avoid rounding up.)

This answer directly addresses why rounding up is not a great solution.

Rounding up breaks elementary-school expectations

Building on an example from a previous answer's, it's common to informally say something like this:

If I evenly divide fourteen marbles among three people, each person gets four marbles and there are two marbles left over.

Indeed, this is how many students are first taught division (before being introduced to fractions/decimals).  A student might write 14 ÷ 3 = 4 remainder 2.  Since this is introduced so early, we'd really like our div operator to preserve this property.

Or, put a bit more formally, of the three properties discussed in the top-voted answer, the first one ((a div b) × b + (a mod b) = a) is by far the most important.

But rounding up breaks this property.  If div rounds up, then 14 div 3 returns 5.  This means that the equation above simplifies to 15 + (13 mod 4) = 13 – and that's not true for any definition of mod.  Similarly, the less-formal/elementary-school approach is also out of luck – or at least requires introducing negative marbles: "Each person gets 5 marbles and there are negative one marbles left over".

 (Rounding to the nearest integer also breaks the property when, as in the example above, that means rounding up.)

Thus, if we want to maintain elementary expectations, we cannot round up.  And with rounding up off the table, the coherency argument that you linked in the question is sufficient to justify rounding down.


问:
What has a larger big-O: O(m^2n) or O(n^2)
Given that m <= n, is O(n^2) in O(m^2n)? I know that O(mn) is in O(n^2) but I do not know what happens when you add the extra term</p>

答:
n^2 vs (m^2)n

Even as m grows with n, and no matter the difference between m and n, n^2 will always be larger so (m^2)n would always be contained within n^2.


问:
Accessing networked computers using C#
I have built an application with a tree view showing the file structure of the server the application is running on. I want to be able to include in the tree the file structure of machines connected through the network.

Something like this but with multiple workgroups.

The only example I have found which is similar so far is this example which simply lists machines connected through the network, whereas I want access to the folders within them.

Thanks in advance for any help

答:
This will get an array of directory names (String[]) assuming the process is running as an account with access to the share:

```<code>var folders = Directory.GetDirectories(@"\\HOSTNAME\ShareName\");
</code>```

You can use a similar method to bind the entries to a TreeView. You'd need to update your question to include whatever UI code you're using.

Title: Accessing networked computers using C#

Body:
This will get an array of directory names (String[]) assuming the process is running as an account with access to the share:

var folders = Directory.GetDirectories(@"\\HOSTNAME\ShareName\");

You can use a similar method to bind the entries to a TreeView. You'd need to update your question to include whatever UI code you're using.


问:
How to add new Node Type to deployed Service Fabric cluster?
I deployed a Service Fabric Cluster running with a single application and 3 Node Types of 5 machines, each with its own placement constraint.

I need to add other 2 Node types (Virtual Machine Scale sets), how can I do that from the azure portal?

答:
For those who read it in 2022 and later there is a newer version of PowerShell command to do that:
Add-AzServiceFabricNodeType

And there is also a AZ CLI command: az sf cluster node-type add


问:
Changing the contents of a column according to the values of other columns using dplyr
I have the following dataframe with many different values in the page and passage column

```<code>df <- read.table(text="page passage  person index text
1  123   A   1 hello
1  123   A   2 my
1  123   A   3 name
1  123   A   4 is
1  123   A   5 guy
1  124   B   1 well
1  124   B   2 hello
1  124   B   3 guy",header=T,stringsAsFactors=F)
</code>```

I want to concatenate the content of the text column according to these columns so that it looks like this

```<code>1  123   A   1 hello my name is guy
1  123   A   2 hello my name is guy
1  123   A   3 hello my name is guy
1  123   A   4 hello my name is guy
1  123   A   5 hello my name is guy
1  124   B   1 well hello guy
1  124   B   2 well hello guy
1  124   B   3 well hello guy
</code>```

答:
Use paste with collapse inside a grouping function:

base R

df$text <- ave(df$text, df$person, FUN = function(x) paste(x, collapse = " "))
```
<h4>dplyr</h4>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
df %>%
  group_by(person) %>%
  mutate(text = paste(text, collapse=" "))
</code>```

data.table

setDT(df)[, text := paste(text, collapse = " "), person]
```
<p>output</p>
```   page passage person index text
  <int>   <int> <chr>  <int> <chr>
1     1     123 A          1 hello my name is guy
2     1     123 A          2 hello my name is guy
3     1     123 A          3 hello my name is guy
4     1     123 A          4 hello my name is guy
5     1     123 A          5 hello my name is guy
6     1     124 B          1 well hello guy
7     1     124 B          2 well hello guy
8     1     124 B          3 well hello guy
```

Body:
I have the following dataframe with many different values in the page and passage column

df <- read.table(text="page passage  person index text
1  123   A   1 hello
1  123   A   2 my
1  123   A   3 name
1  123   A   4 is
1  123   A   5 guy
1  124   B   1 well
1  124   B   2 hello
1  124   B   3 guy",header=T,stringsAsFactors=F)

I want to concatenate the content of the text column according to these columns so that it looks like this

1  123   A   1 hello my name is guy
1  123   A   2 hello my name is guy
1  123   A   3 hello my name is guy
1  123   A   4 hello my name is guy
1  123   A   5 hello my name is guy
1  124   B   1 well hello guy
1  124   B   2 well hello guy
1  124   B   3 well hello guy

Body:
Use paste with collapse inside a grouping function:

base R

df$text <- ave(df$text, df$person, FUN = function(x) paste(x, collapse = " "))

dplyr

library(dplyr)
df %>%
  group_by(person) %>%
  mutate(text = paste(text, collapse=" "))

data.table

setDT(df)[, text := paste(text, collapse = " "), person]

output

   page passage person index text
  <int>   <int> <chr>  <int> <chr>
1     1     123 A          1 hello my name is guy
2     1     123 A          2 hello my name is guy
3     1     123 A          3 hello my name is guy
4     1     123 A          4 hello my name is guy
5     1     123 A          5 hello my name is guy
6     1     124 B          1 well hello guy
7     1     124 B          2 well hello guy
8     1     124 B          3 well hello guy


问:
How to Change Background color in react-bootstrap 5 accordion

Summarize the problem
I read react-bootstrap 5 documentation but didn't see any problem with adding css and how to make it background-color

Describe what you’ve tried
i try is <Accordion.Header bsPrefix={{background: '#d0f1f7'}}>Accordion Item #1</Accordion.Header>

答:
Here it is:

HTML:

```<code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div class="accordion accordion-flush" id="accordionFlushExample">

  <div class="accordion-item">
    <h2 class="accordion-header" id="flush-headingOne">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne">

        Accordion Item #1
      </button>
    </h2>
    <div id="flush-collapseOne" class="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample">
      <div class="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the first item's accordion body.</div>
    </div>
  </div>

      </div>

  <div class="accordion-item">
    <h2 class="accordion-header" id="flush-headingTwo">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" aria-expanded="false" aria-controls="flush-collapseTwo">
        Accordion Item #2
      </button>
    </h2>
    <div id="flush-collapseTwo" class="accordion-collapse collapse" aria-labelledby="flush-headingTwo" data-bs-parent="#accordionFlushExample">
      <div class="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the second item's accordion body. Let's imagine this being filled with some actual content.</div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="flush-headingThree">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseThree" aria-expanded="false" aria-controls="flush-collapseThree">
        Accordion Item #3
      </button>
    </h2>
    <div id="flush-collapseThree" class="accordion-collapse collapse" aria-labelledby="flush-headingThree" data-bs-parent="#accordionFlushExample">
      <div style='background-color:"red" class="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the third item's accordion body. Nothing more exciting happening here in terms of content, but just filling up the space to make it look, at least at first glance, a bit more representative of how this would look in a real-world application.</div>
    </div>
  </div>
</div>
 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</code>```

CSS :

```<code>.accordion-item{background-color:#777777 !important;border:1px solid
rgba(0,0,0,.125)!important}
</code>```

https://jsfiddle.net/h27ck6rp/2/

Body:
Here it is:

HTML:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div class="accordion accordion-flush" id="accordionFlushExample">

  <div class="accordion-item">
    <h2 class="accordion-header" id="flush-headingOne">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne">

        Accordion Item #1
      </button>
    </h2>
    <div id="flush-collapseOne" class="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample">
      <div class="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the first item's accordion body.</div>
    </div>
  </div>

      </div>

  <div class="accordion-item">
    <h2 class="accordion-header" id="flush-headingTwo">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" aria-expanded="false" aria-controls="flush-collapseTwo">
        Accordion Item #2
      </button>
    </h2>
    <div id="flush-collapseTwo" class="accordion-collapse collapse" aria-labelledby="flush-headingTwo" data-bs-parent="#accordionFlushExample">
      <div class="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the second item's accordion body. Let's imagine this being filled with some actual content.</div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="flush-headingThree">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseThree" aria-expanded="false" aria-controls="flush-collapseThree">
        Accordion Item #3
      </button>
    </h2>
    <div id="flush-collapseThree" class="accordion-collapse collapse" aria-labelledby="flush-headingThree" data-bs-parent="#accordionFlushExample">
      <div style='background-color:"red" class="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the third item's accordion body. Nothing more exciting happening here in terms of content, but just filling up the space to make it look, at least at first glance, a bit more representative of how this would look in a real-world application.</div>
    </div>
  </div>
</div>
 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

CSS :

.accordion-item{background-color:#777777 !important;border:1px solid
rgba(0,0,0,.125)!important}

https://jsfiddle.net/h27ck6rp/2/


问:
Can i use native javascript for loop within jquery code?
Can i use native javascript for loop within jquery code? I have a construct in which $.each does not seem feasible. How can I loop in this situation?

the code inside the for loop is not working. any advice would be appreciated.

```<code>if (item.relate){
    $(prodHeading).append(item.name);
    if (item.image) {$(prodContent).append(item.image);}
    if (item.description) {
        $(prodContentText).append(item.description);
        $(prodContent).append(prodContentText);
    }
    $(prodBox).append(prodHeading);
    $(prodBox).append(prodContent);

    //going to look for other attached items

    for (j=0; j<10; j++){
        var prodBox = $(document.createElement('div')).attr('class','productBox');
        var prodHeading = $(document.createElement('div')).attr('class','productBoxHeading');
        var prodContent = $(document.createElement('div')).attr('class','productBoxContent');
        var prodContentText = $(document.createElement('div')).attr('class','text');

        if ('item.image'+j) {$(prodContent).append(item.image);}
        if ('item.description'+j) {
            $(prodContentText).append(item.description);
            $(prodContent).append(prodContentText);
        }
        $(prodBox).append(prodHeading);
        $(prodBox).append(prodContent);
    }
}
</code>```

答:
First,

```<code>for (j=0; j<10; j++){
</code>```

should be using a declared variable:

```<code>for (var j=0; j<10; j++){
</code>```

Second,

```<code>if ('item.image'+j) {
</code>```

does not make much sense. Every such string will pass an if condition. If you are looking whether an element exists, use:

```<code>if ($('item.image'+j).length) {
</code>```

Body:
Can i use native javascript for loop within jquery code? I have a construct in which $.each does not seem feasible. How can I loop in this situation?

the code inside the for loop is not working. any advice would be appreciated.

if (item.relate){
    $(prodHeading).append(item.name);
    if (item.image) {$(prodContent).append(item.image);}
    if (item.description) {
        $(prodContentText).append(item.description);
        $(prodContent).append(prodContentText);
    }
    $(prodBox).append(prodHeading);
    $(prodBox).append(prodContent);

    //going to look for other attached items

    for (j=0; j<10; j++){
        var prodBox = $(document.createElement('div')).attr('class','productBox');
        var prodHeading = $(document.createElement('div')).attr('class','productBoxHeading');
        var prodContent = $(document.createElement('div')).attr('class','productBoxContent');
        var prodContentText = $(document.createElement('div')).attr('class','text');

        if ('item.image'+j) {$(prodContent).append(item.image);}
        if ('item.description'+j) {
            $(prodContentText).append(item.description);
            $(prodContent).append(prodContentText);
        }
        $(prodBox).append(prodHeading);
        $(prodBox).append(prodContent);
    }
}

Body:
First,

for (j=0; j<10; j++){

should be using a declared variable:

for (var j=0; j<10; j++){

Second,

if ('item.image'+j) {

does not make much sense. Every such string will pass an if condition. If you are looking whether an element exists, use:

if ($('item.image'+j).length) {


问:
What happens to unprocessed messages in go channel on abrupt shutdown?
I have deployed a go application in kubernetes. My application has a go routine which continuously listens for messages from a kafka topic and push new messages into a go channel for further processing and commits kafka message. If I scale down the number of replicas using hpa/if replica goes down due to panic, what happens to the messages which are still in go channel unprocessed?</p>

答:
what happens to the messages which are still in go channel unprocessed?

The channels in go are in the memory, so when the app crashes, everything in the channels will be lost.


问:
I'm keep getting an error that says the column of the range is too small
I was writing some code and when i tried to run it I got an error

The starting column of the range is too small.

I'm using Google Apps Script

The error I'm getting is on this line

```<code>var cellCup = ss.getRange(ctCup, 0).activate().getValue();
</code>```
```<code>const ss = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
var ctCup =114;
var cellCup = ss.getRange(ctCup, 0).activate().getValue();
</code>```

But it works here

```<code>    var ctMHS = 3;
    var cellMHS = ss.getRange('A3');
    while ( cellMHS.offset(ctMHS, 0).getValue() != "" ) {
      ctMHS++;
    }

</code>```

答:
According to Google App Script docs https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangerow,-column

The column index of the cell to return; column indexing starts with 1.

This should fix your problem:

```<code>var cellCup = ss.getRange(ctCup, 1).activate().getValue();
</code>```

Body:
I was writing some code and when i tried to run it I got an error

The starting column of the range is too small.

I'm using Google Apps Script

The error I'm getting is on this line

var cellCup = ss.getRange(ctCup, 0).activate().getValue();

const ss = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
var ctCup =114;
var cellCup = ss.getRange(ctCup, 0).activate().getValue();

But it works here

    var ctMHS = 3;
    var cellMHS = ss.getRange('A3');
    while ( cellMHS.offset(ctMHS, 0).getValue() != "" ) {
      ctMHS++;
    }

Body:
According to Google App Script docs https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangerow,-column

The column index of the cell to return; column indexing starts with 1.

This should fix your problem:

var cellCup = ss.getRange(ctCup, 1).activate().getValue();


问:
How to change content when button is selected
Good day everyone, I have a form that has three select buttons of which "Distribute" is pre-selected when the page loads that has information in the content which is the full name, password, and location. How do I use JS to create a click effect that when any button is selected the pre-selected, deselects, and the content changes. For more clarity, here are some images to explain further

When page loads:

What should happen when I select "Buy" :

Here's my code:

* {
  box-sizing: border-box;
  list-style: none;
  text-decoration: none;
  padding: 0;
  margin: 0;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  display: flex;
  font-size: 16px;
  user-select: none;
}

/* APPLICATION */

.applicant {
  width: 60%;
  margin: auto;
  text-align: left;
  margin: 90px auto;
  padding-top: 100px;
  padding-bottom: 100px;
}

.login-center {
  height: 100%;
  flex-basis: 41%;
  background: #ffffff;
  padding: 35px 5px 0px 5px;
  box-sizing: border-box;
  box-shadow: 0 0 50px 0px #e1e1e1;
}

.text h2 {
  text-align: center;
  font-size: 35px;
  font-weight: 600;
  color: #000;
}

.links {
  text-align: center;
  margin-left: -20px;
  margin-right: -20px;
  margin: 0 auto;
  padding-top: 50px;
}

.app-button {
  color: #c4c4c4;
  background-color: #ffffff;
  border: 1px solid #000;
  font-weight: bold;
  font-size: 17px;
  width: 200px;
  margin: 0 20px;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

.app-button:hover {
  background: #c4c4c4;
  color: #000000;
  transition: 0.5s;
}

/* ACTIVE STATE */

.links .active,
.app-button:hover {
  border: 1px solid #c4c4c4;
  background-color: #c4c4c4;
  color: #000;
}

/* FORM */

.form input::placeholder {
  font-size: 14px;
  color: #000;
}

.form label {
  color: #000;
  margin: 20px 0;
  font-size: 17px;
}

.form-u {
  margin: 70px 0;
  padding: 0px 100px;
}

.form input {
  width: 100%;
  padding: 20px;
  margin: 20px 0;
  box-sizing: border-box;
  border: none;
  outline: none;
  background: #ffffff;
  border: 1.7px solid #e1e1e1;
}

.form input:focus {
  border-color: #c4c4c4;
  box-shadow: 0 0 15px 0px #e1e1e1;
}

.button-u {
  color: #c4c4c4;
  background-color: #000;
  border: 1px solid rg#c4c4c4;
  font-weight: bold;
  font-size: 17px;
  width: 100%;
  margin: 40px 0;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

/* DROPDOWN FOR LOCATION*/

.form input {
  font-size: 15px;
  color: #000;
}

.selector {
  width: 100%;
  padding-top: 20px;
  margin-bottom: 25px;
  position: relative;
}

#selectField p {
  font-size: 15px;
}

#selectField {
  width: 100%;
  background: #ffffff;
  box-sizing: border-box;
  border: 1px solid #c4c4c4;
  padding: 20px 20px;
  color: #000;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--Form-->
<section class="applicant">
  <div class="login-center">
    <div class="text">
      <h2>CREATE</h2>
    </div>
    <div class="links">
      <button type="button" class="app-button active">Distribute</button>
      <button type="button" class="app-button">Buy</button>
      <button type="button" class="app-button">Sell</button>

    </div>
    <div class="form-u">
      <form action="" class="form">

        <label for="uname"><b>Full Name:</b></label>
        <input type="text" name="name=" Enter full name "required">

        <label for="psw "><b>Password:</b></label>
        <input type="password " name="password " placeholder="Enter password " required>

        <label for="sem "><b>Location:</b></label>
        <div class="selector ">
          <div id="selectField ">
            <p id="selectText ">Select a Location</p>
            <img src="logo/arrow_down.png " alt=" " id="arrowIcon ">
          </div>
        </div>

        <button type="submit " class="button-u ">SUBMIT</button>

      </form>

    </div>

  </div>

</section></code>```

In summary, I want to be able to click all buttons and each button clicked should have different content as seen from the images. Hope I was clear enough. Thank you

答:
You could check snippet below,
Do note that there's some HTML that I remove from your example, but I achieve this request "I want to be able to click all buttons and each button clicked should have different content as seen from the images"

On the snippet below I use javascript to achieve it, and some update on the form. Note you could achieve this using JQuery or other ways, this is just one of them.

This is my approach

I add new attribute to the Button[for] and Form[id], to connect them, I used this because it gives more clarity, which button for which form.

from there just need to code a few lines of javascript.

Create function to switch form

use javascript to add click event to the button, so the button will call the switch form function.

Using the javascript you'll be able to remove "active" class on any div that has both "app-button" and "active" class, and add the class to the current caller

Using the "for" attribute of those button, we can find the paired form to hide and show.

This code is not that optimized, and not that Good as it doesn't have any animation, you could approach it with CSS transition and toggle the class, and timer, or if you want simplicity you can just add a jquery there and use Fade function.

(function() {
  const switchForm = (element) => {
    const oldActive = document.querySelector(".app-button.active");

    oldActive.classList.remove("active");
    document.querySelector(`#${oldActive.getAttribute("for")}`).style.display = "none";

    element.classList.add("active")
    document.querySelector(`#${element.getAttribute("for")}`).style.display = "";
  }

  document.querySelectorAll(".app-button").forEach(btn => {
    btn.addEventListener("click", () => switchForm(btn));
  });
})()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
  list-style: none;
  text-decoration: none;
  padding: 0;
  margin: 0;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  display: flex;
  font-size: 16px;
  user-select: none;
}

/* APPLICATION */

.applicant {
  width: 60%;
  margin: auto;
  text-align: left;
  margin: 90px auto;
  padding-top: 100px;
  padding-bottom: 100px;
}

.login-center {
  height: 100%;
  flex-basis: 41%;
  background: #ffffff;
  padding: 35px 5px 0px 5px;
  box-sizing: border-box;
  box-shadow: 0 0 50px 0px #e1e1e1;
}

.text h2 {
  text-align: center;
  font-size: 35px;
  font-weight: 600;
  color: #000;
}

.links {
  text-align: center;
  margin-left: -20px;
  margin-right: -20px;
  margin: 0 auto;
  padding-top: 50px;
}

.app-button {
  color: #c4c4c4;
  background-color: #ffffff;
  border: 1px solid #000;
  font-weight: bold;
  font-size: 17px;
  width: 200px;
  margin: 0 20px;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

.app-button:hover {
  background: #c4c4c4;
  color: #000000;
  transition: 0.5s;
}

/* ACTIVE STATE */

.links .active,
.app-button:hover {
  border: 1px solid #c4c4c4;
  background-color: #c4c4c4;
  color: #000;
}

/* FORM */

.form input::placeholder {
  font-size: 14px;
  color: #000;
}

.form label {
  color: #000;
  margin: 20px 0;
  font-size: 17px;
}

.form-u {
  margin: 70px 0;
  padding: 0px 100px;
}

.form input {
  width: 100%;
  padding: 20px;
  margin: 20px 0;
  box-sizing: border-box;
  border: none;
  outline: none;
  background: #ffffff;
  border: 1.7px solid #e1e1e1;
}

.form input:focus {
  border-color: #c4c4c4;
  box-shadow: 0 0 15px 0px #e1e1e1;
}

.button-u {
  color: #c4c4c4;
  background-color: #000;
  border: 1px solid rg#c4c4c4;
  font-weight: bold;
  font-size: 17px;
  width: 100%;
  margin: 40px 0;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

/* DROPDOWN FOR LOCATION*/

.form input {
  font-size: 15px;
  color: #000;
}

.selector {
  width: 100%;
  padding-top: 20px;
  margin-bottom: 25px;
  position: relative;
}

#selectField p {
  font-size: 15px;
}

#selectField {
  width: 100%;
  background: #ffffff;
  box-sizing: border-box;
  border: 1px solid #c4c4c4;
  padding: 20px 20px;
  color: #000;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  position: relative;
}</code>```

CREATE

      <button type="button" for="distribute" class="app-button active">Distribute</button>
      <button type="button" for="buy" class="app-button">Buy</button>
      <button type="button" for="sell" class="app-button">Sell</button>

      <form action="" class="form" id="distribute">
        Distribute Inputs:
        <input type="text" name="name=" Enter full name "required">
        <button type="submit " class="button-u ">SUBMIT DISTRIBUTE</button>
      </form>
      <form action="" class="form" style="display:none;" id="buy">
        Buy Inputs:
        <input type="text" name="name=" Enter full name "required">
        <button type="submit " class="button-u ">SUBMIT BUY</button>
      </form>
      <form action="" class="form" style="display:none;" id="sell">
        Sell Inputs:
        <input type="text" name="name=" Enter full name "required">
        <button type="submit " class="button-u ">SUBMIT SELL</button>
      </form>

```

Body:
Good day everyone, I have a form that has three select buttons of which "Distribute" is pre-selected when the page loads that has information in the content which is the full name, password, and location. How do I use JS to create a click effect that when any button is selected the pre-selected, deselects, and the content changes. For more clarity, here are some images to explain further

When page loads:

What should happen when I select "Buy" :

Here's my code:

* {
  box-sizing: border-box;
  list-style: none;
  text-decoration: none;
  padding: 0;
  margin: 0;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  display: flex;
  font-size: 16px;
  user-select: none;
}

/* APPLICATION */

.applicant {
  width: 60%;
  margin: auto;
  text-align: left;
  margin: 90px auto;
  padding-top: 100px;
  padding-bottom: 100px;
}

.login-center {
  height: 100%;
  flex-basis: 41%;
  background: #ffffff;
  padding: 35px 5px 0px 5px;
  box-sizing: border-box;
  box-shadow: 0 0 50px 0px #e1e1e1;
}

.text h2 {
  text-align: center;
  font-size: 35px;
  font-weight: 600;
  color: #000;
}

.links {
  text-align: center;
  margin-left: -20px;
  margin-right: -20px;
  margin: 0 auto;
  padding-top: 50px;
}

.app-button {
  color: #c4c4c4;
  background-color: #ffffff;
  border: 1px solid #000;
  font-weight: bold;
  font-size: 17px;
  width: 200px;
  margin: 0 20px;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

.app-button:hover {
  background: #c4c4c4;
  color: #000000;
  transition: 0.5s;
}

/* ACTIVE STATE */

.links .active,
.app-button:hover {
  border: 1px solid #c4c4c4;
  background-color: #c4c4c4;
  color: #000;
}

/* FORM */

.form input::placeholder {
  font-size: 14px;
  color: #000;
}

.form label {
  color: #000;
  margin: 20px 0;
  font-size: 17px;
}

.form-u {
  margin: 70px 0;
  padding: 0px 100px;
}

.form input {
  width: 100%;
  padding: 20px;
  margin: 20px 0;
  box-sizing: border-box;
  border: none;
  outline: none;
  background: #ffffff;
  border: 1.7px solid #e1e1e1;
}

.form input:focus {
  border-color: #c4c4c4;
  box-shadow: 0 0 15px 0px #e1e1e1;
}

.button-u {
  color: #c4c4c4;
  background-color: #000;
  border: 1px solid rg#c4c4c4;
  font-weight: bold;
  font-size: 17px;
  width: 100%;
  margin: 40px 0;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

/* DROPDOWN FOR LOCATION*/

.form input {
  font-size: 15px;
  color: #000;
}

.selector {
  width: 100%;
  padding-top: 20px;
  margin-bottom: 25px;
  position: relative;
}

#selectField p {
  font-size: 15px;
}

#selectField {
  width: 100%;
  background: #ffffff;
  box-sizing: border-box;
  border: 1px solid #c4c4c4;
  padding: 20px 20px;
  color: #000;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  position: relative;
}

CREATE

      <button type="button" class="app-button active">Distribute</button>
      <button type="button" class="app-button">Buy</button>
      <button type="button" class="app-button">Sell</button>

      <form action="" class="form">

        Full Name:
        <input type="text" name="name=" Enter full name "required">

        Password:
        <input type="password " name="password " placeholder="Enter password " required>

        Location:

Select a Location

        <button type="submit " class="button-u ">SUBMIT</button>

      </form>

In summary, I want to be able to click all buttons and each button clicked should have different content as seen from the images. Hope I was clear enough. Thank you

Body:
You could check snippet below,
Do note that there's some HTML that I remove from your example, but I achieve this request "I want to be able to click all buttons and each button clicked should have different content as seen from the images"

On the snippet below I use javascript to achieve it, and some update on the form. Note you could achieve this using JQuery or other ways, this is just one of them.

This is my approach

I add new attribute to the Button[for] and Form[id], to connect them, I used this because it gives more clarity, which button for which form.

from there just need to code a few lines of javascript.

Create function to switch form

use javascript to add click event to the button, so the button will call the switch form function.

Using the javascript you'll be able to remove "active" class on any div that has both "app-button" and "active" class, and add the class to the current caller

Using the "for" attribute of those button, we can find the paired form to hide and show.

This code is not that optimized, and not that Good as it doesn't have any animation, you could approach it with CSS transition and toggle the class, and timer, or if you want simplicity you can just add a jquery there and use Fade function.

(function() {
  const switchForm = (element) => {
    const oldActive = document.querySelector(".app-button.active");

    oldActive.classList.remove("active");
    document.querySelector(`#${oldActive.getAttribute("for")}`).style.display = "none";

    element.classList.add("active")
    document.querySelector(`#${element.getAttribute("for")}`).style.display = "";
  }

  document.querySelectorAll(".app-button").forEach(btn => {
    btn.addEventListener("click", () => switchForm(btn));
  });
})()

* {
  box-sizing: border-box;
  list-style: none;
  text-decoration: none;
  padding: 0;
  margin: 0;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  display: flex;
  font-size: 16px;
  user-select: none;
}

/* APPLICATION */

.applicant {
  width: 60%;
  margin: auto;
  text-align: left;
  margin: 90px auto;
  padding-top: 100px;
  padding-bottom: 100px;
}

.login-center {
  height: 100%;
  flex-basis: 41%;
  background: #ffffff;
  padding: 35px 5px 0px 5px;
  box-sizing: border-box;
  box-shadow: 0 0 50px 0px #e1e1e1;
}

.text h2 {
  text-align: center;
  font-size: 35px;
  font-weight: 600;
  color: #000;
}

.links {
  text-align: center;
  margin-left: -20px;
  margin-right: -20px;
  margin: 0 auto;
  padding-top: 50px;
}

.app-button {
  color: #c4c4c4;
  background-color: #ffffff;
  border: 1px solid #000;
  font-weight: bold;
  font-size: 17px;
  width: 200px;
  margin: 0 20px;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

.app-button:hover {
  background: #c4c4c4;
  color: #000000;
  transition: 0.5s;
}

/* ACTIVE STATE */

.links .active,
.app-button:hover {
  border: 1px solid #c4c4c4;
  background-color: #c4c4c4;
  color: #000;
}

/* FORM */

.form input::placeholder {
  font-size: 14px;
  color: #000;
}

.form label {
  color: #000;
  margin: 20px 0;
  font-size: 17px;
}

.form-u {
  margin: 70px 0;
  padding: 0px 100px;
}

.form input {
  width: 100%;
  padding: 20px;
  margin: 20px 0;
  box-sizing: border-box;
  border: none;
  outline: none;
  background: #ffffff;
  border: 1.7px solid #e1e1e1;
}

.form input:focus {
  border-color: #c4c4c4;
  box-shadow: 0 0 15px 0px #e1e1e1;
}

.button-u {
  color: #c4c4c4;
  background-color: #000;
  border: 1px solid rg#c4c4c4;
  font-weight: bold;
  font-size: 17px;
  width: 100%;
  margin: 40px 0;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

/* DROPDOWN FOR LOCATION*/

.form input {
  font-size: 15px;
  color: #000;
}

.selector {
  width: 100%;
  padding-top: 20px;
  margin-bottom: 25px;
  position: relative;
}

#selectField p {
  font-size: 15px;
}

#selectField {
  width: 100%;
  background: #ffffff;
  box-sizing: border-box;
  border: 1px solid #c4c4c4;
  padding: 20px 20px;
  color: #000;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  position: relative;
}

<!--Form-->
<section class="applicant">
  <div class="login-center">
    <div class="text">
      <h2>CREATE</h2>
    </div>
    <div class="links">
      <button type="button" for="distribute" class="app-button active">Distribute</button>
      <button type="button" for="buy" class="app-button">Buy</button>
      <button type="button" for="sell" class="app-button">Sell</button>

    </div>
    <div class="form-u">
      <form action="" class="form" id="distribute">
        <label for="uname"><b>Distribute Inputs:</b></label>
        <input type="text" name="name=" Enter full name "required">
        <button type="submit " class="button-u ">SUBMIT DISTRIBUTE</button>
      </form>
      <form action="" class="form" style="display:none;" id="buy">
        <label for="uname"><b>Buy Inputs:</b></label>
        <input type="text" name="name=" Enter full name "required">
        <button type="submit " class="button-u ">SUBMIT BUY</button>
      </form>
      <form action="" class="form" style="display:none;" id="sell">
        <label for="uname"><b>Sell Inputs:</b></label>
        <input type="text" name="name=" Enter full name "required">
        <button type="submit " class="button-u ">SUBMIT SELL</button>
      </form>
    </div>

  </div>

</section>


问:
New Relic warning: the Xdebug extension prevents the New Relic agent from gathering errors. No errors will be recorded
In /var/log/newrelic/php_agent.log on my servers I see lines like this:

2013-08-30 16:05:01.444 (15615/child) warning: the Xdebug extension prevents the New Relic agent from gathering errors. No errors will be recorded.

Yet, I still see [at least some] PHP errors in New Relic. What's going on? Is this warning a bug in New Relic?

I also found this which says:

If you are using xdebug, you will have a warning about this. So you could turn off Xdebug , or write your own handler and call New Relic API to allow errors report into New Relic properly. See the comments of Kris Weltz for more information.

The words "Kris Weltz" link to a missing document.

Here's what I've got installed:

```<code># rpm -qa | grep relic
newrelic-php5-common-3.7.5.7-1.noarch
newrelic-php5-3.7.5.7-1.x86_64
newrelic-repo-5-3.noarch
newrelic-daemon-3.7.5.7-1.x86_64
newrelic-sysmond-1.2.0.257-1.x86_64
</code>```

答:
Instead of uninstalling extension you can also disable xdebug extension loading in the .ini files.
I use docker, so in the docker container where docker agent runs.

In

In /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini comment following line: zend_extension=xdebug

Also, in /usr/local/etc/php/conf.d/xdebug.ini comment following line: zend_extension=xdebug.so

Restart PHP service or docker container.

If the .ini paths does not match to yours, running php --ini command will list all the .ini files that it uses.

This solution worked for me.

Body:
In /var/log/newrelic/php_agent.log on my servers I see lines like this:

2013-08-30 16:05:01.444 (15615/child) warning: the Xdebug extension prevents the New Relic agent from gathering errors. No errors will be recorded.

Yet, I still see [at least some] PHP errors in New Relic. What's going on? Is this warning a bug in New Relic?

I also found this which says:

If you are using xdebug, you will have a warning about this. So you could turn off Xdebug , or write your own handler and call New Relic API to allow errors report into New Relic properly. See the comments of Kris Weltz for more information.

The words "Kris Weltz" link to a missing document.

Here's what I've got installed:

# rpm -qa | grep relic
newrelic-php5-common-3.7.5.7-1.noarch
newrelic-php5-3.7.5.7-1.x86_64
newrelic-repo-5-3.noarch
newrelic-daemon-3.7.5.7-1.x86_64
newrelic-sysmond-1.2.0.257-1.x86_64


问:
Hosting ASP.NET on Raspberry Pi 3B+ for local network
I am trying to host an API (ASP.NET) on my Raspberri Pi 3B +. I would like to access this API swagger page from my laptop/phone/pc etc.

What I've tried until now:
Installed, compiled, built and ran the web application with dotnet on my RPi.

running dotnet --info  on the RPi provides us the following information:

```<code>.NET SDK (reflecting any global.json):
 Version:   5.0.405
 Commit:    63325e1c7d

Runtime Environment:
 OS Name:     raspbian
 OS Version:  11
 OS Platform: Linux
 RID:         linux-arm
 Base Path:   /usr/share/dotnet/sdk/5.0.405/

Host (useful for support):
  Version: 5.0.14
  Commit:  d5b56c6327

.NET SDKs installed:
  5.0.405 [/usr/share/dotnet/sdk]

.NET runtimes installed:
  Microsoft.AspNetCore.App 5.0.14 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 5.0.14 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
</code>```

When I run the program (filepath ~/first-rpi-api/bin/Release/net5.0/publish/first-rpi-api)

I get the following:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/pi/first-rpi-api/bin/Release/net5.0/publish
```

The default URL for the swagger UI would be : https://localhost:44335/swagger/index.html
However when I try to access the API from my PC on URL : https://RPi_IP:5000/swagger/index.html

I get ERR_CONNECTION_REFUSED

How do I fix this ? Have I missed something and how would I approach this problem ?

答:
```<code>info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
</code>```

Listening on localhost means that it's only listening to network connections from the same machine (which is the Raspberry Pi, in your case). If you want it to listen to network connections from outside the machine, you need to listen to 0.0.0.0.

Without seeing your code that sets up network conncetions, it's hard to be sure what a fix that would integrate well would look like but try doing this before running your program:

```<code>export ASPNETCORE_URLS="http://*:5000;https://*:5001"
</code>```

That will make your application allow connections from anywhere.

Body:
I am trying to host an API (ASP.NET) on my Raspberri Pi 3B +. I would like to access this API swagger page from my laptop/phone/pc etc.

What I've tried until now:
Installed, compiled, built and ran the web application with dotnet on my RPi.

running dotnet --info  on the RPi provides us the following information:

.NET SDK (reflecting any global.json):
 Version:   5.0.405
 Commit:    63325e1c7d

Runtime Environment:
 OS Name:     raspbian
 OS Version:  11
 OS Platform: Linux
 RID:         linux-arm
 Base Path:   /usr/share/dotnet/sdk/5.0.405/

Host (useful for support):
  Version: 5.0.14
  Commit:  d5b56c6327

.NET SDKs installed:
  5.0.405 [/usr/share/dotnet/sdk]

.NET runtimes installed:
  Microsoft.AspNetCore.App 5.0.14 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 5.0.14 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

When I run the program (filepath ~/first-rpi-api/bin/Release/net5.0/publish/first-rpi-api)

I get the following:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/pi/first-rpi-api/bin/Release/net5.0/publish

The default URL for the swagger UI would be : https://localhost:44335/swagger/index.html
However when I try to access the API from my PC on URL : https://RPi_IP:5000/swagger/index.html

I get ERR_CONNECTION_REFUSED

How do I fix this ? Have I missed something and how would I approach this problem ?

Body:
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001

Listening on localhost means that it's only listening to network connections from the same machine (which is the Raspberry Pi, in your case). If you want it to listen to network connections from outside the machine, you need to listen to 0.0.0.0.

Without seeing your code that sets up network conncetions, it's hard to be sure what a fix that would integrate well would look like but try doing this before running your program:

export ASPNETCORE_URLS="http://*:5000;https://*:5001"

That will make your application allow connections from anywhere.


问:
Automate the Boring Stuff - Coin Flip Streaks - How to optimize my answer?
I've been going through automate the boring stuff, and am trying the practice problems.
I came up with this solution to the project on the lists chapter - Coin Flip Streaks.

The objective of the problem is the following:
''For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.''
And this is my code.

```<code>numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    experimentNumber = experimentNumber + 1
    for test in range(100):
        selector = random.randint(0,1)
        if selector == 0:
            experiment = experiment + ['H']
        elif selector == 1:
            experiment = experiment + ['T']

    for n in range(94):
        if experiment[n:n+6] == ['T', 'T', 'T', 'T', 'T', 'T']:
            numberOfStreaks = numberOfStreaks + 1
        elif experiment[n:n+6] == ['H', 'H', 'H', 'H', 'H', 'H']:
            numberOfStreaks = numberOfStreaks + 1
        else:
            numberOfStreaks = numberOfStreaks
print((numberOfStreaks / 100000) * 100)
</code>```

I can only run this solution efficiently for 1000 experiments, and the book says to run for 10000, but it takes too long.
I think this derives from the inneficiency of the algorithm I came up with.

How do I make this algorithm more efficient?

答:
This is how I would write this:

```<code>import random

n_exp = 10_000
n_streak = 0
for experiment in range(n_exp):
    draw = ''.join(random.choices('HT', k=100))
    if 'H'*6 in draw or 'T'*6 in draw:
        n_streak += 1

res = n_streak / n_exp * 100
print(res)
</code>```

The random.choices function builds a string of length 100 with random characters picked in 'HT', then you count the number of non-overlapping repetitions of a substring with 6 H or 6 T, add it to the number of streaks.

Body:
I've been going through automate the boring stuff, and am trying the practice problems.
I came up with this solution to the project on the lists chapter - Coin Flip Streaks.

The objective of the problem is the following:
''For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.''
And this is my code.

numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    experimentNumber = experimentNumber + 1
    for test in range(100):
        selector = random.randint(0,1)
        if selector == 0:
            experiment = experiment + ['H']
        elif selector == 1:
            experiment = experiment + ['T']

    for n in range(94):
        if experiment[n:n+6] == ['T', 'T', 'T', 'T', 'T', 'T']:
            numberOfStreaks = numberOfStreaks + 1
        elif experiment[n:n+6] == ['H', 'H', 'H', 'H', 'H', 'H']:
            numberOfStreaks = numberOfStreaks + 1
        else:
            numberOfStreaks = numberOfStreaks
print((numberOfStreaks / 100000) * 100)

I can only run this solution efficiently for 1000 experiments, and the book says to run for 10000, but it takes too long.
I think this derives from the inneficiency of the algorithm I came up with.

How do I make this algorithm more efficient?

Body:
This is how I would write this:

import random

n_exp = 10_000
n_streak = 0
for experiment in range(n_exp):
    draw = ''.join(random.choices('HT', k=100))
    if 'H'*6 in draw or 'T'*6 in draw:
        n_streak += 1

res = n_streak / n_exp * 100
print(res)

The random.choices function builds a string of length 100 with random characters picked in 'HT', then you count the number of non-overlapping repetitions of a substring with 6 H or 6 T, add it to the number of streaks.


问:
Beautiful Soup: AttributeError: 'NoneType' object has no attribute 'get_text'
I am having a problem with Beautiful Soup and I cannot figure it out for the life of me. I am attempting to find an element and get the text inside it.

```<code>location = t.find('span', itemprop='name').get_text()
</code>```

But I keep getting this error:

```<code>AttributeError: 'NoneType' object has no attribute 'get_text'
</code>```

However, if I run location = t.find('span', itemprop='name') I get the proper Tag object: <class 'bs4.element.Tag'> location=Hobart, IN

What would cause this error?

Here is the full code:

```<code>with open('source.html') as f:
   soup = BeautifulSoup(f.read(), "html.parser")

# Extract script and style elements
for s in soup(["script", "style"]):
    s.extract()

tr = soup.find_all("tr")
for t in tr:
    location = t.find('span', itemprop='name').get_text() # ERROR
</code>```

Source HTML is a table:

```<code>                <tr class="espresso-table-row live">
            <td class="event_title event-61492">Title of class</td>
                            <td class="venue_title event-61492"><span itemprop="name">Location</span></td>
                        <td class="start_date event-61492" data-value="1645452000">
                <ul class="ee-table-view-datetime-list">
                                                <li class="datetime-id-630">
                                February 21, 2022                           </li>
                                    </ul>
            </td>
            <td class="td-group reg-col" nowrap="nowrap"><a id="a_register_link-61492" class="a_register_link" href="https://website.com/">Register</a></td>
        </tr>
</code>```

答:
Question do not provide detailed information about the html, but it looks like there are
 selected that do not have any  with that attribute.

You should select your tags more specific for example with css selectors:

```<code>for span in soup.select('tr span[itemprop="name"]'):
    location = span.get_text()
</code>```

Example

This html will lead with your code to an error cause your find_all('tr') is selecting both
 but in the second one you won't find() a  - result is None and None has no attribute get_text(). It will give you the location if you select it more specific.

```<code>from bs4 import BeautifulSoup
html = '''
<tr class="espresso-table-row live">
    <td class="event_title event-61492">Title of class</td>
    <td class="venue_title event-61492"><span itemprop="name">Location</span></td>
    <td class="start_date event-61492" data-value="1645452000">
        <ul class="ee-table-view-datetime-list">
            <li class="datetime-id-630">
                February 21, 2022
            </li>
        </ul>
    </td>
    <td class="td-group reg-col" nowrap="nowrap"><a id="a_register_link-61492" class="a_register_link" href="https://website.com/">Register</a></td>
</tr>
<tr>
    any other content
</tr>
'''

soup = BeautifulSoup(html)

for span in soup.select('tr span[itemprop="name"]'):
    location = span.get_text()

print(location)
</code>```

Output

```<code>Location
</code>```

Body:
I am having a problem with Beautiful Soup and I cannot figure it out for the life of me. I am attempting to find an element and get the text inside it.

location = t.find('span', itemprop='name').get_text()

But I keep getting this error:

AttributeError: 'NoneType' object has no attribute 'get_text'

However, if I run location = t.find('span', itemprop='name') I get the proper Tag object: <class 'bs4.element.Tag'> location=Hobart, IN

What would cause this error?

Here is the full code:

with open('source.html') as f:
   soup = BeautifulSoup(f.read(), "html.parser")

# Extract script and style elements
for s in soup(["script", "style"]):
    s.extract()

tr = soup.find_all("tr")
for t in tr:
    location = t.find('span', itemprop='name').get_text() # ERROR

Source HTML is a table:

            Title of class
                            Location

                                February 21, 2022

            Register

Body:
Question do not provide detailed information about the html, but it looks like there are <tr> selected that do not have any <span> with that attribute.

You should select your tags more specific for example with css selectors:

for span in soup.select('tr span[itemprop="name"]'):
    location = span.get_text()

Example

This html will lead with your code to an error cause your find_all('tr') is selecting both <tr> but in the second one you won't find() a <span> - result is None and None has no attribute get_text(). It will give you the location if you select it more specific.

from bs4 import BeautifulSoup
html = '''
<tr class="espresso-table-row live">
    <td class="event_title event-61492">Title of class</td>
    <td class="venue_title event-61492"><span itemprop="name">Location</span></td>
    <td class="start_date event-61492" data-value="1645452000">
        <ul class="ee-table-view-datetime-list">
            <li class="datetime-id-630">
                February 21, 2022
            </li>
        </ul>
    </td>
    <td class="td-group reg-col" nowrap="nowrap"><a id="a_register_link-61492" class="a_register_link" href="https://website.com/">Register</a></td>
</tr>
<tr>
    any other content
</tr>
'''

soup = BeautifulSoup(html)

for span in soup.select('tr span[itemprop="name"]'):
    location = span.get_text()

print(location)

Output

Location