问:
opencv depth map accuracy
I want to measure distance to an object using a 3d stereoscopic camera phone with opencv. I am looking for a formula which will measure the accuracy of the distance measurement, depending on the focal length, the distance between the 2 cameras, the image resolution, and the size of the measured object.
Googling a little, I found this formula:

d = Z^2 * p / (f*b)

Z - distance to object, p - disparity accuracy, f - focal length, b - baseline (distance between cameras).

I know the baseline and the focal length, but I don't know the disparity accuracy.
Is this formula what I need? If so, how do I find the disparity accuracy?

Thanks.

答:
If you look at the paragraph after formula 8 in the document you link you can see that they have a disparity accuracy 0.18*10^-6m. Reading a bit further, I conclude that the disparity accuracy they use is the distance in m between two pixels on the CCD of the cameras used. For a 1/4" CCD (which measures 3.2mm by 2.4mm) with resolution 640X480 (a very old VGA camera) this would be 5*10^-6. I don't know what the sensor size for the LG Optimus 3D is, but assuming 1/4" CCD's and 2592 pixel horizontal resolution, the baseline for the disparity accuracy would be: 1.23*10^-6, giving a depth accuracy at 10m of about 0.85m. Which looks reasonable to me. If the CCD is smaller it will improve (i.e. the accuracy value lowers).

This is the lowest possible value that assumes perfect matching of features between the two stereo images. This value just represents the physical limitations of your stereo pair.

Title: opencv depth map accuracy


来源: stackexchange

问:
Trying to make a cron job to move my files from desktop to a temp file at the end of the day
I want to make a simple cron job that moves all the files on my desktop to a temp folder at the end of the day. for debugging
I wrote this bash script that works when I run it using bash:

```<code>#!/bin/bash
/bin/mv ~/Desktop/* ~/Temp

</code>```

saved the script and I am using the following cron job:

```<code>59 23 * * * /bin/mv /Users/username/Desktop/* /Users/username/Temp
</code>```

The cron job executes when I tested printing something to a file. but somehow it will not move files? Is there something I am missing?

答:
Suggesting to fix your bash script with correct user context.

Since ~ is defined by user's context.

It is possible to replace each ~ with $HOME path:

```<code> sed -i "s|~|$HOME|g" your-script.sh
</code>```

And/Or include users context in your script:

```<code> sed -i "2i source $HOME/.bash_profile" your-script.sh
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to make a simple cron job that moves all the files on my desktop to a temp folder at the end of the day. for debugging
I wrote this bash script that works when I run it using bash:

#!/bin/bash
/bin/mv ~/Desktop/* ~/Temp

saved the script and I am using the following cron job:

59 23 * * * /bin/mv /Users/username/Desktop/* /Users/username/Temp

The cron job executes when I tested printing something to a file. but somehow it will not move files? Is there something I am missing?

Body:
Suggesting to fix your bash script with correct user context.

Since ~ is defined by user's context.

It is possible to replace each ~ with $HOME path:

 sed -i "s|~|$HOME|g" your-script.sh

And/Or include users context in your script:

 sed -i "2i source $HOME/.bash_profile" your-script.sh


问:
Render texture doesn't update changes made, how to ensure this happens?
I'm building a system which has a set of quads in front of each other, forming a layer system. This layers are being rendered by a orthographic camera with a render texture, which is used to generate a texture and save it to disk after the layers are populated. It happens that I need to disable some of those layers before the final texture is generated. So I built a module that disable those specific layers' mesh renderers and raise an event to start the render to texture conversion.

To my surprise, the final image still presents the disabled layers in the final image. I'm really confused about this, cause I already debugged the code in every way I could and those specific layers shouldn't be visible at all considering the code. It must have something to do with how often render textures update or some other obscure execution order. The entire module is composed of 3 or 4 classes with dozens of lines, so to exemplify the issue in a more succinct way, I'll post only the method where the RT is being converted into a texture with some checks I made just before the RT pixels are read into the new texture:

```<code>public void SaveTexture(string textureName, TextureFormat textureFormat)
{
    renderTexture = GetComponent<Camera>().targetTexture;
    RenderTexture.active = renderTexture;
    var finalTexture = new Texture2D(renderTexture.width,
        renderTexture.height, textureFormat, false);

    /*First test, confirming that the marked quad' mesh renderer
     is, in fact, disabled, meaning it shouldn't be visible in the camera,
    consequently invisible in the RT. The console shows "false", meaning it's
    disabled. Even so, the quad still being rendered in the final image.*/
    //Debug.Log(transform.GetChild(6).GetChild(0).GetComponent<MeshRenderer>().enabled);

    /*Second test, changing the object' layer, because the projection camera
     has a culling mask enabled to only capture objects in one specific layer.
    Again, it doesn't work and the quad content still being saved in the final image.*/
    //transform.GetChild(6).GetChild(0).gameObject.layer = 0;

    /*Final test, destroying the object to ensure it doesn't appear in the RT.
     This also doesn't work, confirming that no matter what I do, the RT is
    "fixed" at this point of execution and it doesn't update any changes made
    on it's composition.*/
    //Destroy(transform.GetChild(6).GetChild(0).gameObject);

    finalTexture.ReadPixels(new Rect(0, 0, renderTexture.width,
        renderTexture.height), 0, 0);
    finalTexture.Apply();
    finalTexture.name = textureName;
    var teamTitle = generationController.activeTeam.title;
    var kitIndex = generationController.activeKitIndex;
    var customDirectory = saveDirectory + teamTitle + "/"+kitIndex+"/";

    StorageManager<Texture2D>.Save(finalTexture, customDirectory, finalTexture.name);
    RenderTexture.active = null;
    onSaved();
}
</code>```

Funny thing is, if I manually disable that quad in inspector (at runtime, just before trigger the method above), it works, and the final texture is generated without the disabled layer.

I tried my best to show my problem, this is one of those issues that are kinda hard to show here but hopefully somebody will have some insight of what is happening and what should I do to solve that.

答: There are two possible solutions to my issue (got the answer at Unity Forum). The first one, is to use the methods OnPreRender and OnPostRender to properly organize what should happens before or after the camera render update. What I end up doing though was calling the manual render method in the Camera, using the "GetComponenent().Render();" line, which updates the camera render manually. Considering that my structure was ready already, this single line solved my problem!</p>

Body:
I'm building a system which has a set of quads in front of each other, forming a layer system. This layers are being rendered by a orthographic camera with a render texture, which is used to generate a texture and save it to disk after the layers are populated. It happens that I need to disable some of those layers before the final texture is generated. So I built a module that disable those specific layers' mesh renderers and raise an event to start the render to texture conversion.

To my surprise, the final image still presents the disabled layers in the final image. I'm really confused about this, cause I already debugged the code in every way I could and those specific layers shouldn't be visible at all considering the code. It must have something to do with how often render textures update or some other obscure execution order. The entire module is composed of 3 or 4 classes with dozens of lines, so to exemplify the issue in a more succinct way, I'll post only the method where the RT is being converted into a texture with some checks I made just before the RT pixels are read into the new texture:

public void SaveTexture(string textureName, TextureFormat textureFormat)
{
    renderTexture = GetComponent<Camera>().targetTexture;
    RenderTexture.active = renderTexture;
    var finalTexture = new Texture2D(renderTexture.width,
        renderTexture.height, textureFormat, false);

    /*First test, confirming that the marked quad' mesh renderer
     is, in fact, disabled, meaning it shouldn't be visible in the camera,
    consequently invisible in the RT. The console shows "false", meaning it's
    disabled. Even so, the quad still being rendered in the final image.*/
    //Debug.Log(transform.GetChild(6).GetChild(0).GetComponent<MeshRenderer>().enabled);

    /*Second test, changing the object' layer, because the projection camera
     has a culling mask enabled to only capture objects in one specific layer.
    Again, it doesn't work and the quad content still being saved in the final image.*/
    //transform.GetChild(6).GetChild(0).gameObject.layer = 0;

    /*Final test, destroying the object to ensure it doesn't appear in the RT.
     This also doesn't work, confirming that no matter what I do, the RT is
    "fixed" at this point of execution and it doesn't update any changes made
    on it's composition.*/
    //Destroy(transform.GetChild(6).GetChild(0).gameObject);

    finalTexture.ReadPixels(new Rect(0, 0, renderTexture.width,
        renderTexture.height), 0, 0);
    finalTexture.Apply();
    finalTexture.name = textureName;
    var teamTitle = generationController.activeTeam.title;
    var kitIndex = generationController.activeKitIndex;
    var customDirectory = saveDirectory + teamTitle + "/"+kitIndex+"/";

    StorageManager<Texture2D>.Save(finalTexture, customDirectory, finalTexture.name);
    RenderTexture.active = null;
    onSaved();
}

Funny thing is, if I manually disable that quad in inspector (at runtime, just before trigger the method above), it works, and the final texture is generated without the disabled layer.

I tried my best to show my problem, this is one of those issues that are kinda hard to show here but hopefully somebody will have some insight of what is happening and what should I do to solve that.


问:
Compare 2 CSV files using powershell
I am comparing 2 csv files against IP address.

Below is the code, but it is not giving me the correct report. there are IP addresses present in $CSV2 but it is not showing

```<code>$CSV1 = Import-Csv -Path "E:\IP_Details.csv"
$CSV2 = Import-Csv -Path "E:\IP_Details_1.csv"

$Count = $CSV1.Count
$Results = For ($i = 0; $i -lt $Count; $i++) {

$IP_one = $CSV1[$i].'IP adress'.Trim()
$IP_two = $CSV2[$i].'IP adress'.Trim()

    If ($CSV1[$i].'IP adress' -eq $CSV2[$i].'IP adress') {
        $Match = "Match"
    }
    Else {
        $Match = "Not Match"
    }
    [PSCustomObject]@{

        Value = $CSV1[$i].'IP adress'
        IPName = $CSV1[$i].IPName
        Results = $Match
    }
}
$Results | Export-Csv -Path "E:\File.csv" -NoTypeInformation
</code>```

Please let me know what is wrong in the code

Got the below lines which is working fine

```<code>$file1 = import-csv -Path "E:\InfoBlox_Used_IP_Details.csv"
$file2 = import-csv -Path "E:\CMDB_IP_Details.csv"
Compare-Object $file1 $file2 -property 'IP adress' -IncludeEqual | Export-Csv -Path e:\testmantest2.csv
</code>```

but it is giving me output like

```<code>"IP adress","SideIndicator"
"10.15.9.8","=="
"10.15.9.6","=="
"10.15.9.14","=="
"10.12.21.10","<="
</code>```

but I need output like below where == should be match and >= is not match

```<code>"IP adress","IP Name","Status"
"10.15.9.8","one","match"
"10.15.9.6","two","match"
"10.15.9.14","three","match"
"10.12.21.10","four","Not macth"
</code>```

Can you please let me know how can I do that

答:
Here is how you can approach the problem, since you're only interested in knowing if an IP in CSV1 exists in CSV2, using a Hashset should be more efficient than Compare-Object. As for what you're doing wrong, on your initial code, you're running a line-by-line comparison hence even if an IP exists in both Csvs, if they're not on the same line / row your condition will be $false.

```<code>$CSV1 = Import-Csv -Path 'C:\path\to\csv1.csv'
$reference = [System.Collections.Generic.HashSet[string]]::new(
    [string[]](Import-Csv -Path 'C:\path\to\csv2.csv').'IP address'.ForEach('Trim')
)

$results = foreach($line in $Csv1)
{
    $ip = $line.'Ip address'.Trim()
    [PSCustomObject]@{
        Value   = $ip
        IPName  = $line.IPName
        Results = ('Not Match', 'Match')[$reference.Contains($ip)]
    }
}

$results | Export-Csv -Path "E:\File.csv" -NoTypeInformation
</code>```

Title: Compare 2 CSV files using powershell

Body:
I am comparing 2 csv files against IP address.

Below is the code, but it is not giving me the correct report. there are IP addresses present in $CSV2 but it is not showing

$CSV1 = Import-Csv -Path "E:\IP_Details.csv"
$CSV2 = Import-Csv -Path "E:\IP_Details_1.csv"

$Count = $CSV1.Count
$Results = For ($i = 0; $i -lt $Count; $i++) {

$IP_one = $CSV1[$i].'IP adress'.Trim()
$IP_two = $CSV2[$i].'IP adress'.Trim()

    If ($CSV1[$i].'IP adress' -eq $CSV2[$i].'IP adress') {
        $Match = "Match"
    }
    Else {
        $Match = "Not Match"
    }
    [PSCustomObject]@{

        Value = $CSV1[$i].'IP adress'
        IPName = $CSV1[$i].IPName
        Results = $Match
    }
}
$Results | Export-Csv -Path "E:\File.csv" -NoTypeInformation

Please let me know what is wrong in the code

Got the below lines which is working fine

$file1 = import-csv -Path "E:\InfoBlox_Used_IP_Details.csv"
$file2 = import-csv -Path "E:\CMDB_IP_Details.csv"
Compare-Object $file1 $file2 -property 'IP adress' -IncludeEqual | Export-Csv -Path e:\testmantest2.csv

but it is giving me output like

"IP adress","SideIndicator"
"10.15.9.8","=="
"10.15.9.6","=="
"10.15.9.14","=="
"10.12.21.10","<="

but I need output like below where == should be match and >= is not match

"IP adress","IP Name","Status"
"10.15.9.8","one","match"
"10.15.9.6","two","match"
"10.15.9.14","three","match"
"10.12.21.10","four","Not macth"

Can you please let me know how can I do that

Body:
Here is how you can approach the problem, since you're only interested in knowing if an IP in CSV1 exists in CSV2, using a Hashset should be more efficient than Compare-Object. As for what you're doing wrong, on your initial code, you're running a line-by-line comparison hence even if an IP exists in both Csvs, if they're not on the same line / row your condition will be $false.

$CSV1 = Import-Csv -Path 'C:\path\to\csv1.csv'
$reference = [System.Collections.Generic.HashSet[string]]::new(
    [string[]](Import-Csv -Path 'C:\path\to\csv2.csv').'IP address'.ForEach('Trim')
)

$results = foreach($line in $Csv1)
{
    $ip = $line.'Ip address'.Trim()
    [PSCustomObject]@{
        Value   = $ip
        IPName  = $line.IPName
        Results = ('Not Match', 'Match')[$reference.Contains($ip)]
    }
}

$results | Export-Csv -Path "E:\File.csv" -NoTypeInformation


问:
TypeError: Mean() missing 1 required positional argument: 'data'
I'm trying to program a basic mean calculator using classes. However, I'm getting the error

```<code>TypeError: Mean() missing 1 required positional argument: 'data'
</code>```

I have two files: one which contains the class with the mean function and then one which calls it, and that is when I'm getting the error. My code is:

```<code>class Statistics:
    def __init__(self,mean_x,mean_y,var,covar):
        self.mean_x=mean_x
        self.mean_y=mean_y
        self.var=var
        self.covar=covar

    def Mean(self,data):
        return sum(data)/float(len(data))
</code>```

And the code which throws the error is:

```<code>from Statistics import Statistics
X=(0,1,3,5)
mean_x=Statistics.Mean(X)
print(mean_x)
</code>```

答:
You define the instance method, but there is no instance.

Also, it is better to change the 'Mean' to 'mean'.

Body:
I'm trying to program a basic mean calculator using classes. However, I'm getting the error

TypeError: Mean() missing 1 required positional argument: 'data'

I have two files: one which contains the class with the mean function and then one which calls it, and that is when I'm getting the error. My code is:

class Statistics:
    def __init__(self,mean_x,mean_y,var,covar):
        self.mean_x=mean_x
        self.mean_y=mean_y
        self.var=var
        self.covar=covar

    def Mean(self,data):
        return sum(data)/float(len(data))

And the code which throws the error is:

from Statistics import Statistics
X=(0,1,3,5)
mean_x=Statistics.Mean(X)
print(mean_x)


问:
Java: Rationale of the Object class not being declared abstract
Why wasn't the java.lang.Object class declared to be abstract ?

Surely for an Object to be useful it needs added state or behaviour, an Object class is an abstraction, and as such it should have been declared abstract ...  why did they choose not to ?

答:
An Object is useful even if it does not have any state or behaviour specific to it.

One example would be its use as a generic guard that's used for synchronization:

```<code>public class Example {
    private final Object o = new Object();

    public void doSomething() {
        synchronized (o) {
            // do possibly dangerous stuff
        }
    }
}
</code>```

While this class is a bit simple in its implementation (it isn't evident here why it's useful to have an explicit object, you could just declare the method synchronized) there are several cases where this is really useful.

OwnerDisplayName: Ande Turner

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ande

Body:
An Object is useful even if it does not have any state or behaviour specific to it.

One example would be its use as a generic guard that's used for synchronization:

public class Example {
    private final Object o = new Object();

    public void doSomething() {
        synchronized (o) {
            // do possibly dangerous stuff
        }
    }
}

While this class is a bit simple in its implementation (it isn't evident here why it's useful to have an explicit object, you could just declare the method synchronized) there are several cases where this is really useful.

OwnerDisplayName: andri

LastEditorDisplayName: mmyers


问:
What are these comment-like lines in ocamllex generated .ml?
When I generate an .ml file with ocamllex it has a bunch of lines like:

# 21 "lib/myproj/example.ml"
```

These look like comments, except AFAIK comments in OCaml are like (* this is a comment *)

VS Code doesn't seem to treat them as comments either.

What syntax is this? What do they do?

答:
These are "line number directives":

https://ocaml.org/manual/lex.html#sss:lex-linedir

Preprocessors that generate OCaml source code can insert line number directives in their output so that error messages produced by the compiler contain line numbers and file names referring to the source file before preprocessing, instead of after preprocessing.

Body:
When I generate an .ml file with ocamllex it has a bunch of lines like:

# 21 "lib/myproj/example.ml"

These look like comments, except AFAIK comments in OCaml are like (* this is a comment *)

VS Code doesn't seem to treat them as comments either.

What syntax is this? What do they do?


问:
importing jax fails on mac with m1 chip
For python 3.8.8 and using the new mac air (with the m1 chip), in jupyter notebooks and in python terminal, import jax raises this error

```<code>Python 3.8.8 (default, Apr 13 2021, 12:59:45)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import jax
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/steve/Documents/code/jax/jax/__init__.py", line 37, in <module>
    from . import config as _config_module
  File "/Users/steve/Documents/code/jax/jax/config.py", line 18, in <module>
    from jax._src.config import config
  File "/Users/steve/Documents/code/jax/jax/_src/config.py", line 26, in <module>
    from jax import lib
  File "/Users/steve/Documents/code/jax/jax/lib/__init__.py", line 63, in <module>
    cpu_feature_guard.check_cpu_features()
RuntimeError: This version of jaxlib was built using AVX instructions, which your CPU and/or operating system do not support. You may be able work around this issue by building jaxlib from source.
</code>```

I suspect it occurs because of the m1 chip.

I tried using jax with pip install jax, then I built it from source as suggested by the comment, by cloning their repository and following the instructions given here, but the same error message shows.

答:
I had a similar problem. Since I already had Anaconda installed and didn't want to clutter up my space with Anaconda + miniconda + homebrew versions of python and package management and whatever, I hunted around for a simple solution. What ended up working for me was first uninstalling jax and jaxlib and then installing jax and jaxlib via conda-forge directly:

```<code>pip uninstall jax jaxlib
conda install -c conda-forge jaxlib
conda install -c conda-forge jax
</code>```

Title: importing jax fails on mac with m1 chip

Body:
For python 3.8.8 and using the new mac air (with the m1 chip), in jupyter notebooks and in python terminal, import jax raises this error

Python 3.8.8 (default, Apr 13 2021, 12:59:45)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import jax
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/steve/Documents/code/jax/jax/__init__.py", line 37, in <module>
    from . import config as _config_module
  File "/Users/steve/Documents/code/jax/jax/config.py", line 18, in <module>
    from jax._src.config import config
  File "/Users/steve/Documents/code/jax/jax/_src/config.py", line 26, in <module>
    from jax import lib
  File "/Users/steve/Documents/code/jax/jax/lib/__init__.py", line 63, in <module>
    cpu_feature_guard.check_cpu_features()
RuntimeError: This version of jaxlib was built using AVX instructions, which your CPU and/or operating system do not support. You may be able work around this issue by building jaxlib from source.

I suspect it occurs because of the m1 chip.

I tried using jax with pip install jax, then I built it from source as suggested by the comment, by cloning their repository and following the instructions given here, but the same error message shows.

Body:
I had a similar problem. Since I already had Anaconda installed and didn't want to clutter up my space with Anaconda + miniconda + homebrew versions of python and package management and whatever, I hunted around for a simple solution. What ended up working for me was first uninstalling jax and jaxlib and then installing jax and jaxlib via conda-forge directly:

pip uninstall jax jaxlib
conda install -c conda-forge jaxlib
conda install -c conda-forge jax


问:
re.sub change the direction of the replaced Persian/Arabic content
Here is my code:

import re

CUSTOMIZED_SUB_PATTERN = "\{{\{{(?:\s)*{tag_key}(?:\s)*\|(?:\s)*([^|}}]+)(?:\s)*\}}\}}"
pattern = re.compile(CUSTOMIZED_SUB_PATTERN.format(tag_key='name'))
title = "عزیز {{ name | default value 1}} سلام"
re.sub(pattern, "محمد", title)
```
<p><strong>The output:</strong></p>
```'عزیز محمد سلام'
```
<p><strong>But what I want is:</strong></p>
```'سلام محمد عزیز'
```

So as you can see the direction of the sentence has been changed over the replacement.

Question:
How can I fix this issue?

答:
```<code>from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import arabic_reshaper
from bidi.algorithm import get_display

pdfmetrics.registerFont(TTFont('Scheherazade', 'Janna LT Bold.ttf'))

page = canvas.Canvas("test.pdf", pagesize=A4)
page.setFont('Scheherazade', 12)
text_to_be_reshaped = 'اللغة العربية رائعة'
reshaped_text = arabic_reshaper.reshape(text_to_be_reshaped)
bidi_text = get_display(reshaped_text)
page.drawString(10*mm, 267*mm, bidi_text)
page.showPage()
page.save()
</code>```

Body:
Here is my code:

import re

CUSTOMIZED_SUB_PATTERN = "\{{\{{(?:\s)*{tag_key}(?:\s)*\|(?:\s)*([^|}}]+)(?:\s)*\}}\}}"
pattern = re.compile(CUSTOMIZED_SUB_PATTERN.format(tag_key='name'))
title = "عزیز {{ name | default value 1}} سلام"
re.sub(pattern, "محمد", title)

The output:

'عزیز محمد سلام'

But what I want is:

'سلام محمد عزیز'

So as you can see the direction of the sentence has been changed over the replacement.

Question:
How can I fix this issue?


问:
Jenkins active (exited)
For some reason Jenkins stops working all the time and I have to restart jenkins service to make it work again. Every time this happens service is "active (exited)" but there is nothing in the logs. I use Ubuntu 16.04.

```<code>root@laran:~# service jenkins status
    ● jenkins.service - LSB: Start Jenkins at boot time
       Loaded: loaded (/etc/init.d/jenkins; bad; vendor preset: enabled)
       Active: active (exited) since Sun 2017-03-05 06:09:46 EST; 6min ago
         Docs: man:systemd-sysv-generator(8)
      Process: 25459 ExecStop=/etc/init.d/jenkins stop (code=exited, status=0/SUCCESS)
      Process: 25477 ExecStart=/etc/init.d/jenkins start (code=exited, status=0/SUCCESS)
</code>```

答:
In my case, I mistakenly deleted the log folder "/var/log/jenkins". Hence jenkins was trying to find the folder and was unable to find it and hence was not able to start.

Creating the folder again and assigning the permission to jenkins user solved my problem.

Command to assign permission to jenkins user:

chown -R jenkins:jenkins /var/log/jenkins

ContentLicense: CC BY-SA 3.0

Title: Jenkins active (exited)

Body:
For some reason Jenkins stops working all the time and I have to restart jenkins service to make it work again. Every time this happens service is "active (exited)" but there is nothing in the logs. I use Ubuntu 16.04.

root@laran:~# service jenkins status
    ● jenkins.service - LSB: Start Jenkins at boot time
       Loaded: loaded (/etc/init.d/jenkins; bad; vendor preset: enabled)
       Active: active (exited) since Sun 2017-03-05 06:09:46 EST; 6min ago
         Docs: man:systemd-sysv-generator(8)
      Process: 25459 ExecStop=/etc/init.d/jenkins stop (code=exited, status=0/SUCCESS)
      Process: 25477 ExecStart=/etc/init.d/jenkins start (code=exited, status=0/SUCCESS)


问:
What is causing the '403 Forbidden error' in my Apache2 server? And how can I fix it? The available fixes on the web are not working for me
A little bit of context to my problem... I'm trying to deploy my django application following a tutorial (https://www.youtube.com/watch?v=Sa_kQheCnds) which uses linode to setup a linux apache server, and after following the steps, it always results in the same error, 403 Forbidden: You don't have permission to access this resource. I've followed the steps in this guide roughly 6 times now and I've determined that I'm definitely not doing anything the guy didn't do.

Something worth mentioning is that in the tutorial, Ubuntu 18.10 is being used, however I don't have Ubuntu 18.10 available, so I've tried it using Ubuntu 18.04, 20.04 and 21.10.

In my sixth and latest attempt, I am using Ubuntu 21.10

I've also tried running the server with DEBUG=True to see if I can get a little more insight on the error, but it just displays the following:

The tutorial is very long so I've broken down every single step in this post.

The steps I had to follow are:

(everything done in the Windows Linux Bash shell)

Creating Linode and analizing Ip Address and SSH Credentials I got

Root Connection to the Server

ssh into the server for the first time

Installing Software Updates

Running the command sudo apt-get update && apt-get upgrade

Setting Host Name

hostnamectl set-hostname SERVER_NAME

Then checking if it was rightfully executed with hostname

Setting Host File

nano /etc/hosts and then adding the IP address and server name to the file.

Adding Limited User

The guy in the video said it's not good practice to use root user because it's easy to mess things up like that so we created a limited user with adduser USER_NAME and then gave it sudo permissions with adduser USER_NAME sudo

Setting Up SSH Key Based Authentication

In my local machine's bash shell:
ssh keygen -b 4096
And deposit that file into my home folder, after that I copy that file over to my server with
scp ~/.ssh/id_rsa.pub user@serverip:~/.ssh/authorized_keys
then lasty confirming it was done correcty in the server with
ls .ssh

Setting Permissions for SSH Directory

Attach certain permision like
sudo chmod 700 ~/.ssh/
and
sudo chmod 600 ~/.ssh/*

Forbiding Root Login & Password Authentication

sudo nano /etc/ssh/sshh_config
to forbit #PermitRootLogin and #PasswordAuthentification
and then restart with
sudo systemctl restart sshd

Setting Up a Firewall

First, I install Uncomplicated Firewall with
sudo apt-get install ufw
and then I do the following commands:
sudo ufw default allow outgoing , sudo ufw default deny incoming , sudo ufw allow ssh and sudo ufw allow 8000.
After that, I enable the firewall with sudo ufw enable

Generating requirements.txt File

Here I actually did it a bit different that in the video. I open my VSCODE environment for the project in question, and then I run a pip freeze in the terminal to see if the dependencies are correct, if they are I write the requirements with pip freeze > requirements.txt

Copying Django Application on to the Webserver

This step is pretty straightforward. Just scp -r /folder/ user@serverip:~/ and that way the folder project is copied into the web server.

Creating Virtual Environment on the Server

First run a sudo apt-get install python3-pip and then pip install sudo apt-get install python3-venv. Once that's done, to create my virtual environment I do python3 -m venv django_project/venv and lastly I activate it by cding into the project's folder and then source venv/bin/activate.

Installing Dependencies

With my virtual environment running I run a pip install -r requirements.txt

Changing Django Settings for Testing the Application on Django Server

Inside the project's folder: sudo nano django_project/settings.py and add my server's IP to the allowed hosts list, and add a STATIC_ROOT directory.

Collecting Static Files

python manage.py collectstatic
Which could collect about 120 static files, but my project is a somewhat different from the on in the video because I added way more features so it collects about 137 files (in case these details are needed)

Testing Application

python manage.py runserver 0.0.0.0:8000 and then test to see if there is any problems, there are not (minus some variables I forgot to add because they were in my PC's environment variables) so I move on to the next step.

Installing Apache & ModWSGI

sudo apt-get install apache2, sudo apt-get install libapache2-mod-wsgi-py3.

Configuring Apache Webserver

Then move into the apache configuration folder cd /etc/apache2/sites-available/ and create a new configuration file based off the default one with sudo cp 000-default.conf django_project.conf, and then I edit with sudo nano django_project.conf it and add the following things to it: https://github.com/CoreyMSchafer/code_snippets/blob/master/Django_Blog/snippets/django_project.conf

Enabling Site Through Apache

Run the following commands:
sudo a2ensite django_project , sudo a2dissite 000-default.conf

Setting Up File Permissions

Run the following commands:
sudo chown :www-date django_project/db.sqlite3 , sudo chmod 664 django_project/db.sqlite3 and sudo chown :www-data django_project/. Then sudo chown -R :www-data django_project/media/andsudo chmod -R django_project/media```

Creating Configuration File for Hiding Sensitive Information

I won't detail this process, I just make a .json file with some secret information like the SECRET_KEY and the email and password.

Updating Project Settings File

I delete the sentitive information from the settings.py of the project, and instead add those with the .json file (like if it were an environment variable).

Allowing http Traffic

Run the following commands:
sudo ufw delete allow 8000, and sudo ufw allow http/tcp.

Restarting the Server & Running the Site

sudo service apache2 restart

Please, I'd appreciate any kind of help. I have to fix this error for a school project and I can't find solutions that actually fix it. I've read in some forums that I just needed to change certain permissions again, I did that and still the same error. It's really driving me crazy.

答: I think the Forbidden is returned as Apache2 user (www-data) cant reach your HOME folder, move everything to another path like /data or /var/www and give www-data a rx access through the chmod command.</p>


问:
Invoice List Running Balance based on date and Account
I'm using Excel 2010 and have made a UserForm that Displays a complete list of Invoices from Worksheets("InvoiceListIncome") using a ListBox control, the Worksheet has 13 Columns and Thousands of rows, an example image below;

The problem I'm having is the Balance Row Range("InvoiceListIncome_Balance")" displays the balance of each Invoice individual, what I need is a running balance starting from the first invoice Range("InvoiceListIncome_Date") so with each Transaction it Adds up the Current + all previous invoices for that account.

The Macro I'm currently using is;

```<code>Range("InvoiceListIncome_Balance").FormulaR1C1 = "=SUM(RC[-1])-SUM(RC[-2])"
</code>```

which simply subtracts whats Paid in Column F from Item Price in Column G, but I cant seem to figure out how to add all previous balances by date, I can either get it to Sum the complete Range with the Customers account as the criteria or just the activerow.

I have been running circles trying to figure this out for days now, any help would be muchly appreciated, thanks.

Here is an example of what I need;

答:
You want a running total, so you want to incorporate the balance of row (n-1) when calculating the balance for row n.

Based on your 1st picture, make the following changes:

formula in G2: =F2-E2

formula in G3: =G2+F3-E3

copy formula from G3 down to the end of the list; the last value is your current balance

edit

sorry ... I seem to have overlooked the break-on-account condition. Well that makes it even easier as there is only one formula you need all the way down ....

to break on customer (provided the customer column is sorted) you would use the following formula

formula in G2: =IF(A2=A1,G1+F2-E2,F2-E2)

copy formula from G2 down to the end of the list

(if this.account = previous.account then calculate.running.total else create.new.balance)

This will work as long as your first customers' name is <> "Account" :-)

Body:
I'm using Excel 2010 and have made a UserForm that Displays a complete list of Invoices from Worksheets("InvoiceListIncome") using a ListBox control, the Worksheet has 13 Columns and Thousands of rows, an example image below;

The problem I'm having is the Balance Row Range("InvoiceListIncome_Balance")" displays the balance of each Invoice individual, what I need is a running balance starting from the first invoice Range("InvoiceListIncome_Date") so with each Transaction it Adds up the Current + all previous invoices for that account.

The Macro I'm currently using is;

Range("InvoiceListIncome_Balance").FormulaR1C1 = "=SUM(RC[-1])-SUM(RC[-2])"

which simply subtracts whats Paid in Column F from Item Price in Column G, but I cant seem to figure out how to add all previous balances by date, I can either get it to Sum the complete Range with the Customers account as the criteria or just the activerow.

I have been running circles trying to figure this out for days now, any help would be muchly appreciated, thanks.

Here is an example of what I need;


问:
Rails: How to change progress color under address bar
```<code><form action="/result" method="GET">
  <button type="submit"></button>
</form>
</code>```

When I click a submit button with above code, the browser shows blue progress bar under address bar .

I wanna change this default blue color into others.
How can I do it?

答:
The blue progress bar is present because you might have enabled Turbolinks in your application. To change the color or height of the progress bar you can simply write a CSS. like so</p>
```<code>.turbolinks-progress-bar {
  height: 5px;
  background-color: red;
}

</code>```

Body:
<form action="/result" method="GET">
  <button type="submit"></button>
</form>

When I click a submit button with above code, the browser shows blue progress bar under address bar .

I wanna change this default blue color into others.
How can I do it?

Body:
The blue progress bar is present because you might have enabled Turbolinks in your application. To change the color or height of the progress bar you can simply write a CSS. like so

.turbolinks-progress-bar {
  height: 5px;
  background-color: red;
}


问:
paste on top of the row instead of the bottom row
at the moment I have a sheet that has a script that is time triggered, the script at the end of the day will copy sheets at the bottom of the target sheet, everytime I am trying to do targetSheet.getrange(1,1) + 1; it's not  converting range to int. can someone please help?</p>
```<code>   function copyData() {

  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');

  let sourceRange = sourceSheet.getDataRange();
  let sourceValues = sourceRange.getValues();

  let rowCount = sourceValues.length;
  let columnCount = sourceValues[0].length;

  let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
  let lastrowCount = targetSheet.getLastRow() + 1;

  let targetRange = targetSheet.getRange(lastrowCount,1, rowCount,columnCount);

  targetRange.setValues(sourceValues);
}
</code>```

答:
Is that what you mean? Paste values on the top of the sheet.</p>
```<code>function copyData() {

  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');

  let sourceRange = sourceSheet.getDataRange();
  let sourceValues = sourceRange.getValues();

  let rowCount = sourceValues.length;
  let columnCount = sourceValues[0].length;

  let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
  targetSheet.insertRows(1,sourceValues.length);

  let targetRange = targetSheet.getRange(1,1,sourceValues.length,sourceValues[0].length);

  targetRange.setValues(sourceValues);
}
</code>```

Body:
at the moment I have a sheet that has a script that is time triggered, the script at the end of the day will copy sheets at the bottom of the target sheet, everytime I am trying to do targetSheet.getrange(1,1) + 1; it's not  converting range to int. can someone please help?

   function copyData() {

  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');

  let sourceRange = sourceSheet.getDataRange();
  let sourceValues = sourceRange.getValues();

  let rowCount = sourceValues.length;
  let columnCount = sourceValues[0].length;

  let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
  let lastrowCount = targetSheet.getLastRow() + 1;

  let targetRange = targetSheet.getRange(lastrowCount,1, rowCount,columnCount);

  targetRange.setValues(sourceValues);
}

Body:
Is that what you mean? Paste values on the top of the sheet.

function copyData() {

  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');

  let sourceRange = sourceSheet.getDataRange();
  let sourceValues = sourceRange.getValues();

  let rowCount = sourceValues.length;
  let columnCount = sourceValues[0].length;

  let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
  targetSheet.insertRows(1,sourceValues.length);

  let targetRange = targetSheet.getRange(1,1,sourceValues.length,sourceValues[0].length);

  targetRange.setValues(sourceValues);
}


问:
Getting attribute of jQuery Dropzone DIV
I have dropzone (v3.7.1) divs in each of my bootstrap tabs.

How can I upload all files in all dropzones only after clicking on submit button (not using form for each dropzone)? When I set autoProcessQueue to false and try to attach listener, an error saying unable to attach an event to undefined shows up...

How do I get attributes of a dropzone object e.g. rel="6" of the first dropzone? Attempts to use this.attr('rel') / $(this).attr('rel') results in 'undefined'...

HTML

```<code><form class="my-form" method="post">
    <input type="text" name="form-input-1" id="form-input-1" />
    <input type="text" name="form-input-2" id="form-input-2" />

    <div class="tab-content">
        <div class="tab-pane active" id="ic_6">
            <h3>Overview</h3>
            <div rel="6" class="dropzone" id="my-dropzone"></div>
        </div>
        <div class="tab-pane" id="ic_1">
            <h3>Living Room</h3>
            <div rel="1" class="dropzone" id="my-dropzone"></div>
        </div>
        <div class="tab-pane" id="ic_2">
            <h3>Kitchen</h3>
            <div rel="2" class="dropzone" id="my-dropzone"></div>
        </div>
        <div class="tab-pane" id="ic_3">
            <h3>Bathroom</h3>
            <div rel="3" class="dropzone" id="my-dropzone"></div>
        </div>
        <div class="tab-pane" id="ic_4">
            <h3>Bedroom</h3>
            <div rel="4" class="dropzone" id="my-dropzone"></div>
        </div>
        <div class="tab-pane" id="ic_5">
            <h3>Outdoors</h3>
            <div rel="5" class="dropzone" id="my-dropzone"></div>
        </div>
    </div>

    <button type="submit">Submit</button>
</form>
</code>```

JS

```<code>Dropzone.options.myDropzone = {
    url: "upload.php",
    maxFilesize: 2, // MB
    addRemoveLinks: true,
    acceptedFiles: "image/*",
    accept: function(file, done) {
        console.log("uploaded");
        done();
    },
    init: function() {
        this.on("addedfile", function(file) {
            //== divider ==//
            var dividerElement = Dropzone.createElement("<div> </div>");
            file.previewElement.appendChild(dividerElement);

            //== caption input : still trying to figure capturing this ==//
            var captionInput = Dropzone.createElement("<input type='text' name='caption' maxlength='50' placeholder='Enter a caption' />");
            file.previewElement.appendChild(captionInput);
        });

        this.on("removedfile", function(file) {
            $.ajax({
                url: "delete_temp_files.php",
                type: "POST",
                data: { filename: file.name }
            });
        });
    }
}
</code>```

答:
I know this is an old post, but the solution to accessing attributes on the original element is
console.log($($(this)[0].element).attr("rel"));</p>

Body:
I have dropzone (v3.7.1) divs in each of my bootstrap tabs.

How can I upload all files in all dropzones only after clicking on submit button (not using form for each dropzone)? When I set autoProcessQueue to false and try to attach listener, an error saying unable to attach an event to undefined shows up...

How do I get attributes of a dropzone object e.g. rel="6" of the first dropzone? Attempts to use this.attr('rel') / $(this).attr('rel') results in 'undefined'...

HTML

<form class="my-form" method="post">
    <input type="text" name="form-input-1" id="form-input-1" />
    <input type="text" name="form-input-2" id="form-input-2" />

Overview

Living Room

Kitchen

Bathroom

Bedroom

Outdoors

    <button type="submit">Submit</button>
</form>

JS

Dropzone.options.myDropzone = {
    url: "upload.php",
    maxFilesize: 2, // MB
    addRemoveLinks: true,
    acceptedFiles: "image/*",
    accept: function(file, done) {
        console.log("uploaded");
        done();
    },
    init: function() {
        this.on("addedfile", function(file) {
            //== divider ==//
            var dividerElement = Dropzone.createElement("

");
            file.previewElement.appendChild(dividerElement);

            //== caption input : still trying to figure capturing this ==//
            var captionInput = Dropzone.createElement("<input type='text' name='caption' maxlength='50' placeholder='Enter a caption' />");
            file.previewElement.appendChild(captionInput);
        });

        this.on("removedfile", function(file) {
            $.ajax({
                url: "delete_temp_files.php",
                type: "POST",
                data: { filename: file.name }
            });
        });
    }
}


问:
Delete a node(or more nodes) between others in a linked list C
Hi I'm creating a program for school where I have to:

Create structures

Create functions to print my linked list

Create functions to insert an element to the bottom of the list

Delete duplicate elements.

I created all a part the last one step(delete function). Can you help me to know what is the right way? This is my code:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/*STRUCTURE*/
typedef struct punto {
    int x;
    int y;
} PUNTO;

typedef struct quadrato {
    PUNTO v;
    int lato;
} QUADRATO;

typedef struct nodo {
    QUADRATO q;
    struct nodo *next;
} NODO;

/*PRINT LIST*/
void stampaQuadrato(QUADRATO q) {
    printf("The square has the side equal to %d and coordinates of the lower left vertex (%d,%d)\n", q.lato, q.v.x, q.v.y);
}

void stampaLista(NODO *head) {
    if(head->next==NULL) {
        printf("List empty!\n");
    } else {
        while(head->next != NULL) {
            head = head->next;
            stampaQuadrato(head->q);
        }
    }
}

/*ADD*/
QUADRATO creaQuadrato() {

    QUADRATO nuovo;

    printf("Side measurement: ");
    scanf("%d", &nuovo.lato);
    printf("\n");
    printf("Coordinates of the lower left vertex\n");
    printf("x: ");
    scanf("%d", &nuovo.v.x);
    printf("\n");
    printf("y: ");
    scanf("%d", &nuovo.v.y);
    printf("\n");

    return nuovo;

}

void insert(NODO *head) {
    NODO* nuovoNodo = malloc(sizeof(NODO));
    nuovoNodo->q = creaQuadrato();
    if(head==NULL) {
        head = head->next;
        head = nuovoNodo;
    } else {
        while(head->next != NULL) {
            head = head->next;
        }
        head->next = nuovoNodo;
    }
}

/*DELETE*/
void deleteDuplicates(NODO *head) {
    if(head==NULL) {
        printf("There are no element in the list!\n");
    } else {
        while(head->next != NULL) {
            if(head->q.lato == head->next->q.lato &&
               head->q.v.x == head->next->q.v.x &&
               head->q.v.y == head->next->q.v.y) {
                   NODO* nodoQuad = head->next;
                   head->next = nodoQuad->next;
                   //head->next = head->next->next;
                   free(nodoQuad);
                   printf("Element deleted!\n");
               } else {
                   head = head->next;
               }
        }
    }
}

int main() {
    NODO *head = malloc(sizeof(NODO));
    head->next = NULL;
    int scelta = -1;

    while(scelta != 0) {
        printf("Choose one\n");
        printf("Press 1 --> See list\n");
        printf("Press 2 --> Insert new square(quadrato)\n");
        printf("Press 3 --> Delete duplicates\n");
        printf("Press 0 --> Stop program\n");
        scanf("%d", &scelta);

        if(scelta==1) {
            stampaLista(head);
        }
        else if(scelta==2) {
            insert(head);
        }
        else if(scelta==3) {
            deleteDuplicates(head);
        }
        else if(scelta==0) {
            printf("See you soon ;)\n");
        }

        }

}
</code>```

答:
You can do something like this:

```<code>    /* removeDuplicate() will remove duplicate nodes from the list */
void removeDuplicate(NODO *self) {
    /* Node current will point to head  */
    NODO *current = self->head;
    NODO *index = NULL;
    NODO *temp = NULL;

    if(self->head == NULL) {
        return;
    } else {
        while(current != None) {
            /* Node temp will point to previous node to index */
            temp = current;
            /* Index will point to node next to current */
            index = current->next;

            while(index != NULL) {
                /* If current node's data is equal to index node's data */
                if(current->data == index->data) {
                    /* Here, index node is pointing to the node which is duplicate of current node */
                    /* Skips the duplicate node by pointing to next node */
                    temp->next = index->next;
                } else {
                    /* Temp will point to the previous node of the index. */
                    temp = index;
                }
                index = index->next;
            }
            current = current->next;
        }
    }
}
</code>```

You need to write similar as above for your code's needs.

Body:
Hi I'm creating a program for school where I have to:

Create structures

Create functions to print my linked list

Create functions to insert an element to the bottom of the list

Delete duplicate elements.

I created all a part the last one step(delete function). Can you help me to know what is the right way? This is my code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/*STRUCTURE*/
typedef struct punto {
    int x;
    int y;
} PUNTO;

typedef struct quadrato {
    PUNTO v;
    int lato;
} QUADRATO;

typedef struct nodo {
    QUADRATO q;
    struct nodo *next;
} NODO;

/*PRINT LIST*/
void stampaQuadrato(QUADRATO q) {
    printf("The square has the side equal to %d and coordinates of the lower left vertex (%d,%d)\n", q.lato, q.v.x, q.v.y);
}

void stampaLista(NODO *head) {
    if(head->next==NULL) {
        printf("List empty!\n");
    } else {
        while(head->next != NULL) {
            head = head->next;
            stampaQuadrato(head->q);
        }
    }
}

/*ADD*/
QUADRATO creaQuadrato() {

    QUADRATO nuovo;

    printf("Side measurement: ");
    scanf("%d", &nuovo.lato);
    printf("\n");
    printf("Coordinates of the lower left vertex\n");
    printf("x: ");
    scanf("%d", &nuovo.v.x);
    printf("\n");
    printf("y: ");
    scanf("%d", &nuovo.v.y);
    printf("\n");

    return nuovo;

}

void insert(NODO *head) {
    NODO* nuovoNodo = malloc(sizeof(NODO));
    nuovoNodo->q = creaQuadrato();
    if(head==NULL) {
        head = head->next;
        head = nuovoNodo;
    } else {
        while(head->next != NULL) {
            head = head->next;
        }
        head->next = nuovoNodo;
    }
}

/*DELETE*/
void deleteDuplicates(NODO *head) {
    if(head==NULL) {
        printf("There are no element in the list!\n");
    } else {
        while(head->next != NULL) {
            if(head->q.lato == head->next->q.lato &&
               head->q.v.x == head->next->q.v.x &&
               head->q.v.y == head->next->q.v.y) {
                   NODO* nodoQuad = head->next;
                   head->next = nodoQuad->next;
                   //head->next = head->next->next;
                   free(nodoQuad);
                   printf("Element deleted!\n");
               } else {
                   head = head->next;
               }
        }
    }
}

int main() {
    NODO *head = malloc(sizeof(NODO));
    head->next = NULL;
    int scelta = -1;

    while(scelta != 0) {
        printf("Choose one\n");
        printf("Press 1 --> See list\n");
        printf("Press 2 --> Insert new square(quadrato)\n");
        printf("Press 3 --> Delete duplicates\n");
        printf("Press 0 --> Stop program\n");
        scanf("%d", &scelta);

        if(scelta==1) {
            stampaLista(head);
        }
        else if(scelta==2) {
            insert(head);
        }
        else if(scelta==3) {
            deleteDuplicates(head);
        }
        else if(scelta==0) {
            printf("See you soon ;)\n");
        }

        }

}

Body:
You can do something like this:

    /* removeDuplicate() will remove duplicate nodes from the list */
void removeDuplicate(NODO *self) {
    /* Node current will point to head  */
    NODO *current = self->head;
    NODO *index = NULL;
    NODO *temp = NULL;

    if(self->head == NULL) {
        return;
    } else {
        while(current != None) {
            /* Node temp will point to previous node to index */
            temp = current;
            /* Index will point to node next to current */
            index = current->next;

            while(index != NULL) {
                /* If current node's data is equal to index node's data */
                if(current->data == index->data) {
                    /* Here, index node is pointing to the node which is duplicate of current node */
                    /* Skips the duplicate node by pointing to next node */
                    temp->next = index->next;
                } else {
                    /* Temp will point to the previous node of the index. */
                    temp = index;
                }
                index = index->next;
            }
            current = current->next;
        }
    }
}

You need to write similar as above for your code's needs.


问:
Making animation on matplotlib of graph with Networkx efficiently
I am trying to animate a graph whose edges widths and color change over time. My code works, but it is extremely slow. I imagine there are more efficient implementations.

```<code>def minimal_graph(datas, pos):
    frames = len(datas[0])
    fig, axes = plt.subplots(1, 2)
    axes = axes.flatten()
    for j, dat in enumerate(datas):
        G = nx.from_numpy_matrix(dat[0])
        nx.draw(G, pos, ax=axes[j])
    def update(it, data, pos, ax):
        print(it)
        for i, dat in enumerate(data):
            # This is the problematic line, because I clear the axis hence
            # everything has to be drawn from scratch every time.
            ax[i].clear()
            G = nx.from_numpy_matrix(dat[it])
            edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items())
            nx.draw(
                G,
                pos,
                node_color='#24FF00',
                edgelist=edges,
                edge_color=weights,
                width=weights,
                edge_vmin=-5,
                edge_vmax=5,
                ax=ax[i])
    ani = animation.FuncAnimation(fig, update, frames=frames, fargs=(
        datas, pos, axes), interval=100)
    ani.save('temp/graphs.mp4')
    plt.close()

dataset1 = []
dataset2 = []
for i in range(100):
    arr1 = np.random.rand(400, 400)
    arr2 = np.random.rand(400, 400)
    dataset1.append(arr1)
    dataset2.append(arr2)

datasets = [dataset1, dataset2]
G = nx.from_numpy_matrix(dataset1[0])
pos = nx.spring_layout(G)

minimal_graph(datasets, pos)
</code>```

As pointed out in the code, the problem is that at every frame I redraw the graph from "scratch". When using animations in matplotlib, I usually try to create lines and use the function '''line.set_data()''', which I know is a lot faster. It's just that I don't know how to set that for a graph using networkx. I found this question here, but they also use the same ax.clear and redraw everything for every frame. So, is there a way to set a line object to not redraw everything every iteration? For example, in my case the nodes are always the same (color, location, size stay the same).

答:
nx.draw does not expose the matplotlib artists used to represent the nodes and edges, so you cannot alter the properties of the artists in-place. Technically, if you plot the edges separately, you do get some collection of artists back but it is non-trivial to map the list of artists back to the edges, in particular if there are self-loops present.

If you are open for using other libraries to make the animation, I wrote netgraph some time ago. Crucially to your problem, it exposes all artists in easily to index forms such that their properties can be altered in-place and without redrawing everything else. netgraph accepts both full-rank matrices and networkx Graph objects as inputs so it should be simple to feed in your data.

Below is a simple example visualization. If I run the same script with with 400 nodes and 1000 edges, it needs 30 seconds to complete on my laptop.

```<code>#!/usr/bin/env python
"""
MWE for animating edges.
"""
import numpy as np
import matplotlib.pyplot as plt

from netgraph import Graph # pip install netgraph
from matplotlib.animation import FuncAnimation

total_nodes = 10
total_frames = 100

adjacency_matrix = np.random.rand(total_nodes, total_nodes) < 0.2
weight_matrix = 5 * np.random.randn(total_frames, total_nodes, total_nodes)

# precompute normed weight matrix, such that weights are on the interval [0, 1];
# weights can then be passed directly to matplotlib colormaps (which expect float on that interval)
vmin, vmax = -5, 5
weight_matrix[weight_matrix<vmin] = vmin
weight_matrix[weight_matrix>vmax] = vmax
weight_matrix -= vmin
weight_matrix /= vmax - vmin

cmap = plt.cm.RdGy

plt.ion()

fig, ax = plt.subplots()
g = Graph(adjacency_matrix, arrows=True, ax=ax)

def update(ii):
    artists = []
    for jj, kk in zip(*np.where(adjacency_matrix)):
        w = weight_matrix[ii, jj, kk]
        g.edge_artists[(jj, kk)].set_facecolor(cmap(w))
        g.edge_artists[(jj, kk)].width = 0.01 * np.abs(w-0.5) # assuming large negative edges should be wide, too
        g.edge_artists[(jj, kk)]._update_path()
        artists.append(g.edge_artists[(jj, kk)])
    return artists

animation = FuncAnimation(fig, update, frames=total_frames, interval=100, blit=True)
animation.save('edge_animation.mp4')
</code>```

Body:
I am trying to animate a graph whose edges widths and color change over time. My code works, but it is extremely slow. I imagine there are more efficient implementations.

def minimal_graph(datas, pos):
    frames = len(datas[0])
    fig, axes = plt.subplots(1, 2)
    axes = axes.flatten()
    for j, dat in enumerate(datas):
        G = nx.from_numpy_matrix(dat[0])
        nx.draw(G, pos, ax=axes[j])
    def update(it, data, pos, ax):
        print(it)
        for i, dat in enumerate(data):
            # This is the problematic line, because I clear the axis hence
            # everything has to be drawn from scratch every time.
            ax[i].clear()
            G = nx.from_numpy_matrix(dat[it])
            edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items())
            nx.draw(
                G,
                pos,
                node_color='#24FF00',
                edgelist=edges,
                edge_color=weights,
                width=weights,
                edge_vmin=-5,
                edge_vmax=5,
                ax=ax[i])
    ani = animation.FuncAnimation(fig, update, frames=frames, fargs=(
        datas, pos, axes), interval=100)
    ani.save('temp/graphs.mp4')
    plt.close()

dataset1 = []
dataset2 = []
for i in range(100):
    arr1 = np.random.rand(400, 400)
    arr2 = np.random.rand(400, 400)
    dataset1.append(arr1)
    dataset2.append(arr2)

datasets = [dataset1, dataset2]
G = nx.from_numpy_matrix(dataset1[0])
pos = nx.spring_layout(G)

minimal_graph(datasets, pos)

As pointed out in the code, the problem is that at every frame I redraw the graph from "scratch". When using animations in matplotlib, I usually try to create lines and use the function '''line.set_data()''', which I know is a lot faster. It's just that I don't know how to set that for a graph using networkx. I found this question here, but they also use the same ax.clear and redraw everything for every frame. So, is there a way to set a line object to not redraw everything every iteration? For example, in my case the nodes are always the same (color, location, size stay the same).

Body:
nx.draw does not expose the matplotlib artists used to represent the nodes and edges, so you cannot alter the properties of the artists in-place. Technically, if you plot the edges separately, you do get some collection of artists back but it is non-trivial to map the list of artists back to the edges, in particular if there are self-loops present.

If you are open for using other libraries to make the animation, I wrote netgraph some time ago. Crucially to your problem, it exposes all artists in easily to index forms such that their properties can be altered in-place and without redrawing everything else. netgraph accepts both full-rank matrices and networkx Graph objects as inputs so it should be simple to feed in your data.

Below is a simple example visualization. If I run the same script with with 400 nodes and 1000 edges, it needs 30 seconds to complete on my laptop.

#!/usr/bin/env python
"""
MWE for animating edges.
"""
import numpy as np
import matplotlib.pyplot as plt

from netgraph import Graph # pip install netgraph
from matplotlib.animation import FuncAnimation

total_nodes = 10
total_frames = 100

adjacency_matrix = np.random.rand(total_nodes, total_nodes) < 0.2
weight_matrix = 5 * np.random.randn(total_frames, total_nodes, total_nodes)

# precompute normed weight matrix, such that weights are on the interval [0, 1];
# weights can then be passed directly to matplotlib colormaps (which expect float on that interval)
vmin, vmax = -5, 5
weight_matrix[weight_matrix<vmin] = vmin
weight_matrix[weight_matrix>vmax] = vmax
weight_matrix -= vmin
weight_matrix /= vmax - vmin

cmap = plt.cm.RdGy

plt.ion()

fig, ax = plt.subplots()
g = Graph(adjacency_matrix, arrows=True, ax=ax)

def update(ii):
    artists = []
    for jj, kk in zip(*np.where(adjacency_matrix)):
        w = weight_matrix[ii, jj, kk]
        g.edge_artists[(jj, kk)].set_facecolor(cmap(w))
        g.edge_artists[(jj, kk)].width = 0.01 * np.abs(w-0.5) # assuming large negative edges should be wide, too
        g.edge_artists[(jj, kk)]._update_path()
        artists.append(g.edge_artists[(jj, kk)])
    return artists

animation = FuncAnimation(fig, update, frames=total_frames, interval=100, blit=True)
animation.save('edge_animation.mp4')


问:
Pandas DataFrame merging with aggregation
Let's create 2 dataframes, df1 and df2:

```<code>import pandas as pd
df1 = pd.DataFrame([["A", "A", "B", "B", "C"], ["a1", "a2", "b1", "b2", "c1"], [10, 10, 20, 20, 30], [1, 5, 6, 3, 4]]).T
df2 = pd.DataFrame([["B", "B", "C", "F"], ["b1", "b3", "c1", "f2"], [30, 30, 40, 40], [8, 3, 5, 2]]).T
df1.columns = df2.columns = ["label1", "label2", "total", "count"]
</code>```

Please notice, "total" must be the same for each "label1"

I need to merge theses 2 dataframes following these rules :

All "count" with same "label2" are simply added. ex: in df1, b1=6, in df2, b1=8, when merged, b1=14

"total" with same "label1" are added (and must be the same for each "label1"). ex: in df1, all B=20, in df2, all B=30, when merged, all B=50

In df3, this is what I'm trying to get:

I think I should maybe use pandas.DataFrame.merge, 1 or 2 times, but I don't even understand how to aggregate data. Any clue is appreciated.

答:
Try this:

```<code>df3 = (
    pd.concat([df1, df2])
    .pipe(lambda x: (x.assign(total=x['label1'].map(x.groupby('label1')['total'].unique().apply(sum))))
    .groupby(['label1', 'label2'])
    .agg(total=('total', 'first'), count=('count', 'sum'))
    .reset_index()
)
</code>```

Output:

```<code>>>> df3
  label1 label2  total  count
0      A     a1     10      1
1      A     a2     10      5
2      B     b1     50     14
3      B     b2     50      3
4      B     b3     50      3
5      C     c1     70      9
6      F     f2     40      2
</code>```

Body:
Let's create 2 dataframes, df1 and df2:

import pandas as pd
df1 = pd.DataFrame([["A", "A", "B", "B", "C"], ["a1", "a2", "b1", "b2", "c1"], [10, 10, 20, 20, 30], [1, 5, 6, 3, 4]]).T
df2 = pd.DataFrame([["B", "B", "C", "F"], ["b1", "b3", "c1", "f2"], [30, 30, 40, 40], [8, 3, 5, 2]]).T
df1.columns = df2.columns = ["label1", "label2", "total", "count"]

Please notice, "total" must be the same for each "label1"

I need to merge theses 2 dataframes following these rules :

All "count" with same "label2" are simply added. ex: in df1, b1=6, in df2, b1=8, when merged, b1=14

"total" with same "label1" are added (and must be the same for each "label1"). ex: in df1, all B=20, in df2, all B=30, when merged, all B=50

In df3, this is what I'm trying to get:

I think I should maybe use pandas.DataFrame.merge, 1 or 2 times, but I don't even understand how to aggregate data. Any clue is appreciated.

Body:
Try this:

df3 = (
    pd.concat([df1, df2])
    .pipe(lambda x: (x.assign(total=x['label1'].map(x.groupby('label1')['total'].unique().apply(sum))))
    .groupby(['label1', 'label2'])
    .agg(total=('total', 'first'), count=('count', 'sum'))
    .reset_index()
)

Output:

>>> df3
  label1 label2  total  count
0      A     a1     10      1
1      A     a2     10      5
2      B     b1     50     14
3      B     b2     50      3
4      B     b3     50      3
5      C     c1     70      9
6      F     f2     40      2


问:
Null pointer exeception in ListAdapter
I want to display Data in List View but I got Error Null Pointer Exception run time in line

```<code>fList.setAdapter(la);
</code>```

My code is here List is complete printing in Log
Thanks

```<code>public class Forfattere extends Activity {
/** Called when the activity is first created. */
ArrayList<String> aList = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.forfattere);
    ListView fList = (ListView)findViewById(R.id.Author_list);
    ArrayList<String> a = DBlistbookfestival.getAuthorName();
    for(int i=0;i<a.size();i++){
        aList.add(a.get(i));
        Log.v("all_data",a.get(i));
    }
    ListAdapter1 la = new ListAdapter1(this, R.id.Author_list, aList);
    fList.setAdapter(la);
 }

private class ListAdapter1 extends ArrayAdapter<String> {  // --CloneChangeRequired
    private ArrayList<String> mList;  // --CloneChangeRequired
    public ListAdapter1(Context context, int textViewResourceId,ArrayList<String> list) { // --CloneChangeRequired
        super(context, textViewResourceId, list);
        this.mList = list;
    }

    public View getView(int position, View convertView, ViewGroup parent){
        View view = convertView;
        try{
        if (view == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = vi.inflate(R.layout.custom_radio, null);     // --CloneChangeRequired(list_item)
        }
        final String listItem = mList.get(position);    // --CloneChangeRequired
        if (listItem != null) {
            ( (TextView) view.findViewById(R.id.textView111) ).setText(listItem);
        }}catch(Exception e){

        }
        return view;
    }
}
</code>```

}

答: your listview could be null if findbyId doesnt find your listview R.id.Author_list in the layout.</p>

Title: Null pointer exeception in ListAdapter

Body:
I want to display Data in List View but I got Error Null Pointer Exception run time in line

fList.setAdapter(la);

My code is here List is complete printing in Log
Thanks

public class Forfattere extends Activity {
/** Called when the activity is first created. */
ArrayList<String> aList = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.forfattere);
    ListView fList = (ListView)findViewById(R.id.Author_list);
    ArrayList<String> a = DBlistbookfestival.getAuthorName();
    for(int i=0;i<a.size();i++){
        aList.add(a.get(i));
        Log.v("all_data",a.get(i));
    }
    ListAdapter1 la = new ListAdapter1(this, R.id.Author_list, aList);
    fList.setAdapter(la);
 }

private class ListAdapter1 extends ArrayAdapter<String> {  // --CloneChangeRequired
    private ArrayList<String> mList;  // --CloneChangeRequired
    public ListAdapter1(Context context, int textViewResourceId,ArrayList<String> list) { // --CloneChangeRequired
        super(context, textViewResourceId, list);
        this.mList = list;
    }

    public View getView(int position, View convertView, ViewGroup parent){
        View view = convertView;
        try{
        if (view == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = vi.inflate(R.layout.custom_radio, null);     // --CloneChangeRequired(list_item)
        }
        final String listItem = mList.get(position);    // --CloneChangeRequired
        if (listItem != null) {
            ( (TextView) view.findViewById(R.id.textView111) ).setText(listItem);
        }}catch(Exception e){

        }
        return view;
    }
}

}


问:
Convert Map<string><string> in QuickSight
I have a column of type Map string->string in Athena and this is not recognized in AWS QuickSight. I am trying to convert this field to varchar in QuickSight using SQL

```<code>SELECT cast(body as varchar) FROM db.events;
</code>```

But it fails

```<code>Cannot cast map(varchar,varchar) to varchar
</code>```

How can I convert this field correctly so QuickSight can query against it?

答:
I think there is is no easy way to do that, but maybe there are some workarounds.

If each map has two keys with known names you can create two new columns:

```<code>SELECT
    ELEMENT_AT(map_col,'key1') AS key1_col
    ,ELEMENT_AT(map_col,'key2') AS key2_col
FROM
    (
    SELECT
        MAP(
            ARRAY['key1','key2'],
            ARRAY['val1','val2']
            ) AS map_col
    )
</code>```

Which will output:

key1_col
key2_col

val1
val2

If your map column has just one key you can adapt the snippet above and use it or use this one:

```<code>SELECT
    ARRAY_JOIN(MAP_KEYS(map_col), ', ') AS keys
    ,ARRAY_JOIN(MAP_VALUES(map_col), ', ') AS vals
FROM
    (
    SELECT
        MAP(
            ARRAY['key1'],
            ARRAY['val1']
            ) AS map_col
    )
</code>```

which will result in:

keys
vals

key1
val1

As said above, there is no correct way, if you have many keys you can try to use the second snippet to create strings to store keys and values, and later use calculated fields (maybe using split) to access them.

Hope it helps (:

Body:
I have a column of type Map string->string in Athena and this is not recognized in AWS QuickSight. I am trying to convert this field to varchar in QuickSight using SQL

SELECT cast(body as varchar) FROM db.events;

But it fails

Cannot cast map(varchar,varchar) to varchar

How can I convert this field correctly so QuickSight can query against it?

Body:
I think there is is no easy way to do that, but maybe there are some workarounds.

If each map has two keys with known names you can create two new columns:

SELECT
    ELEMENT_AT(map_col,'key1') AS key1_col
    ,ELEMENT_AT(map_col,'key2') AS key2_col
FROM
    (
    SELECT
        MAP(
            ARRAY['key1','key2'],
            ARRAY['val1','val2']
            ) AS map_col
    )

Which will output:

key1_col
key2_col

val1
val2

If your map column has just one key you can adapt the snippet above and use it or use this one:

SELECT
    ARRAY_JOIN(MAP_KEYS(map_col), ', ') AS keys
    ,ARRAY_JOIN(MAP_VALUES(map_col), ', ') AS vals
FROM
    (
    SELECT
        MAP(
            ARRAY['key1'],
            ARRAY['val1']
            ) AS map_col
    )

which will result in:

keys
vals

key1
val1

As said above, there is no correct way, if you have many keys you can try to use the second snippet to create strings to store keys and values, and later use calculated fields (maybe using split) to access them.

Hope it helps (:


问:
How to collect a list of random numbers in ranges?
I have a list of numbers not in order 8,9,10,25,47,48,49,50,51,52,53,54,55,102,107,111,201,202,203,204,205, and it is a very important to me to make this list of numbers in ranges, like this :  8-10,25,47-55,102,107,111,201-205,
I'm familiar with shell scripting, but i couldn't find any solution.

答:
Find the minimum and maximum in the list. Store all the numbers as keys in an associative array. Then, iterate all the numbers from the minimum to the maximum, if the number - 1 is not in the associative array, a new range starts. If it's there, the range continues, if the number + 1 is not in there, the range ends here.

#! /bin/bash

list2ranges () {
    local -a arr
    IFS=, arr=($1)
    local min=${arr[0]}
    local max=${arr[0]}

    local -A seen
    local e
    for e in "${arr[@]}" ; do
        (( e < min )) && min=e
        (( e > max )) && max=e
        seen[$e]=1
    done

    local -a out
    local i
    for ((i=min; i<=max; ++i)) ; do
        if [[ ${seen[$i]} ]] ; then
            if [[ ${seen[$((i-1))]} ]] ; then
                if [[ ${out[${#out[@]}-1]} != *- ]] ; then
                    out[${#out[@]}-1]+=-
                fi
                if [[ ! ${seen[$((i+1))]} ]] ; then
                    out[${#out[@]}-1]+=$i
                fi
            else
                out+=($i)
            fi
        fi
    done
    IFS=, echo "${out[*]}"
}

list=8,9,10,25,47,48,49,50,51,52,53,54,55,102,107,111,201,202,203,204,205

diff <(list2ranges "$list") <(echo 8-10,25,47-55,102,107,111,201-205)
```
<p>If the difference between the minimum and the maximum is large, this will take a long time. Consider using Perl with Set::IntSpan instead.</p>
<pre class="lang-sh prettyprint-override"><code>list=8,9,10,25,47,48,49,50,51,52,53,54,55,102,107,111,201,202,203,204,205
perl -MSet::IntSpan -wE 'say Set::IntSpan->new(shift)' -- "$list"
</code>```

Body:
Find the minimum and maximum in the list. Store all the numbers as keys in an associative array. Then, iterate all the numbers from the minimum to the maximum, if the number - 1 is not in the associative array, a new range starts. If it's there, the range continues, if the number + 1 is not in there, the range ends here.

#! /bin/bash

list2ranges () {
    local -a arr
    IFS=, arr=($1)
    local min=${arr[0]}
    local max=${arr[0]}

    local -A seen
    local e
    for e in "${arr[@]}" ; do
        (( e < min )) && min=e
        (( e > max )) && max=e
        seen[$e]=1
    done

    local -a out
    local i
    for ((i=min; i<=max; ++i)) ; do
        if [[ ${seen[$i]} ]] ; then
            if [[ ${seen[$((i-1))]} ]] ; then
                if [[ ${out[${#out[@]}-1]} != *- ]] ; then
                    out[${#out[@]}-1]+=-
                fi
                if [[ ! ${seen[$((i+1))]} ]] ; then
                    out[${#out[@]}-1]+=$i
                fi
            else
                out+=($i)
            fi
        fi
    done
    IFS=, echo "${out[*]}"
}

list=8,9,10,25,47,48,49,50,51,52,53,54,55,102,107,111,201,202,203,204,205

diff <(list2ranges "$list") <(echo 8-10,25,47-55,102,107,111,201-205)

If the difference between the minimum and the maximum is large, this will take a long time. Consider using Perl with Set::IntSpan instead.

list=8,9,10,25,47,48,49,50,51,52,53,54,55,102,107,111,201,202,203,204,205
perl -MSet::IntSpan -wE 'say Set::IntSpan->new(shift)' -- "$list"


问:
Unable to deploy Google Cloud Function due to mysterious --production=false flag
For some reason, I can no longer deploy existing google functions from my local machine or from github actions. Whenever I deploy using the gcloud functions deploy command, I get the following error in the console: ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Build failed: Unknown Syntax Error: Invalid option name ("--production=false"). I am not using a --production=false option in my gcloud deploy command, so I don't really understand where that is coming from.

Build logs always failing on:

Step #1 - "build": Unable to delete previous cache image: DELETE https://us.gcr.io/v2/{{projectId}}/gcf/{{region}}/{{guid}}/cache/manifests/sha256:{{imageId}}: GOOGLE_MANIFEST_DANGLING_TAG: Manifest is still referenced by tag: latest.

Deploy command:

```<code>gcloud functions deploy --runtime=nodejs16 --region=us-central1 {{function_name}} --entry-point={{node_function}} --trigger-topic={{topic_name}}
</code>```

Attempted with the following gcloud versions and got the same result each time:

370, 371, 369, 360

I am not sure where this is coming from. I did not have this problem when I deployed just yesterday and it is not specific to my local machine.

答:
This was due to a regression issue on Google's part. They released a fix for it today and deploys are working again now.

Issue: https://github.com/GoogleCloudPlatform/buildpacks/issues/175#issuecomment-1030519240

Body:
For some reason, I can no longer deploy existing google functions from my local machine or from github actions. Whenever I deploy using the gcloud functions deploy command, I get the following error in the console: ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Build failed: Unknown Syntax Error: Invalid option name ("--production=false"). I am not using a --production=false option in my gcloud deploy command, so I don't really understand where that is coming from.

Build logs always failing on:

Step #1 - "build": Unable to delete previous cache image: DELETE https://us.gcr.io/v2/{{projectId}}/gcf/{{region}}/{{guid}}/cache/manifests/sha256:{{imageId}}: GOOGLE_MANIFEST_DANGLING_TAG: Manifest is still referenced by tag: latest.

Deploy command:

gcloud functions deploy --runtime=nodejs16 --region=us-central1 {{function_name}} --entry-point={{node_function}} --trigger-topic={{topic_name}}

Attempted with the following gcloud versions and got the same result each time:

370, 371, 369, 360

I am not sure where this is coming from. I did not have this problem when I deployed just yesterday and it is not specific to my local machine.


问:
Create a flowchart that will adequately represent the logic
“For a salesman to determine their salary for the month at a given point during
the month, they will enter their basic salary, total sales and commission rate
into an application. The application will then calculate and display the
salesman’s salary by adding the salesman’s basic salary to the product of the
total sales that they had at the given point in time and the commission rate at
which they were appointed. The commission rate is expressed as a percentage.”</p>

答: The flowchart would look something like this:


问:
How do I flip this sprite in pygame?
EDIT: I've now flipped the sprite, but when the animation plays on the flipped sprite, it has a black background instead of blending in with the major background. Just updated my code to the current situation. (2/8/2021)

I'm trying to flip a sprite in pygame, for example, I don't want them running left but looking right, which is what is happening right now.

The part that is giving me issues is the second comment that says ISSUES.

Here is my code (spritesheet is a class that transforms the image into a surface):

```<code>import pygame
import os
import sys
import random
from pygame.locals import *
import spritesheet
import time

pygame.init()

clock = pygame.time.Clock()
FPS = 60
prev_time = time.time()

pygame.display.set_caption('Platformer')

BG_COLOR = (50, 50, 50)
BLACK = (0, 0, 0)

WIN_SIZE = [1920,1080]

WIN = pygame.display.set_mode((WIN_SIZE[0], WIN_SIZE[1]), 0, 32)

# CONFIGURING Animations

IDLE_INDEX = 0

RUN_INDEX = 0

moving_right = False
moving_left = False

lookingRight = True

speed = 4
animation_tick = 8

player_location = [50, 50]
player_y_momentum = 0

player_rect = pygame.Rect(player_location[0] + 155, player_location[1] + 140, 70, 133)

def retrieve_list(animType, image):
    if animType == "idle":
        IDLE_FRAMES = []
        IDLE_STEPS = 9
        sprite_sheet = spritesheet.SpriteSheet(image)
        for step in range(IDLE_STEPS):
            newFRAME = sprite_sheet.get_image(step, 120, 80, 3.5, BLACK)
            IDLE_FRAMES.append(newFRAME)
        return IDLE_FRAMES
    if animType == "run":
        RUN_FRAMES = []
        RUN_STEPS = 9
        sprite_sheet = spritesheet.SpriteSheet(image)
        for step in range(RUN_STEPS):
            newFRAME = sprite_sheet.get_image(step, 120, 80, 3.5, BLACK)
            RUN_FRAMES.append(newFRAME)
        return RUN_FRAMES

sprite_sheet_img_IDLE = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Idle.png')
sprite_sheet_img_RUN = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Run.png')
IDLE_FRAMES = retrieve_list("idle", sprite_sheet_img_IDLE)
RUN_FRAMES = retrieve_list("run", sprite_sheet_img_RUN)
currentANIMATION = "idle"
playingAnim = None

while True:

    clock.tick(FPS)
    now = time.time()
    dt = now - prev_time
    prev_time = now
    WIN.fill(BG_COLOR)

    if currentANIMATION == "idle":
        if player_location[1] > WIN_SIZE[1] - IDLE_FRAMES[IDLE_INDEX].get_height():
            player_y_momentum = -player_y_momentum
        else:
            player_y_momentum += 0.2
        player_location[1] += player_y_momentum
    elif currentANIMATION == "run":
        if player_location[1] > WIN_SIZE[1] - RUN_FRAMES[RUN_INDEX].get_height():
            player_y_momentum = -player_y_momentum
        else:
            player_y_momentum += 0.2
        player_location[1] += player_y_momentum

    if moving_right:
        currentANIMATION = "run"
        if not lookingRight:
            lookingRight = True
        WIN.fill(BG_COLOR)
        playingAnim = WIN.blit(RUN_FRAMES[RUN_INDEX], (player_location[0], player_location[1]))
        player_location[0] += speed
    if moving_left:
        currentANIMATION = "run"
        if lookingRight:
            lookingRight = False
        leftFrame = pygame.transform.flip(RUN_FRAMES[RUN_INDEX], True, False)
        WIN.fill(BG_COLOR)
        playingAnim = WIN.blit(leftFrame, (player_location[0], player_location[1]))
        player_location[0] -= speed
    elif moving_right != True and moving_left != True:
        currentANIMATION = "idle"
        WIN.fill(BG_COLOR)
        playingAnim = WIN.blit(IDLE_FRAMES[IDLE_INDEX], (player_location[0], player_location[1]))

    player_rect.x = player_location[0] + 155
    player_rect.y = player_location[1] + 140

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_RIGHT or event.key == ord('d'):
                moving_right = True
            if event.key == K_LEFT or event.key == ord('a'):
                moving_left = True
        if event.type == KEYUP:
            if event.key == K_RIGHT or event.key == ord('d'):
                moving_right = False
            if event.key == K_LEFT or event.key == ord('a'):
                moving_left = False

    pygame.display.update()
    if animation_tick == 8:  # change 20 to how ever many ticks in between animation frames
        if currentANIMATION == "idle":
            if IDLE_INDEX < 8:
                IDLE_INDEX += 1
            else:
                IDLE_INDEX = 0
        if currentANIMATION == "run":
            if RUN_INDEX < 8:
                RUN_INDEX += 1
            else:
                RUN_INDEX = 0
        animation_tick = 0  # reset tick back to 0 after changing frame
    else:
        animation_tick += 1  # add 1 each iteration of the while loop
</code>```

Here are the spritesheets if you want to replicate my situation:
running spritesheet:

idle spritesheet:

I've tried flipping the original surface, but then the image gets messed up with black around it, and it doesn't play the animation.

答:
pygame.transform.flip does not flip the image in place, but returns a new image that is flipped:

flipped_image = pygame.transform.flip(image, True, False)
```

Title: How do I flip this sprite in pygame?

Body:
EDIT: I've now flipped the sprite, but when the animation plays on the flipped sprite, it has a black background instead of blending in with the major background. Just updated my code to the current situation. (2/8/2021)

I'm trying to flip a sprite in pygame, for example, I don't want them running left but looking right, which is what is happening right now.

The part that is giving me issues is the second comment that says ISSUES.

Here is my code (spritesheet is a class that transforms the image into a surface):

import pygame
import os
import sys
import random
from pygame.locals import *
import spritesheet
import time

pygame.init()

clock = pygame.time.Clock()
FPS = 60
prev_time = time.time()

pygame.display.set_caption('Platformer')

BG_COLOR = (50, 50, 50)
BLACK = (0, 0, 0)

WIN_SIZE = [1920,1080]

WIN = pygame.display.set_mode((WIN_SIZE[0], WIN_SIZE[1]), 0, 32)

# CONFIGURING Animations

IDLE_INDEX = 0

RUN_INDEX = 0

moving_right = False
moving_left = False

lookingRight = True

speed = 4
animation_tick = 8

player_location = [50, 50]
player_y_momentum = 0

player_rect = pygame.Rect(player_location[0] + 155, player_location[1] + 140, 70, 133)

def retrieve_list(animType, image):
    if animType == "idle":
        IDLE_FRAMES = []
        IDLE_STEPS = 9
        sprite_sheet = spritesheet.SpriteSheet(image)
        for step in range(IDLE_STEPS):
            newFRAME = sprite_sheet.get_image(step, 120, 80, 3.5, BLACK)
            IDLE_FRAMES.append(newFRAME)
        return IDLE_FRAMES
    if animType == "run":
        RUN_FRAMES = []
        RUN_STEPS = 9
        sprite_sheet = spritesheet.SpriteSheet(image)
        for step in range(RUN_STEPS):
            newFRAME = sprite_sheet.get_image(step, 120, 80, 3.5, BLACK)
            RUN_FRAMES.append(newFRAME)
        return RUN_FRAMES

sprite_sheet_img_IDLE = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Idle.png')
sprite_sheet_img_RUN = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Run.png')
IDLE_FRAMES = retrieve_list("idle", sprite_sheet_img_IDLE)
RUN_FRAMES = retrieve_list("run", sprite_sheet_img_RUN)
currentANIMATION = "idle"
playingAnim = None

while True:

    clock.tick(FPS)
    now = time.time()
    dt = now - prev_time
    prev_time = now
    WIN.fill(BG_COLOR)

    if currentANIMATION == "idle":
        if player_location[1] > WIN_SIZE[1] - IDLE_FRAMES[IDLE_INDEX].get_height():
            player_y_momentum = -player_y_momentum
        else:
            player_y_momentum += 0.2
        player_location[1] += player_y_momentum
    elif currentANIMATION == "run":
        if player_location[1] > WIN_SIZE[1] - RUN_FRAMES[RUN_INDEX].get_height():
            player_y_momentum = -player_y_momentum
        else:
            player_y_momentum += 0.2
        player_location[1] += player_y_momentum

    if moving_right:
        currentANIMATION = "run"
        if not lookingRight:
            lookingRight = True
        WIN.fill(BG_COLOR)
        playingAnim = WIN.blit(RUN_FRAMES[RUN_INDEX], (player_location[0], player_location[1]))
        player_location[0] += speed
    if moving_left:
        currentANIMATION = "run"
        if lookingRight:
            lookingRight = False
        leftFrame = pygame.transform.flip(RUN_FRAMES[RUN_INDEX], True, False)
        WIN.fill(BG_COLOR)
        playingAnim = WIN.blit(leftFrame, (player_location[0], player_location[1]))
        player_location[0] -= speed
    elif moving_right != True and moving_left != True:
        currentANIMATION = "idle"
        WIN.fill(BG_COLOR)
        playingAnim = WIN.blit(IDLE_FRAMES[IDLE_INDEX], (player_location[0], player_location[1]))

    player_rect.x = player_location[0] + 155
    player_rect.y = player_location[1] + 140

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_RIGHT or event.key == ord('d'):
                moving_right = True
            if event.key == K_LEFT or event.key == ord('a'):
                moving_left = True
        if event.type == KEYUP:
            if event.key == K_RIGHT or event.key == ord('d'):
                moving_right = False
            if event.key == K_LEFT or event.key == ord('a'):
                moving_left = False

    pygame.display.update()
    if animation_tick == 8:  # change 20 to how ever many ticks in between animation frames
        if currentANIMATION == "idle":
            if IDLE_INDEX < 8:
                IDLE_INDEX += 1
            else:
                IDLE_INDEX = 0
        if currentANIMATION == "run":
            if RUN_INDEX < 8:
                RUN_INDEX += 1
            else:
                RUN_INDEX = 0
        animation_tick = 0  # reset tick back to 0 after changing frame
    else:
        animation_tick += 1  # add 1 each iteration of the while loop

Here are the spritesheets if you want to replicate my situation:
running spritesheet:

idle spritesheet:

I've tried flipping the original surface, but then the image gets messed up with black around it, and it doesn't play the animation.


问:
Plot list of lists with facet_wrap()
Say I have a list of the following structure:

```<code>> results %>% str()
List of 6
 $ : num [1:5000, 1:2] -9.22 10.01 -3.33 -3.91 1.2 ...
  ..- attr(*, "scaled:center")= num [1:2] -0.1 -0.05
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
 $ : num [1:5000, 1:2] -7.82  7.74  6.30 -2.34 -5.76 ...
  ..- attr(*, "scaled:center")= num [1:2] 0.1 0.5
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
 $ : num [1:5000, 1:2] 1.87  0.17 -3.90 -0.20  4.73 ...
  ..- attr(*, "scaled:center")= num [1:2] -0.3 -0.001
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
 $ : num [1:5000, 1:2] -2.54  8.29 -4.76 -4.47  4.59 ...
  ..- attr(*, "scaled:center")= num [1:2] 2.05 -0.03
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
 $ : num [1:5000, 1:2] --1.67  0.74 -4.94  9.94 -1.70 ...
  ..- attr(*, "scaled:center")= num [1:2] -0.3 -0.5
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
 $ : num [1:5000, 1:2] 8.91 -7.83  8.12  6.32  0.84 ...
  ..- attr(*, "scaled:center")= num [1:2] 3.01 0.8
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
</code>```

I want to plot each list in ggplot and can do this easily by referencing the correct index and feeding it into a ggplot() call. For example:

```<code>results[[1]] %>%
as.data.frame() %>%
  ggplot(., aes(V1, V2, color = color, alpha = color)) +
  geom_point() +
  scale_color_gradientn(colours = viridisLite::turbo(256)) +
  labs(title = "nn = ")
</code>```

But this becomes rather tedious when I want a plot for each list. Ideally i'd use something like facet_wrap() to produce a single graph with all the plots in it. However, I do not know how to transform the original results object into the right format. I have tried the following:

```<code>results %>% as.data.frame() %>% dim()
</code>```

But that returns a df of 5,000 x 12, whereas what I want is a df of 30,000 x 3 (where the third column is the indicator for which list the data originally comes from).

Does anyone know if there is an easy way to feed the lists into ggplot directly and facet them as per the description above? Or, alternatively, can someone help me figure out how to transform the results object into the right format?

Many thanks in advance

答:
You could use lapply to convert each element of your list to a data.frame and afterwards use e.g. dplyr::bind_rows to bind your data in one dataframe and to add an id column which could then be used as faceting variable.

Using some fake data as example data:

# Fake example data
results <- list(
  matrix(data = 1:20, nrow = 10),
  matrix(data = 1:20, nrow = 10),
  matrix(data = 1:20, nrow = 10)
)

library(ggplot2)
library(dplyr)

dresults <- lapply(results, as.data.frame) %>%
  bind_rows(.id = "id")

ggplot(dresults, aes(V1, V2)) +
  geom_point() +
  facet_wrap(~id)
```

Title: Plot list of lists with facet_wrap()

Body:
Say I have a list of the following structure:

> results %>% str()
List of 6
 $ : num [1:5000, 1:2] -9.22 10.01 -3.33 -3.91 1.2 ...
  ..- attr(*, "scaled:center")= num [1:2] -0.1 -0.05
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
 $ : num [1:5000, 1:2] -7.82  7.74  6.30 -2.34 -5.76 ...
  ..- attr(*, "scaled:center")= num [1:2] 0.1 0.5
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
 $ : num [1:5000, 1:2] 1.87  0.17 -3.90 -0.20  4.73 ...
  ..- attr(*, "scaled:center")= num [1:2] -0.3 -0.001
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
 $ : num [1:5000, 1:2] -2.54  8.29 -4.76 -4.47  4.59 ...
  ..- attr(*, "scaled:center")= num [1:2] 2.05 -0.03
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
 $ : num [1:5000, 1:2] --1.67  0.74 -4.94  9.94 -1.70 ...
  ..- attr(*, "scaled:center")= num [1:2] -0.3 -0.5
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL
 $ : num [1:5000, 1:2] 8.91 -7.83  8.12  6.32  0.84 ...
  ..- attr(*, "scaled:center")= num [1:2] 3.01 0.8
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:5000] "1" "2" "3" "4" ...
  .. ..$ : NULL

I want to plot each list in ggplot and can do this easily by referencing the correct index and feeding it into a ggplot() call. For example:

results[[1]] %>%
as.data.frame() %>%
  ggplot(., aes(V1, V2, color = color, alpha = color)) +
  geom_point() +
  scale_color_gradientn(colours = viridisLite::turbo(256)) +
  labs(title = "nn = ")

But this becomes rather tedious when I want a plot for each list. Ideally i'd use something like facet_wrap() to produce a single graph with all the plots in it. However, I do not know how to transform the original results object into the right format. I have tried the following:

results %>% as.data.frame() %>% dim()

But that returns a df of 5,000 x 12, whereas what I want is a df of 30,000 x 3 (where the third column is the indicator for which list the data originally comes from).

Does anyone know if there is an easy way to feed the lists into ggplot directly and facet them as per the description above? Or, alternatively, can someone help me figure out how to transform the results object into the right format?

Many thanks in advance


问:
Regex- match 3 or 6 of type
I'm writing an application that requires color manipulation, and I want to know when the user has entered a valid hex value. This includes both '#ffffff' and '#fff', but not the ones in between, like 4 or 5 Fs. My question is, can I write a regex that determines if a character is present a set amount of times or another exact amount of times?

What I tried was mutating the:

```<code>/#(\d|\w){3}{6}/
</code>```

Regular expression to this:

```<code>/#(\d|\w){3|6}/
</code>```

Obviously this didn't work. I realize I could write:

```<code>/(#(\d|\w){3})|(#(\d|\w){6})/
</code>```

However I'm hoping for something that looks better.

答:
I had to find a pattern for this myself today but I also needed to include the extra flag for transparency (i.e. #FFF5 / #FFFFFF55). Which made things a little more complicated as the valid combinations goes up a little.

In case it's of any use, here's what I came up with:

```<code>var inputs = [
  "#12", // Invalid
  "#123", // Valid
  "#1234", // Valid
  "#12345", // Invalid
  "#123456", // Valid
  "#1234567", // Invalid
  "#12345678", // Valid
  "#123456789" // Invalid
];

var regex = /(^\#(([\da-f]){3}){1,2}$)|(^\#(([\da-f]){4}){1,2}$)/i;

inputs.forEach((itm, ind, arr) => console.log(itm, (regex.test(itm) ? "valid" : "-")));
</code>```

Which should return:

#123 valid

#1234 valid

#12345 -

#123456 valid

#1234567 -

#12345678 valid

#123456789 -

Title: Regex- match 3 or 6 of type

Body:
I'm writing an application that requires color manipulation, and I want to know when the user has entered a valid hex value. This includes both '#ffffff' and '#fff', but not the ones in between, like 4 or 5 Fs. My question is, can I write a regex that determines if a character is present a set amount of times or another exact amount of times?

What I tried was mutating the:

/#(\d|\w){3}{6}/

Regular expression to this:

/#(\d|\w){3|6}/

Obviously this didn't work. I realize I could write:

/(#(\d|\w){3})|(#(\d|\w){6})/

However I'm hoping for something that looks better.

Body:
I had to find a pattern for this myself today but I also needed to include the extra flag for transparency (i.e. #FFF5 / #FFFFFF55). Which made things a little more complicated as the valid combinations goes up a little.

In case it's of any use, here's what I came up with:

var inputs = [
  "#12", // Invalid
  "#123", // Valid
  "#1234", // Valid
  "#12345", // Invalid
  "#123456", // Valid
  "#1234567", // Invalid
  "#12345678", // Valid
  "#123456789" // Invalid
];

var regex = /(^\#(([\da-f]){3}){1,2}$)|(^\#(([\da-f]){4}){1,2}$)/i;

inputs.forEach((itm, ind, arr) => console.log(itm, (regex.test(itm) ? "valid" : "-")));

Which should return:

#123 valid

#1234 valid

#12345 -

#123456 valid

#1234567 -

#12345678 valid

#123456789 -


问:
Google Cloud Platform Service Account Key retention and client connections

Description of Issue

I am trying to figure out if an active connection to BigQuery from a service account key will be terminated if that key is revoked from the Service Account.

Example

Say I have this running, which clearly the source code shows that it only creates one connection using that service account, and that is on start up. If the GCP service account key that is being used in a case like this is revoked, will this application connection also be terminated? Since the application authenticated when the service account key was valid will it keep its connection alive?

答:
I am trying to figure out if an active connection to BigQuery from a
service account key will be terminated if that key is revoked from the
Service Account.

Not immediately.

The service account key is used to authorize access to BigQuery. Once the connection is created, encryption is via SSL certificates (HTTPS), and the service account key is no longer required until token refresh.

The public certificates used to verify private key signatures are cached. I do not know how often the keys and certificates are refreshed internally. Google recommends caching certificates for up to 24 hours. Access tokens are typically valid for 3600 seconds. Once a service account key is deleted, it takes a few minutes for this to be known globally (5 - 10 minutes). BigQuery will not know about this event until it needs to validate an access token.