问:
How to drawtext with a color gradient fill with ffmpeg (ffmpeg-python)? and then mix with music?
I'd like to achieve this result (to place a text with gradint or whatever picture-fill on top of a video):

So I decided to make a picture of gradient:

and then with chroma-key technique transform it to this (with transparent background):

and then place it over the video.

Here is the code with ffmpeg-python:

```<code>font_path = 'fonts/my_font.ttf'
input_video = ffmpeg.input('vid01.mp4')
split = input_video.filter_multi_output('split')
split_main = split[0]
split_txt_bg = split[1]

text_bg_black = ffmpeg.filter(text_bg, 'eq', brightness=-1000, saturation=0) # generate black bg from video input
text_mask = ffmpeg.filter(text_bg_black, 'drawtext', text='some text', fontcolor='0xFFFFFF', fontsize=85, x='(w-text_w)/2', y='68-(text_h/2)', fontfile=font_path) #draw text
text_mask_transparent = ffmpeg.filter(text_mask, 'colorkey', color='0xFFFFFF', similarity=0.45, blend=0.1)
text_on_bg = ffmpeg.filter([fill_gradient_gold, text_mask_transparent], 'overlay', x='(W-w)/2', y='(H-h)/2')
text = ffmpeg.filter(text_on_bg, 'colorkey', color='0x000000', similarity=0.45, blend=0.01)

comp1 = ffmpeg.filter([split_main, text], 'overlay', x='(W-w)/2', y='(H-h)/2')

comp.output('vid01_comp1.mp4').overwrite_output().run()
</code>```

This solution works, BUT with problems:

in the final it lowers the brightness of original gradient picture, that I don't want at all

it doesn't seem to be elegant (cuz of chroma-keying solution)

Is it possible to make a alpha-mask with drawtext and then use it to cut the gradient?

It would be better if you provide the answer in ffmpeg-python cuz I'm a newbie and it's very hard for me to convert command-line ffmpeg to ffmpeg-python, thank you!

I also can't get how to mix resulting video comp1 with music file, help pls.

答:
We may draw the text on black background, and use alphamerge for creating transparent background with colored gradient text.

Then we can overlay the gradient (with the transparent background) on the input video.

I don't know if my suggested solution is the most elegant, but it is not lower the brightness of the gradient picture.

The suggested solution applies the following stages:

Define synthetic black video source (1 frame).

Draw white text on the black video frame.

Add the "white text on black background" as alpha channel of the gradient image.

Only the white text is opaque, and the black background is fully transparent.

Overlay the above frame over the video.

Start by creating synthetic yellow video file (with sine audio) for testing:

```<code># Build first synthetic video, for testing:
(
    ffmpeg
    .output(ffmpeg.input('sine=frequency=500', f='lavfi'),
            ffmpeg.input('color=yellow:size=1920x1080:rate=1', f='lavfi'),
            'in.mp4', vcodec='libx264', crf=17, pix_fmt='yuv444p', acodec='aac', ar=22050, t=10)
    .overwrite_output()
    .run()
)
</code>```

Solution code sample:

```<code>import ffmpeg

# Example using FFmpeg CLI:
# ffmpeg -y -i text_bg.png -f lavfi -i color=0x505050:size=1920x1080:rate=1:duration=1 -filter_complex "color=black[blk];[blk][0:v]scale2ref[b][v0];[b]drawtext=text='some text':fontcolor='0xFFFFFF':fontsize=300:x='(w-text_w)/2':y='(h-text_h)/2',format=gray[a];[v0][a]alphamerge[txt];[1:v][txt]overlay=format=yuv444" -frames:v 1 overlayed_text.png

input = ffmpeg.input('in.mp4')
input_video = input.video
input_audio = input.audio

bg = ffmpeg.input('text_bg.png').video  # Gradient image

blk = ffmpeg.input('color=black:size=1920x1080:rate=1:duration=1', f='lavfi').video  # Black background

# White text on black background - used as alpha channel
txt = blk.filter('drawtext', text='some text', fontcolor='0xFFFFFF', fontsize=400, x='(w-text_w)/2', y='(h-text_h)/2').filter('format', pix_fmts='gray')

# Add txt as alpha channel to bg - only the white text is opaque, the black background is transparent.
txt_on_bg = ffmpeg.filter([bg, txt], 'alphamerge')

# Overlay txt_on_bg on input_video
comp1 = ffmpeg.filter([input_video, txt_on_bg], 'overlay', x='(W-w)/2', y='(H-h)/2', format='yuv444')

ffmpeg.output(comp1, input_audio, 'vid01_comp1.mp4', vcodec='libx264', crf=17, pix_fmt='yuv444p', acodec='copy').overwrite_output().run()
</code>```

Sample output:

Body:
I'd like to achieve this result (to place a text with gradint or whatever picture-fill on top of a video):

So I decided to make a picture of gradient:

and then with chroma-key technique transform it to this (with transparent background):

and then place it over the video.

Here is the code with ffmpeg-python:

font_path = 'fonts/my_font.ttf'
input_video = ffmpeg.input('vid01.mp4')
split = input_video.filter_multi_output('split')
split_main = split[0]
split_txt_bg = split[1]

text_bg_black = ffmpeg.filter(text_bg, 'eq', brightness=-1000, saturation=0) # generate black bg from video input
text_mask = ffmpeg.filter(text_bg_black, 'drawtext', text='some text', fontcolor='0xFFFFFF', fontsize=85, x='(w-text_w)/2', y='68-(text_h/2)', fontfile=font_path) #draw text
text_mask_transparent = ffmpeg.filter(text_mask, 'colorkey', color='0xFFFFFF', similarity=0.45, blend=0.1)
text_on_bg = ffmpeg.filter([fill_gradient_gold, text_mask_transparent], 'overlay', x='(W-w)/2', y='(H-h)/2')
text = ffmpeg.filter(text_on_bg, 'colorkey', color='0x000000', similarity=0.45, blend=0.01)

comp1 = ffmpeg.filter([split_main, text], 'overlay', x='(W-w)/2', y='(H-h)/2')

comp.output('vid01_comp1.mp4').overwrite_output().run()

This solution works, BUT with problems:

in the final it lowers the brightness of original gradient picture, that I don't want at all

it doesn't seem to be elegant (cuz of chroma-keying solution)

Is it possible to make a alpha-mask with drawtext and then use it to cut the gradient?

It would be better if you provide the answer in ffmpeg-python cuz I'm a newbie and it's very hard for me to convert command-line ffmpeg to ffmpeg-python, thank you!

I also can't get how to mix resulting video comp1 with music file, help pls.

Body:
We may draw the text on black background, and use alphamerge for creating transparent background with colored gradient text.

Then we can overlay the gradient (with the transparent background) on the input video.

I don't know if my suggested solution is the most elegant, but it is not lower the brightness of the gradient picture.

The suggested solution applies the following stages:

Define synthetic black video source (1 frame).

Draw white text on the black video frame.

Add the "white text on black background" as alpha channel of the gradient image.

Only the white text is opaque, and the black background is fully transparent.

Overlay the above frame over the video.

Start by creating synthetic yellow video file (with sine audio) for testing:

# Build first synthetic video, for testing:
(
    ffmpeg
    .output(ffmpeg.input('sine=frequency=500', f='lavfi'),
            ffmpeg.input('color=yellow:size=1920x1080:rate=1', f='lavfi'),
            'in.mp4', vcodec='libx264', crf=17, pix_fmt='yuv444p', acodec='aac', ar=22050, t=10)
    .overwrite_output()
    .run()
)

Solution code sample:

import ffmpeg

# Example using FFmpeg CLI:
# ffmpeg -y -i text_bg.png -f lavfi -i color=0x505050:size=1920x1080:rate=1:duration=1 -filter_complex "color=black[blk];[blk][0:v]scale2ref[b][v0];[b]drawtext=text='some text':fontcolor='0xFFFFFF':fontsize=300:x='(w-text_w)/2':y='(h-text_h)/2',format=gray[a];[v0][a]alphamerge[txt];[1:v][txt]overlay=format=yuv444" -frames:v 1 overlayed_text.png

input = ffmpeg.input('in.mp4')
input_video = input.video
input_audio = input.audio

bg = ffmpeg.input('text_bg.png').video  # Gradient image

blk = ffmpeg.input('color=black:size=1920x1080:rate=1:duration=1', f='lavfi').video  # Black background

# White text on black background - used as alpha channel
txt = blk.filter('drawtext', text='some text', fontcolor='0xFFFFFF', fontsize=400, x='(w-text_w)/2', y='(h-text_h)/2').filter('format', pix_fmts='gray')

# Add txt as alpha channel to bg - only the white text is opaque, the black background is transparent.
txt_on_bg = ffmpeg.filter([bg, txt], 'alphamerge')

# Overlay txt_on_bg on input_video
comp1 = ffmpeg.filter([input_video, txt_on_bg], 'overlay', x='(W-w)/2', y='(H-h)/2', format='yuv444')

ffmpeg.output(comp1, input_audio, 'vid01_comp1.mp4', vcodec='libx264', crf=17, pix_fmt='yuv444p', acodec='copy').overwrite_output().run()

Sample output:


来源: stackexchange

问:
Storing public certificates and private keys safely
I want to use certificate based authentication in AWS Lambda to generate oauth tokens. Currently I am storing the certificates and private keys locally and running it like a normal java application.

I am planning to use AWS Secrets manager to store these certificates and keys. However the issue is since we are using terraform to provision AWS resources, it seems like we will have to keep these certs and keys in our bitbucket repo which will have security risks. Is there any other way I can use these certificates in AWS lambda without actually storing them in bitbucket repo?

答:
The Terraform aws_secretsmanager_secret_version resource takes a string value, but that doesn't mean you have to hard-code the string inside that resource. You need to think about how you can read that key value into Terraform and reference it inside the resource.

For example, that string could come from a local file, or an S3 object. Terraform could also generate the TLS key for you.

ContentLicense: CC BY-SA 4.0


问:
For Loop Construction Turned Functional
I am currently learning Racket and want to do the following simple task: Construct a list which contains all tuples (i,j) : Int * Int  with 0 <= i < N and 0 <= j < M.

In, let's say Python, I would immediately know how to approach this, by using for loops:

# Not using any modules on purpose here
a = []
for i in range(5):
    for j in range(6):
        a.append((i,j))
```
<p>But I have trouble doing this in Racket. By now I have found a solution which replicates the <em>for</em>-loop approach by using a recursively defined function which for <code>a : A</code> and <code>f : Int -> A -> A</code> satisfies the equations</p>
```for 0 a f = (f 0) a
for n a f = for (n-1) ( (f n) a ) f
```
<p>which results in a chain of applications: <code>for n a f = ( (f 0) ∘ ... ∘ (f n) )(a)</code>. (By <code>f ∘ g </code> I mean composition of <code>f</code> and <code>g</code>). So first <code>f n</code> is applied to <code>a</code>, then <code>f (n - 1)</code> to the result of that, etc.</p>
<p>Given I basically want to do something like <code>((f 0 0) ∘ (f 0 1) ∘ ... ∘ (f N M)) (a)</code>, it can be split up as:</p>
``` (((f 0 0) ... (f 0 M)) ∘ ... ∘ ((f N 0) ... (f N M))) (a)
= ((λz. for M z (f 0)) ∘ ... ∘ (λz. for M z (f N))) (a)
= for N a (λi z. for M z (f i))
```
<p>Which then translates to the following Racket code:</p>
<pre class="lang-lisp prettyprint-override"><code>(define (for n a f)   ;; (for n '() cons) = range(n) = (0 1 ... n-1)
    (if (< 0 n)
        (for (- n 1) (f (- n 1) a) f)
        a))

(define a '())
(define (append i j x) (cons (cons i j) x))

(for 5 a (λ(i x)
       (for 6 x (λ(j y)
              (append i j y)))))
</code>```

The answer produces the desired result and is at least nice regarding that it is obvious how to extend this construction with any number of additional loops.

But I am still wondering whether there isn't a neater functional way to do this.

I'm happy with any answer  that does or does not use functions which might already be present in some library and which I have simply missed so far.

答:
You are probably looking for for*/list:

```<code>(for*/list ([i (range 5)]
            [j (range 6)])
  (list i j))
</code>```

See also Racket guide for Iterations and Comprehensions.

Title: For Loop Construction Turned Functional

Body:
I am currently learning Racket and want to do the following simple task: Construct a list which contains all tuples (i,j) : Int * Int  with 0 <= i < N and 0 <= j < M.

In, let's say Python, I would immediately know how to approach this, by using for loops:

# Not using any modules on purpose here
a = []
for i in range(5):
    for j in range(6):
        a.append((i,j))

But I have trouble doing this in Racket. By now I have found a solution which replicates the for-loop approach by using a recursively defined function which for a : A and f : Int -> A -> A satisfies the equations

for 0 a f = (f 0) a
for n a f = for (n-1) ( (f n) a ) f

which results in a chain of applications: for n a f = ( (f 0) ∘ ... ∘ (f n) )(a). (By f ∘ g  I mean composition of f and g). So first f n is applied to a, then f (n - 1) to the result of that, etc.

Given I basically want to do something like ((f 0 0) ∘ (f 0 1) ∘ ... ∘ (f N M)) (a), it can be split up as:

 (((f 0 0) ... (f 0 M)) ∘ ... ∘ ((f N 0) ... (f N M))) (a)
= ((λz. for M z (f 0)) ∘ ... ∘ (λz. for M z (f N))) (a)
= for N a (λi z. for M z (f i))

Which then translates to the following Racket code:

(define (for n a f)   ;; (for n '() cons) = range(n) = (0 1 ... n-1)
    (if (< 0 n)
        (for (- n 1) (f (- n 1) a) f)
        a))

(define a '())
(define (append i j x) (cons (cons i j) x))

(for 5 a (λ(i x)
       (for 6 x (λ(j y)
              (append i j y)))))

The answer produces the desired result and is at least nice regarding that it is obvious how to extend this construction with any number of additional loops.

But I am still wondering whether there isn't a neater functional way to do this.

I'm happy with any answer  that does or does not use functions which might already be present in some library and which I have simply missed so far.

Body:
You are probably looking for for*/list:

(for*/list ([i (range 5)]
            [j (range 6)])
  (list i j))

See also Racket guide for Iterations and Comprehensions.


问:
How to alternate order in flowchart?
How to alternate order in flowchart?

Imagine in the following flowchart,

"Want Fries" must be checked before checking "Want Drink". Now, I want to get an endpoint where, both of the conditions can be checked in any order. What should be the concise flowchart of it?

Update:

One possible diagram I made is the following but it looks not concise and also looks clumsy.

答:
You can use fork and join symbols to represent parallel processing. It indicates the start or end of a section of processes that can be done independently. The UML notation for fork and join is a straight line.

See the below picture.

Title: How to alternate order in flowchart?


问:
configuration of readiness probe for my webapp
I am running a sample webapp python in Kubernetes.
I am not able to figure out how I make use of probes here.

I want app to recover from broken states by automatically restarting pods

Route the traffic to the healthy pods only.

Make sure the database is up and running before the application (which in my case is Redis).

I have understanding of probes but not sure how/what values exactly to look for

My definition file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
     env: production
     app: frontend
spec:
  selector:
    matchLabels:
      env: production
      app: frontend
  replicas: 1
  template:
    metadata:
      name: myapp-pod
      labels:
        env: production
        app: frontend
    spec:
      containers:
      - name: myapp-container
        image: myimage:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 5000
```
<p>Now I am doing something like this</p>
```        readinessProbe:
          httpGet:
            path: /
            port: 5000
          initialDelaySeconds: 20
          periodSeconds: 5
        livenessProbe:
        httpGet:
          path: /
          port: 5000
        intialDelaySeconds: 10
        periodSeconds: 5
```

答:
You need to define both

readinessProbe: allowing to tell whether your Deployment is ready to serve traffic at any point of time during its lifecycle. This configuration item can support different command but in your case, this would be an httpGet matching and endpoint that you would implement in your web-app (most modern stack define the endpoints by default so check check the documentation of whatever framework you are using). Note that the endpoint handler would need to check the readiness of any needed dependency, in your case you would need to check if http[s]://redis-host:redis-port responds with success

livenessProbe: allowing for the control plane to check continuously your pods health and to decide on actions needed to get the cluster to the desired state rolling out any pods failing to report being alive. This probe support different definitions as well and as for the readinessProbe most modern framework offer endpoints responding to such request by default

Here down you can see a sample of both probes, for which you would have two respective HTTP endpoints within your web application:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
     env: production
     app: frontend
spec:
  selector:
    matchLabels:
      env: production
      app: frontend
  replicas: 1
  template:
    metadata:
      name: myapp-pod
      labels:
        env: production
        app: frontend
    spec:
      containers:
      - name: myapp-container
        image: myimage:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 5000
      readinessProbe:
        httpGet:
          path: /health
          port: 5000
      livenessProbe:
        httpGet:
          path: /health
          port: 5000
```

Body:
I am running a sample webapp python in Kubernetes.
I am not able to figure out how I make use of probes here.

I want app to recover from broken states by automatically restarting pods

Route the traffic to the healthy pods only.

Make sure the database is up and running before the application (which in my case is Redis).

I have understanding of probes but not sure how/what values exactly to look for

My definition file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
     env: production
     app: frontend
spec:
  selector:
    matchLabels:
      env: production
      app: frontend
  replicas: 1
  template:
    metadata:
      name: myapp-pod
      labels:
        env: production
        app: frontend
    spec:
      containers:
      - name: myapp-container
        image: myimage:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 5000

Now I am doing something like this

        readinessProbe:
          httpGet:
            path: /
            port: 5000
          initialDelaySeconds: 20
          periodSeconds: 5
        livenessProbe:
        httpGet:
          path: /
          port: 5000
        intialDelaySeconds: 10
        periodSeconds: 5


问:
Using inline view in SQL
I have a database table with employees (emp) with colomns name and salary. By using an inline view query i would like to list name, salary and a new colomn with each employees % of the total salary of all employees (salary/tot_sal*100). I am having trouble understanding the use of views. I tried the following code, but it did not work. Any ideas?</p>
```<code>create view tot_sal as
select sum(sal);

select name, salary, salary/tot_sal*100
from tot_sal
</code>```

答:
You have SELECT twice and a semi-colon.
The name for the view cannot be the same as the table.
You have to name each column.
Try the following</p>
```<code>create view tot_sal_view as select
    sum(sal) sum_salary,
    name,
    salary,
    salary/tot_sal*100
from tot_sal;
</code>```

Title: Using inline view in SQL

Body:
I have a database table with employees (emp) with colomns name and salary. By using an inline view query i would like to list name, salary and a new colomn with each employees % of the total salary of all employees (salary/tot_sal*100). I am having trouble understanding the use of views. I tried the following code, but it did not work. Any ideas?

create view tot_sal as
select sum(sal);

select name, salary, salary/tot_sal*100
from tot_sal

Body:
You have SELECT twice and a semi-colon.
The name for the view cannot be the same as the table.
You have to name each column.
Try the following

create view tot_sal_view as select
    sum(sal) sum_salary,
    name,
    salary,
    salary/tot_sal*100
from tot_sal;


问:
What are the benefits of abstract classes?
i have researched the topic of abstract classes. And I am not sure, if I understand the sense of this construct.

Is it right, that abstract classes are only control structures in OOP, respectively that I don't forget to implement a method in a sub class? I see no other benefits. I know that abstract classes never become an object. So, what the sense / benefits of abstract classes, abstract methods etc.?

Thanks for help.

答:
Is it right, that abstract classes are only control structures in OOP, respectively that I don't forget to implement a method in a sub class?

This is actually the responsibility of interfaces.

Abstract classes are for sharing the code, the logic or behavior between multiple subclasses. And because the behavior provided by the base class may require that some missing parts of the logic are provided by subclasses, we can declare a base class as abstract and declare abstract members in it - similarly to interfaces. "abstract" in this context basically means that the functionality is incomplete and can't be used straight away, without filling the gaps.

In practice, sharing of the code through subtyping is generally discouraged and therefore abstract classes are less popular nowadays than in the past. We learnt that it is usually better and easier to maintain if we share the code by composition of multiple separate classes than by subclassing (https://en.wikipedia.org/wiki/Composition_over_inheritance).

Edit: see this example:

abstract class AbstractDataHandler {
    fun doSomething() {
        // acquire data
        processData(data)
        // do something else with data
    }

    abstract fun processData(data: Data)
}

class MyDataHandler : AbstractDataHandler() {
    override fun processData(data: Data) {
        // process data
    }
}
```
<p>We have some kind of a data handler. At some point it has to perform some kind of data processing, but this processing should be different depending on the specific subclass. So <code>AbtractDataHandler</code> can't perform the whole operation alone. It needs a way to invoke data processing step that is provided by the subclass. It defines this processing as an abstract function.</p>
<p>The same example could be implemented with composition instead:</p>
<pre class="lang-kotlin prettyprint-override"><code>interface DataProcessor {
    fun processData(data: Data)
}

class DataHandler(private val processor: DataProcessor) {
    fun doSomething() {
        // acquire data
        processor.processData(data)
        // do something else with data
    }
}
</code>```

(In this specific case it would be probably more Kotlin-ish to not use an interface, but a function type.)

Also, abstract classes are common if we need to implement an interface and there is some very basic functionality that is the same across all implementations. For example, all implementations have to provide the same fields for storing the data. Then abstract class could provide these fields, but it does know nothing about implementing the rest of the interface, so most of functions remain abstract.

Body:
Is it right, that abstract classes are only control structures in OOP, respectively that I don't forget to implement a method in a sub class?

This is actually the responsibility of interfaces.

Abstract classes are for sharing the code, the logic or behavior between multiple subclasses. And because the behavior provided by the base class may require that some missing parts of the logic are provided by subclasses, we can declare a base class as abstract and declare abstract members in it - similarly to interfaces. "abstract" in this context basically means that the functionality is incomplete and can't be used straight away, without filling the gaps.

In practice, sharing of the code through subtyping is generally discouraged and therefore abstract classes are less popular nowadays than in the past. We learnt that it is usually better and easier to maintain if we share the code by composition of multiple separate classes than by subclassing (https://en.wikipedia.org/wiki/Composition_over_inheritance).

Edit: see this example:

abstract class AbstractDataHandler {
    fun doSomething() {
        // acquire data
        processData(data)
        // do something else with data
    }

    abstract fun processData(data: Data)
}

class MyDataHandler : AbstractDataHandler() {
    override fun processData(data: Data) {
        // process data
    }
}

We have some kind of a data handler. At some point it has to perform some kind of data processing, but this processing should be different depending on the specific subclass. So AbtractDataHandler can't perform the whole operation alone. It needs a way to invoke data processing step that is provided by the subclass. It defines this processing as an abstract function.

The same example could be implemented with composition instead:

interface DataProcessor {
    fun processData(data: Data)
}

class DataHandler(private val processor: DataProcessor) {
    fun doSomething() {
        // acquire data
        processor.processData(data)
        // do something else with data
    }
}

(In this specific case it would be probably more Kotlin-ish to not use an interface, but a function type.)

Also, abstract classes are common if we need to implement an interface and there is some very basic functionality that is the same across all implementations. For example, all implementations have to provide the same fields for storing the data. Then abstract class could provide these fields, but it does know nothing about implementing the rest of the interface, so most of functions remain abstract.


问:
Makefile error when trying to see output in ubuntu windows
I am extremely new to python and unix and my assignment for class is to make a makefile called python_program for a simple program called python_program.py . Ive looked on the other threads related to this type of question but I dont know enough to understand most of the things they are saying. When I run make in ubuntu it does create the new python_program file with the printed "Python is a fun language to learn" but when I do the command ./python_program it gives me the error code below. I appreciate all the help and advice given

python_program.py

```<code>#!/usr/bin/env python

def main():
    print("Python is a fun language to learn")

main()
</code>```

My Makefile

```<code>python_program: python_program.py
    python  python_program.py > python_program
    chmod +x python_program.py
</code>```

I've tried many different version to create the MakeFile and this is my most recent one, but eachtime I run it it creates a blank python_program file or it gives me an error code in the Ubunut command line.

Error Code:

```<code>./python_program: line 1: Python: command not found
</code>```

Just some extra information as to why I have to do this and the exact objective of this code

```<code>The Python Makefile must use the file python_program.py to create an executable file called python_program.

Assume that your Python Makefile is called Makefile and is in the same directory as the python_program.py, and therefore, when you run make in that directory, your Python Makefile will create a python_program executable.

Also, your Python Makefile must recreate python_program when python_program.py changes and you run make again.

This means that:

Run make.
Execute ./python_program.
Edit the source code python_program.py (change the strings, for instance).
Run make.
Execute ./python_program and verify that the changes you made in step 3 are reflected.
There are several ways to approach this (because there’s nothing to compile). For instance, you can take advantage of the shebang functionality, which allows a file that can be interpreted to be executed. This requires that the file is executable (chmod +x filename).
</code>```

答:
You are misunderstanding what you need to do.

Your Python program python_program.py must create a file, python_program, which is a valid executable program.  Just adding chmod +x to a file will tell the computer it's an executable program, but that doesn't mean it's a valid executable program.

You could have a PDF file containing a letter to your roommate, and run chmod +x on it, and then the computer would let you "run" it, but it wouldn't actually work, because a letter to your roommate is not a valid executable program.

In your example above you have created a Python program that writes out a file that contains the string Python is a fun language to learn.  But, just a like a letter to your roommate, a file containing the string Python is a fun language to learn is not a valid executable program.

So, when you try to run it, it fails.

You need to modify your python_program.py so that the file it generates, python_program, is an actual valid executable program.  Your quoted text above doesn't give you any directions as to what form that might take, so it's up to you.  But it can't just be the equivalent of a letter to your roommate.

Body:
I am extremely new to python and unix and my assignment for class is to make a makefile called python_program for a simple program called python_program.py . Ive looked on the other threads related to this type of question but I dont know enough to understand most of the things they are saying. When I run make in ubuntu it does create the new python_program file with the printed "Python is a fun language to learn" but when I do the command ./python_program it gives me the error code below. I appreciate all the help and advice given

python_program.py

#!/usr/bin/env python

def main():
    print("Python is a fun language to learn")

main()

My Makefile

python_program: python_program.py
    python  python_program.py > python_program
    chmod +x python_program.py

I've tried many different version to create the MakeFile and this is my most recent one, but eachtime I run it it creates a blank python_program file or it gives me an error code in the Ubunut command line.

Error Code:

./python_program: line 1: Python: command not found

Just some extra information as to why I have to do this and the exact objective of this code

The Python Makefile must use the file python_program.py to create an executable file called python_program.

Assume that your Python Makefile is called Makefile and is in the same directory as the python_program.py, and therefore, when you run make in that directory, your Python Makefile will create a python_program executable.

Also, your Python Makefile must recreate python_program when python_program.py changes and you run make again.

This means that:

Run make.
Execute ./python_program.
Edit the source code python_program.py (change the strings, for instance).
Run make.
Execute ./python_program and verify that the changes you made in step 3 are reflected.
There are several ways to approach this (because there’s nothing to compile). For instance, you can take advantage of the shebang functionality, which allows a file that can be interpreted to be executed. This requires that the file is executable (chmod +x filename).


问:
c++ test if random number is positive or negative
I have school work with C++ and Im new to it. I have to generate 17 random numbers and then test if they are positive/negative/equal to zero. I can't seem to find a way to take the random generated number from the for loop to test it in the if/else if loop. Heeeeelp please :D (The b variable is just there from tests)</p>
```<code>#include <ctime>
using namespace std;
int main() {

    srand(
          (unsigned) time(0)
    );

    int a;
    int b;
    int num;

    for(int a = 0; a<17; a++) {
        cout << "Skaitlis: " << rand()% 20 + -10 << "\n";

        if(b > 0){
            cout << b << " is a positive number." << endl;
        }
        else if (b == 0){
            cout << b << " is equal to zero." << endl;
        }
        else {
            cout << b << " is a negative number." << endl;
        }
   }
}
</code>```

答:
I'm not sure if that's what you mean, but you can just assign the result of your random function to a variable, for example:

int rnd = rand() % 20 - 10;
cout << "Skaitlis: " << rnd << '\n';
if (rnd > 0)
    cout << rnd << " is a positive number." << endl;
else if (rnd == 0)
    cout << rnd << " is equal to zero." << endl;
else
    cout << rnd << " is a negative number." << endl;
```

Also, if you are just starting programming, I don't think that's necessary to know, but keep in mind that rand() isn't really a good way to create random numbers. It's way better to use for example mt19937 (although it's a little bit more complicated). rand() function generates random numbers only up to 32767 (though it also depends on the compilator you're using) and if you're trying to get a random number in a specific range, there's also a higher chance , that the rand() function will return a smaller number.

Body:
I have school work with C++ and Im new to it. I have to generate 17 random numbers and then test if they are positive/negative/equal to zero. I can't seem to find a way to take the random generated number from the for loop to test it in the if/else if loop. Heeeeelp please :D (The b variable is just there from tests)

#include <ctime>
using namespace std;
int main() {

    srand(
          (unsigned) time(0)
    );

    int a;
    int b;
    int num;

    for(int a = 0; a<17; a++) {
        cout << "Skaitlis: " << rand()% 20 + -10 << "\n";

        if(b > 0){
            cout << b << " is a positive number." << endl;
        }
        else if (b == 0){
            cout << b << " is equal to zero." << endl;
        }
        else {
            cout << b << " is a negative number." << endl;
        }
   }
}

Body:
I'm not sure if that's what you mean, but you can just assign the result of your random function to a variable, for example:

int rnd = rand() % 20 - 10;
cout << "Skaitlis: " << rnd << '\n';
if (rnd > 0)
    cout << rnd << " is a positive number." << endl;
else if (rnd == 0)
    cout << rnd << " is equal to zero." << endl;
else
    cout << rnd << " is a negative number." << endl;

Also, if you are just starting programming, I don't think that's necessary to know, but keep in mind that rand() isn't really a good way to create random numbers. It's way better to use for example mt19937 (although it's a little bit more complicated). rand() function generates random numbers only up to 32767 (though it also depends on the compilator you're using) and if you're trying to get a random number in a specific range, there's also a higher chance , that the rand() function will return a smaller number.


问:
How to use Kotlin coroutines await() on main thread
I just started learning Kotlin coroutines and was trying to simulate some long time API-calls with showing the result on the UI:

```<code>class MainActivity : AppCompatActivity() {
    fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

    override
    fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.setContentView(R.layout.activity_main)
        val resultTV = findViewById(R.id.text) as TextView

        val a = async(CommonPool) {
            delay(1_000L)
            6
        }

        val b = async(CommonPool) {
            delay(1_000L)
            7
        }

        launch(< NEED UI thread here >) {
            val aVal = a.await()
            val bVal = b.await()
            resultTV.setText((aVal * bVal).toString())
        }
    }
}
</code>```

I don't understand how could I possibly use launch method with main context.

Unfortunately, I was not able to find anything about delivering results for some specific threads on the official tutorial for coroutines.

答:
There are a couple of useful tools that can be used for the purpose of long time running API-calls in Activity/Fragment. So basically if you want to run two long running tasks in parallel and update UI after both are finished you can do it the next way:

```<code>lifecycleScope.launch {
    // launching two tasks in parallel
    val aValDeferred = executeLongRunningTask1Async()
    val bValDeferred = executeLongRunningTask2Async()

    // wait for both of them are finished
    val aVal = aValDeferred.await()
    val bVal = bValDeferred.await()

    // update UI
    resultTV.setText((aVal * bVal).toString())
}

private fun executeLongRunningTask1Async(): Deferred<Int> = lifecycleScope.async(Dispatchers.Default) {
    delay(1_000L)
    6
}

private fun executeLongRunningTask2Async(): Deferred<Int> = lifecycleScope.async(Dispatchers.Default) {
    delay(1_000L)
    7
}
</code>```

lifecycleScope -  is a CoroutineScope, by default it has Dispatchers.Main context, it means we can update UI in the launch block. For LifecycleScope, use androidx.lifecycle:lifecycle-runtime-ktx:2.4.0 or higher.

lifecycleScope.async(Dispatchers.Default) - here Dispatchers.Default is used as a context of the coroutine to have the async block running in the background thread.

ContentLicense: CC BY-SA 3.0

Body:
I just started learning Kotlin coroutines and was trying to simulate some long time API-calls with showing the result on the UI:

class MainActivity : AppCompatActivity() {
    fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

    override
    fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.setContentView(R.layout.activity_main)
        val resultTV = findViewById(R.id.text) as TextView

        val a = async(CommonPool) {
            delay(1_000L)
            6
        }

        val b = async(CommonPool) {
            delay(1_000L)
            7
        }

        launch(< NEED UI thread here >) {
            val aVal = a.await()
            val bVal = b.await()
            resultTV.setText((aVal * bVal).toString())
        }
    }
}

I don't understand how could I possibly use launch method with main context.

Unfortunately, I was not able to find anything about delivering results for some specific threads on the official tutorial for coroutines.

Body:
There are a couple of useful tools that can be used for the purpose of long time running API-calls in Activity/Fragment. So basically if you want to run two long running tasks in parallel and update UI after both are finished you can do it the next way:

lifecycleScope.launch {
    // launching two tasks in parallel
    val aValDeferred = executeLongRunningTask1Async()
    val bValDeferred = executeLongRunningTask2Async()

    // wait for both of them are finished
    val aVal = aValDeferred.await()
    val bVal = bValDeferred.await()

    // update UI
    resultTV.setText((aVal * bVal).toString())
}

private fun executeLongRunningTask1Async(): Deferred<Int> = lifecycleScope.async(Dispatchers.Default) {
    delay(1_000L)
    6
}

private fun executeLongRunningTask2Async(): Deferred<Int> = lifecycleScope.async(Dispatchers.Default) {
    delay(1_000L)
    7
}

lifecycleScope -  is a CoroutineScope, by default it has Dispatchers.Main context, it means we can update UI in the launch block. For LifecycleScope, use androidx.lifecycle:lifecycle-runtime-ktx:2.4.0 or higher.

lifecycleScope.async(Dispatchers.Default) - here Dispatchers.Default is used as a context of the coroutine to have the async block running in the background thread.


问:
Selecting multiple elements with querySelectorAll and applying event in JavaScript
there is an onchange event on the input and want it to change the value of the spans with the class of "number" whenever it changes so there here is the HTML :

function myFunction() {
  var x = document.getElementById("myText").value
  document.querySelectorAll(".number").innerText = x
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="uper-container">
  <p>Metric/Imperial unit conversion</p>
  <!-- *********************************************************************************************** -->
  <!-- this input will change the value of 6's span below with the class of "number" -->
  <!-- ********************************************************************************************** -->
  <input type="text" id="myText" placeholder="number here" value="20" onchange="myFunction()">
</div>
<div class="lower-container">
  <p>Length(Meter/Feet)</p>
  <p>
    <span class="number"></span> meters = <span class="d"></span>feet |
    <span class="number"></span> feet = <span class="d"></span>meters
  </p>
  <p>Volume(Liters/Gallons)
    <</p>
      <p>
        <span class="number"></span> liter = <span class="d"></span>gallon |
        <span class="number"></span> gallon = <span class="d"></span>liter
      </p>
      <p>Mass(Kilograms/Pounds)</p>
      <p>
        <span class="number"></span> kilogram = <span class="d"></span>pound |
        <span class="number"></span> pound = <span class="d"></span>kilogram
      </p>
</div></code>```

so how to make spans with the class="number" have the same value as input id="myText"?
and one thing to mention is that I use scrimba editor.

答:
You can also use the for-of loop.</p>
```<code>function myFunction() {
    const x = document.getElementById("myText").value;
    const numberElements = document.querySelectorAll(".number");

    for (let element of numberElements) {
        element.innerText = x;
    }
}
</code>```

Body:
there is an onchange event on the input and want it to change the value of the spans with the class of "number" whenever it changes so there here is the HTML :

function myFunction() {
  var x = document.getElementById("myText").value
  document.querySelectorAll(".number").innerText = x
}

Metric/Imperial unit conversion

  <input type="text" id="myText" placeholder="number here" value="20" onchange="myFunction()">

Length(Meter/Feet)

     meters = feet |
     feet = meters

Volume(Liters/Gallons)
    <

         liter = gallon |
         gallon = liter

Mass(Kilograms/Pounds)

         kilogram = pound |
         pound = kilogram

so how to make spans with the class="number" have the same value as input id="myText"?
and one thing to mention is that I use scrimba editor.

Body:
You can also use the for-of loop.

function myFunction() {
    const x = document.getElementById("myText").value;
    const numberElements = document.querySelectorAll(".number");

    for (let element of numberElements) {
        element.innerText = x;
    }
}


问:
gitea has error merging changes on my build server
I build successfully at my computer and push to the build server.
However, the build server fails to build.
The build server log is:

```<code>HEAD is now at 85262fd8 Merge remote-tracking branch 'origin/myfeature50'
end reset
start pull
From https://mycomp.net/myproj
    f6a17689..72034e9f   S2 -> origin/S2
Auto-merging src/Service.java
CONFLICT (content): Merge conflict in src/Service.java
Automatic merge failed; fix conflicts and then commit the result.
end pull
</code>```

git log at my computer:

```<code>72034e9f Fix bug
f6a17689 Merge remote-tracking branch 'origin/myfeature200' into S2
..
85262fd8 Merge remote-tracking branch 'origin/myfeature50' into S2
</code>```

The build server seems to keep pulling from remote-tracking branch 'origin/myfeature50'
The build server use gitea.
How to fix this build server problem?

Update #1
Must I do rebase instead of merge?
I do this but the build server still has the same build (Merge conflict) error:

```<code>git checkout myfeature50
git merge --no-ff myfeature200
//resolve conflict
git add
git commit
git push

</code>```

Update #2

```<code>git checkout myfeature50
git rebase myfeature200
//resolve conflict
git add
git commit
git push
</code>```

答:
Software on your build server is attempting to automatically merge your changes, but that fails. If your configuration allows it you could merge the changes yourself, or you could rebase your branch with master and push that, making automatic merge work.

I would suggest rebasing your branch with master and pushing those changes to branch.

Body:
I build successfully at my computer and push to the build server.
However, the build server fails to build.
The build server log is:

HEAD is now at 85262fd8 Merge remote-tracking branch 'origin/myfeature50'
end reset
start pull
From https://mycomp.net/myproj
    f6a17689..72034e9f   S2 -> origin/S2
Auto-merging src/Service.java
CONFLICT (content): Merge conflict in src/Service.java
Automatic merge failed; fix conflicts and then commit the result.
end pull

git log at my computer:

72034e9f Fix bug
f6a17689 Merge remote-tracking branch 'origin/myfeature200' into S2
..
85262fd8 Merge remote-tracking branch 'origin/myfeature50' into S2

The build server seems to keep pulling from remote-tracking branch 'origin/myfeature50'
The build server use gitea.
How to fix this build server problem?

Update #1
Must I do rebase instead of merge?
I do this but the build server still has the same build (Merge conflict) error:

git checkout myfeature50
git merge --no-ff myfeature200
//resolve conflict
git add
git commit
git push

Update #2

git checkout myfeature50
git rebase myfeature200
//resolve conflict
git add
git commit
git push


问:
Is there a `jq` command line tool or wrapper which lets you interactively explore `jq` similar to `jmespath.terminal`
jq is a lightweight and flexible command-line JSON processor.

https://stedolan.github.io/jq/

Is there a jq command line tool or wrapper which lets you pipe output into it and interactively explore jq, with the JSON input in one pane and your interactively updating result in another pane, similar to jmespath.terminal ?

I'm looking for something similar to the JMESPath Terminal jpterm

"JMESPath exploration tool in the terminal"

https://github.com/jmespath/jmespath.terminal

I found this project jqsh but it's not maintained and it appears to produce a lot of errors when I use it.

https://github.com/bmatsuo/jqsh

I've used https://jqplay.org/ and it's a great web based jq learning tool. However, I want to be able to, in the shell, pipe the json output of a command into an interactive jq which allows me to explore and experiment with jq commands.

Thanks in advance!

答:
There is a new one: https://github.com/PaulJuliusMartinez/jless

JLess is a command-line JSON viewer designed for reading, exploring, and searching through JSON data.

JLess will pretty print your JSON and apply syntax highlighting.

Expand and collapse Objects and Arrays to grasp the high- and low-level structure of a JSON document. JLess has a large suite of vim-inspired commands that make exploring data a breeze.

JLess supports full text regular-expression based search. Quickly find the data you're looking for in long String values, or jump between values for the same Object key.


问:
I can't add id from XML

Why can't I add this id  here?

答:
If you want to access the TextView directly from the itemView you should use findViewById:

```<code>holder.itemView.findViewById<TextView>(R.id.tvTodoTitle).apply {
    // Initialize the TextView here...
    text = "Example"
}
</code>```

Title: I can't add id from XML

Body: Why can't I add this id  here?

Body:
If you want to access the TextView directly from the itemView you should use findViewById:

holder.itemView.findViewById<TextView>(R.id.tvTodoTitle).apply {
    // Initialize the TextView here...
    text = "Example"
}


问:
conda init powershell has no effect
I installed Anaconda3 on my Windows Laptop and tried to make the conda activate command available in powershell so that I can use the conda env in VS Code for a Jupyter Notebook. But the problem is this:

Added Conda to the Environment-PATH

I executed conda init powershell in the conda prompt and closed it afterwars

opened powershell and executed set-executionpolicy remotesigned

then i restarted the computer

eventhough it should be working at this point I still get the following message when executing conda activate base inside powershell:

CommandNotFoundError: Your shell has not been properly configured to
use 'conda activate'. If using 'conda activate' from a batch script,
change your invocation to 'CALL conda.bat activate'. To initialize
your shell, run conda init <SHELL_NAME> Currently supported shells
are:

bash

cmd.exe

fish

tcsh

xonsh

zsh

powershell

See 'conda init --help' for more information and options. IMPORTANT:
You may need to close and restart your shell after running 'conda
init'.

答:
I noticed that your powershell could execute conda init successfully.

2.I executed conda init powershell in the conda prompt and closed it afterwars

Normally this command will edit this account's powershell startup config file, which locates in C:\Users\[YOUR_ACCOUNT_NAME]\Documents\WindowsPowerShell\profile.ps1. Please make sure that the edited file include codes like this in your personal folder:

```<code>#region conda initialize
# !! Contents within this block are managed by 'conda init' !!
(& "C:\ProgramData\Miniconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | Invoke-Expression
#endregion
</code>```

Sometimes the code page that powershell is using may cause jumbled characters when your account name includes non-ascii characters, resulting in editing the profile.ps1 in the jumbled path. Just copy it into your real account path as shown above.

Title: conda init powershell has no effect

Body:
I noticed that your powershell could execute conda init successfully.

2.I executed conda init powershell in the conda prompt and closed it afterwars

Normally this command will edit this account's powershell startup config file, which locates in C:\Users\[YOUR_ACCOUNT_NAME]\Documents\WindowsPowerShell\profile.ps1. Please make sure that the edited file include codes like this in your personal folder:

#region conda initialize
# !! Contents within this block are managed by 'conda init' !!
(& "C:\ProgramData\Miniconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | Invoke-Expression
#endregion

Sometimes the code page that powershell is using may cause jumbled characters when your account name includes non-ascii characters, resulting in editing the profile.ps1 in the jumbled path. Just copy it into your real account path as shown above.


问:
How to get metadata of a blob from Event Grid Trigger in Azure Function
My requirement is to get metadata from the blob on an EventGridTrigger. The ask seems to be simple, however I am not able to find examples online. Below is my Azure Funtion.
I need to get the Metadata of the blob. What is the best way of getting it.

```<code>        public static void Run([EventGridTrigger] EventGridEvent eventGridEvent,
        [Blob("{data.url}", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream input,
        ExecutionContext context,
        ILogger log)
        {
              // other lines of code
              IDictionary<string, string> metadata = get_metadata_of_the_blob;
              // other lines of code
        }
</code>```

I need to somehow get the Metadata within the function code at: get_metadata_of_the_blob

答:
try the following:

```<code>public static async Task Run(JObject eventGridEvent, CloudBlockBlob blob, ILogger log)
{
   // ...

   await blob.FetchAttributesAsync();
   log.LogInformation($"\nMetadata: {string.Join(" | ", blob.Metadata.Select(i => $"{i.Key}={i.Value}"))}");

   // ...
}
</code>```

and the function.json:

```<code>{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    },
    {
      "type": "blob",
      "name": "blob",
      "path": "{data.url}",
      "connection": "AzureWebJobsStorage",
      "direction": "in"
    }
  ],
  "disabled": false
}
</code>```

Body:
My requirement is to get metadata from the blob on an EventGridTrigger. The ask seems to be simple, however I am not able to find examples online. Below is my Azure Funtion.
I need to get the Metadata of the blob. What is the best way of getting it.

        public static void Run([EventGridTrigger] EventGridEvent eventGridEvent,
        [Blob("{data.url}", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream input,
        ExecutionContext context,
        ILogger log)
        {
              // other lines of code
              IDictionary<string, string> metadata = get_metadata_of_the_blob;
              // other lines of code
        }

I need to somehow get the Metadata within the function code at: get_metadata_of_the_blob

Body:
try the following:

public static async Task Run(JObject eventGridEvent, CloudBlockBlob blob, ILogger log)
{
   // ...

   await blob.FetchAttributesAsync();
   log.LogInformation($"\nMetadata: {string.Join(" | ", blob.Metadata.Select(i => $"{i.Key}={i.Value}"))}");

   // ...
}

and the function.json:

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    },
    {
      "type": "blob",
      "name": "blob",
      "path": "{data.url}",
      "connection": "AzureWebJobsStorage",
      "direction": "in"
    }
  ],
  "disabled": false
}


问:
FFMEG option scale=-1 and scale=-2
I tried to convert a video and resize it with scale=-1:720, but got the error "width not divisible by 2". And I solved it with: scale=-2:720.
What are the differences between

```<code>scale=-1:720
</code>```

and

```<code>scale=-2:720
</code>```

答:
It's in the documentation:

If one and only one of the values is -n with n >= 1, the scale filter will use a value that maintains the aspect ratio of the input image, calculated from the other specified dimension. After that it will, however, make sure that the calculated dimension is divisible by n and adjust the value if necessary.

Title: FFMEG option scale=-1 and scale=-2

Body:
I tried to convert a video and resize it with scale=-1:720, but got the error "width not divisible by 2". And I solved it with: scale=-2:720.
What are the differences between

scale=-1:720

and

scale=-2:720


问:
How to add links to all Heading 1 style text?
The code is intended to add the same hyperlink to all Heading 1 style text. (Purpose: clicking any heading brings you to the top of the document).

It works for the first Heading Style text. It does not advance to the next instance.

I found this was due to the line which adds the hyperlink. When this line is removed, all the Heading 1 style text is found (but of course then I can't add the link).

Sub addLinksToAllTextHavingCertainStyle()
Dim r As Range
Set r = ActiveDocument.Content
r.Find.ClearFormatting
Do
    With r.Find
        .Text = ""
        .Replacement.Text = ""
        .Style = "Heading 1"
        .Forward = True
        .Wrap = wdFindStop
        .Format = True
        .Execute
    End With
    r.Select 'for testing
    ActiveDocument.Hyperlinks.Add Anchor:=r, Address:="", SubAddress:="_top", ScreenTip:=""
Loop
End Sub
```

答:
You're looping the wrong part of the code. As written your code loops the entire find, which means it just starts over from the beginning each time.

It is only the execution of the Find that needs to be looped, the parameters you have set will remain. When Find is executed the range that the Find is executed on is redefined to the found match, so in a loop you need to collapse the range to the end to avoid the match being endlessly re-found.

```<code>Sub addLinksToAllTextHavingCertainStyle()
    Dim r As Range
    Set r = ActiveDocument.Content

    With r.Find
        .ClearFormatting
        .Text = ""
        .Replacement.Text = ""
        .Style = "Heading 1"
        .Forward = True
        .Wrap = wdFindStop
        .Format = True
    End With
    Do While r.Find.Execute = True
        ActiveDocument.Hyperlinks.Add Anchor:=r, Address:="", SubAddress:="_top", ScreenTip:=""
        r.Collapse wdCollapseEnd
    Loop
End Sub
</code>```

Body:
You're looping the wrong part of the code. As written your code loops the entire find, which means it just starts over from the beginning each time.

It is only the execution of the Find that needs to be looped, the parameters you have set will remain. When Find is executed the range that the Find is executed on is redefined to the found match, so in a loop you need to collapse the range to the end to avoid the match being endlessly re-found.

Sub addLinksToAllTextHavingCertainStyle()
    Dim r As Range
    Set r = ActiveDocument.Content

    With r.Find
        .ClearFormatting
        .Text = ""
        .Replacement.Text = ""
        .Style = "Heading 1"
        .Forward = True
        .Wrap = wdFindStop
        .Format = True
    End With
    Do While r.Find.Execute = True
        ActiveDocument.Hyperlinks.Add Anchor:=r, Address:="", SubAddress:="_top", ScreenTip:=""
        r.Collapse wdCollapseEnd
    Loop
End Sub


问:
Roll vector so max value is centered and order of values relative to it stay the same
How can I roll a vector so the max value is in the middle and the order of values relative to it stay the same?

If the length of the vector is even, then just put it in the mean value: n/2

If I have:
vec <- c(0, 2, 4, 3, 1, 8)

I want to return:
3 1 8 0 2 4

Thanks.

答:
You can use the SOfun package which has a function called shifter:

```<code>library(SOfun)

shifter(vec, which.max(vec) - length(vec) / 2)
</code>```

Output

```<code>[1] 3 1 8 0 2 4
</code>```

In the second case, you have:

```<code>vec <- c(0, 8, 4, 3, 1, 2)
</code>```

with max value before the middle, resulting in a negative shift:

```<code>shifter(vec, which.max(vec) - length(vec) / 2)
</code>```

Output

```<code>[1] 2 0 8 4 3 1
</code>```

Body:
You can use the SOfun package which has a function called shifter:

library(SOfun)

shifter(vec, which.max(vec) - length(vec) / 2)

Output

[1] 3 1 8 0 2 4

In the second case, you have:

vec <- c(0, 8, 4, 3, 1, 2)

with max value before the middle, resulting in a negative shift:

shifter(vec, which.max(vec) - length(vec) / 2)

Output

[1] 2 0 8 4 3 1


问:
SQL ALCHEMY- FAST API- API MODULE OBJECT NOT CALLABLE
end point to test sql alchemy. Error reads: module object is not callable? also the query word isn't highlighted. The tutorial says I should do db.query(models.Posts).all() but that's not working either. normally vs code highlights and auto-completes so i know its connecting to the right object.

when i type in db.query() the ide doesn't recognise the query method? i even imported it manually from sqlalchemy.orm and it still isn't recognised?? everything else works fine, just testing the orm via the query method is bugging.

Error says :   File "C:****/**/***lib\site-packages\sqlalchemy\orm\session.py", line 747, in _connection_for_bind
conn = bind.connect()
AttributeError: 'function' object has no attribute 'connect'

In the tutorial the teacher just types db. query(models.Post).all() and all the functions and methods are recognized. On mine query isn't recognized. Help please.

```<code>from logging import exception
from random import randrange
from tkinter.tix import STATUS
from typing import Optional
from urllib import response
from fastapi import Body, FastAPI, Query, Response ,status, HTTPException , Depends
from pydantic import BaseModel
import psycopg2
from psycopg2.extras import RealDictCursor
import time
from sqlalchemy import create_engine, engine_from_config
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,session , query

import models
from database import ormengine , SessionLocal , get_db

@app.get("/sqlalchemy")
def test_post(db: session= Depends(get_db)):
    post = db.query(models.Post).all()
    return {"data":post}
</code>```

models.py file is:

```<code>import string
from typing import Text
from xmlrpc.client import boolean
from database import Base, SessionLocal
from sqlalchemy import TIMESTAMP, Integer, PrimaryKeyConstraint, String, Boolean, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.expression import null , text
from sqlalchemy.sql.sqltypes import Text , TIMESTAMP

class Post(Base):
    __tablename__= 'apiproj2'

    id= Column( Integer , primary_key= True, nullable= False)
    title= Column( String, nullable= False)
    content = Column( String, nullable= False)
    published= Column(Boolean, server_default= 'True' , nullable=False)
    created_at = Column(TIMESTAMP( timezone=True), nullable= False , server_default= text('now()'))
</code>```

database.py

```<code>from sqlalchemy import create_engine, engine_from_config
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

 SQLALCHEMY_DATABASE_URL = "postgresql://postgres:naijalife@localhost/fastapi database"
    sqlalchemy_conn= 'postgresql://postgres:naija4life@localhost/fastapi database'
    ormengine= create_engine(sqlalchemy_conn)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind= engine_from_config )
    Base = declarative_base()

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
</code>```

答: I was calling the wrong engine, I should've called ormengine. The engine I created to connect to the database. The tutorial had an error in it. I changed this but it didn't work, after restarting vs code it worked. Thanks for the help guys.</p>

Body:
end point to test sql alchemy. Error reads: module object is not callable? also the query word isn't highlighted. The tutorial says I should do db.query(models.Posts).all() but that's not working either. normally vs code highlights and auto-completes so i know its connecting to the right object.

when i type in db.query() the ide doesn't recognise the query method? i even imported it manually from sqlalchemy.orm and it still isn't recognised?? everything else works fine, just testing the orm via the query method is bugging.

Error says :   File "C:****/**/***lib\site-packages\sqlalchemy\orm\session.py", line 747, in _connection_for_bind
conn = bind.connect()
AttributeError: 'function' object has no attribute 'connect'

In the tutorial the teacher just types db. query(models.Post).all() and all the functions and methods are recognized. On mine query isn't recognized. Help please.

from logging import exception
from random import randrange
from tkinter.tix import STATUS
from typing import Optional
from urllib import response
from fastapi import Body, FastAPI, Query, Response ,status, HTTPException , Depends
from pydantic import BaseModel
import psycopg2
from psycopg2.extras import RealDictCursor
import time
from sqlalchemy import create_engine, engine_from_config
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,session , query

import models
from database import ormengine , SessionLocal , get_db

@app.get("/sqlalchemy")
def test_post(db: session= Depends(get_db)):
    post = db.query(models.Post).all()
    return {"data":post}

models.py file is:

import string
from typing import Text
from xmlrpc.client import boolean
from database import Base, SessionLocal
from sqlalchemy import TIMESTAMP, Integer, PrimaryKeyConstraint, String, Boolean, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.expression import null , text
from sqlalchemy.sql.sqltypes import Text , TIMESTAMP

class Post(Base):
    __tablename__= 'apiproj2'

    id= Column( Integer , primary_key= True, nullable= False)
    title= Column( String, nullable= False)
    content = Column( String, nullable= False)
    published= Column(Boolean, server_default= 'True' , nullable=False)
    created_at = Column(TIMESTAMP( timezone=True), nullable= False , server_default= text('now()'))

database.py

from sqlalchemy import create_engine, engine_from_config
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

 SQLALCHEMY_DATABASE_URL = "postgresql://postgres:naijalife@localhost/fastapi database"
    sqlalchemy_conn= 'postgresql://postgres:naija4life@localhost/fastapi database'
    ormengine= create_engine(sqlalchemy_conn)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind= engine_from_config )
    Base = declarative_base()

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


问:
Drop foreign key without knowing the name of the constraint?
I have created one table using the below command:

```<code>create table Table1(
    Id int Not Null
        Foreign key
        references Table2(Id)
        on delete cascade
        on update cascade,
    UserName nvarchar(150),
    TimeInSeconds int Not Null

    primary key(Id,TimeInSeconds)
);
</code>```

But now I want to drop the foreign key.
As I haven't given a constraint name, I can't use:

```<code>Alter table <tablename>
drop foreign key <foreign key name>
</code>```

Is there any way?

答:
To drop a foreign key  use the following commands :

SHOW CREATE TABLE table_name;

ALTER TABLE table_name  DROP FOREIGN KEY table_name_ibfk_3;
("table_name_ibfk_3" is constraint  foreign key name assigned for unnamed constraints). It varies.

ALTER TABLE table_name DROP column_name.

Body:
I have created one table using the below command:

create table Table1(
    Id int Not Null
        Foreign key
        references Table2(Id)
        on delete cascade
        on update cascade,
    UserName nvarchar(150),
    TimeInSeconds int Not Null

    primary key(Id,TimeInSeconds)
);

But now I want to drop the foreign key.
As I haven't given a constraint name, I can't use:

Alter table <tablename>
drop foreign key <foreign key name>

Is there any way?


问:
Is possible to get the last string of an url as a param?
I cant get it with javascript URLSearchParams  function because it needs the "?" before.

Its possible to get the last string after last slash of an URL?

```<code>For ex:
mydomain.com/hello
mydomain.com/otherExample
</code>```

I need that "hello" be the param and stay in the index of my domain with the "param" value assigned to a var? Note that the "hello" page or directory doesn't exists.

Maybe is possible to manage it with the 404 error redirection?

答:
The Location object has a property that does exactly what you want:

```<code>window.location.pathname
</code>```

If you don't want the initial slash, you can remove it like so:

```<code>window.location.pathname.substring(1)
</code>```

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Location

Body:
I cant get it with javascript URLSearchParams  function because it needs the "?" before.

Its possible to get the last string after last slash of an URL?

For ex:
mydomain.com/hello
mydomain.com/otherExample

I need that "hello" be the param and stay in the index of my domain with the "param" value assigned to a var? Note that the "hello" page or directory doesn't exists.

Maybe is possible to manage it with the 404 error redirection?

Body:
The Location object has a property that does exactly what you want:

window.location.pathname

If you don't want the initial slash, you can remove it like so:

window.location.pathname.substring(1)

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Location


问:
How to change the theme of streamlit?
I'm having trouble changing the theme of my webapp. I'm using the Visual Studio Code program to program and there, I opened a folder named .streamlit and inside it, a file named config.toml. I pasted the theme changes, but when I refreshed the page, they were not saved. What could have happened?

My theme:

```<code>[theme]
base="dark"
primaryColor="#fff700"
</code>```

Print of Visual code:

答:
Check on the Menu > Settings > Theme:

There is a list of themes you can choose from:

Choose the "Custom Theme" from it.

Title: How to change the theme of streamlit?

Body:
I'm having trouble changing the theme of my webapp. I'm using the Visual Studio Code program to program and there, I opened a folder named .streamlit and inside it, a file named config.toml. I pasted the theme changes, but when I refreshed the page, they were not saved. What could have happened?

My theme:

[theme]
base="dark"
primaryColor="#fff700"

Print of Visual code:


问:
How to get data for react from php through json, preventing others from seeing these data?
I am getting from MySQL database data with PHP and converting them to JSON data so react get them.

PHP file:

```<code>    $trp = mysqli_query($conn, "SELECT * FROM react_php");
        $rows = array();
        while ($r = mysqli_fetch_assoc($trp)) {
            $rows[] = $r;
        }
        print json_encode($rows); //convert php data to json data
</code>```

React file:

```<code>    useEffect(() => {
            axios
              .get("http://localhost/react-php-sql/server/get-data.php/")
              .then((res) => {
                setData(res.data);
              });
          }, [data]);
</code>```

But the problem is that people can go to that URL and see these data. How can I prevent others from seeing them??

答:
If your application is going to be deployed, all info related to project which is private such as API key, API end-point can be in env File (this file is not deployed with source code) and once you deploy your web info is configured at server, and no one can access it

If you're afraid of other developers who can access your API end-point through the browser developer tool(by inspect) you can make your API routes protected

Body:
I am getting from MySQL database data with PHP and converting them to JSON data so react get them.

PHP file:

    $trp = mysqli_query($conn, "SELECT * FROM react_php");
        $rows = array();
        while ($r = mysqli_fetch_assoc($trp)) {
            $rows[] = $r;
        }
        print json_encode($rows); //convert php data to json data

React file:

    useEffect(() => {
            axios
              .get("http://localhost/react-php-sql/server/get-data.php/")
              .then((res) => {
                setData(res.data);
              });
          }, [data]);

But the problem is that people can go to that URL and see these data. How can I prevent others from seeing them??


问:
Find span element based on text written inside li Bs4 scraping
I want to find the text located in the
, if it exists I want to scrape the  text, but if it does not exist I will raise exception, for example:

```<code>if 'Floor' found then scrape the span
</code>```

This is my code and it works perfect but scraping everything without any condition :

```<code>import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

# Set base url & headers :
baseurl = 'https://aqarmap.com.eg'
headers = {
    'User_Agent' :
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
    }
test_link = 'https://aqarmap.com.eg/en/listing/3138984-for-rent-cairo-new-cairo-el-narges-el-narges-omarat'
r = requests.get(test_link , headers=headers)
soup = bs(r.content,'lxml')
title = soup.find('h1').text.replace('\n','')
loc = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
sub_loc = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
floor = soup.find('span' , class_='badge badge-default').text.replace('\n','')
room = soup.find('span' , class_='badge badge-default').find_next('span').text.replace('\n','')
baths = soup.find('span' , class_='badge badge-default').find_next('span').text.replace('\n','')
finish = soup.find('span' , class_='badge badge-default').find_next('span').find_next('span').find_next('span').text.replace('\n','')
view = soup.find('span' , class_='badge badge-default').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
area = soup.find('span' , class_='badge badge-default').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
date = soup.find('span' , class_='badge badge-default').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
price = soup.find('div' , class_='listing-price-content').find_next('span').text
print(title,loc,sub_loc,floor,room,baths,finish,view,area,date,price)
</code>```

答:
In general, it would be good to check if the tag you are looking for exists before applying the text method:

```<code>title = title.text.strip() if (title := soup.find('h1')) else None
</code>```

To select tag by text and check if it exists, you can go with css selectors and -soup-contains():

```<code>floor = tag.text.strip() if (tag := soup.select_one('ul.list-group li:-soup-contains("Floor") span')) else None
</code>```

Above works well for some tags, but to go generic and get rid of these confusing property selections, I would suggest the following - Use a dict to store the information in a list of dicts. So you are save if you create a dataframe based on it and a propertiy is missing. Pandas will fill this outomatically with nan.

```<code>data = {}
data['title'] = soup.find('h1').text.strip()
data['loc'] = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
data['sub_loc'] = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
data.update(dict([li.stripped_strings for li in soup.select('ul.list-group li')]))
</code>```

Benefits - You can do adjustments simple, filter if you like and export results in a strucured way.

Example

```<code>import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

baseurl = 'https://aqarmap.com.eg'
headers = {
    'User_Agent' :
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
    }

data = []

def scrape(test_link):
    r = requests.get(test_link , headers=headers)
    soup = bs(r.content,'lxml')

    data = {}
    data['title'] = soup.find('h1').text.strip()
    data['loc'] = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
    data['sub_loc'] = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
    data.update(dict([li.stripped_strings for li in soup.select('ul.list-group li')]))
    return data

urlList = ['https://aqarmap.com.eg/en/listing/3138984-for-rent-cairo-new-cairo-el-narges-el-narges-omarat',
           'https://aqarmap.com.eg/en/listing/3124476-for-rent-cairo-new-cairo-el-narges-el-narges-omarat?source=related-listing-source']

for url in urlList:
    data.append(scrape(url))

pd.DataFrame(data)
</code>```

Output

title
loc
sub_loc
Floor
Room
Baths
Finish Type
Size (in meters)
Listing ID
Publish Date
Price
Seller Role
Payment Method
Price Per Meter
View

Furnished Apartment For rent in El Narges Omarat
El Narges
El Narges Omarat
3
3
2
SUPER_LUX
180 M²
EG-3138984
09/01/2022
19,000 EGP
Agent
Cash
106 EGP/M²
nan

Furnished Apartment For rent in El Narges Omarat
El Narges
El Narges Omarat
2
2
2
SUPER_LUX
180 M²
EG-3124476
30/12/2021
19,000 EGP
Agent
Cash
106 EGP/M²
Garden

Body:
I want to find the text located in the
, if it exists I want to scrape the  text, but if it does not exist I will raise exception, for example:

if 'Floor' found then scrape the span

This is my code and it works perfect but scraping everything without any condition :

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

# Set base url & headers :
baseurl = 'https://aqarmap.com.eg'
headers = {
    'User_Agent' :
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
    }
test_link = 'https://aqarmap.com.eg/en/listing/3138984-for-rent-cairo-new-cairo-el-narges-el-narges-omarat'
r = requests.get(test_link , headers=headers)
soup = bs(r.content,'lxml')
title = soup.find('h1').text.replace('\n','')
loc = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
sub_loc = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
floor = soup.find('span' , class_='badge badge-default').text.replace('\n','')
room = soup.find('span' , class_='badge badge-default').find_next('span').text.replace('\n','')
baths = soup.find('span' , class_='badge badge-default').find_next('span').text.replace('\n','')
finish = soup.find('span' , class_='badge badge-default').find_next('span').find_next('span').find_next('span').text.replace('\n','')
view = soup.find('span' , class_='badge badge-default').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
area = soup.find('span' , class_='badge badge-default').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
date = soup.find('span' , class_='badge badge-default').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
price = soup.find('div' , class_='listing-price-content').find_next('span').text
print(title,loc,sub_loc,floor,room,baths,finish,view,area,date,price)

Body:
In general, it would be good to check if the tag you are looking for exists before applying the text method:

title = title.text.strip() if (title := soup.find('h1')) else None

To select tag by text and check if it exists, you can go with css selectors and -soup-contains():

floor = tag.text.strip() if (tag := soup.select_one('ul.list-group li:-soup-contains("Floor") span')) else None

Above works well for some tags, but to go generic and get rid of these confusing property selections, I would suggest the following - Use a dict to store the information in a list of dicts. So you are save if you create a dataframe based on it and a propertiy is missing. Pandas will fill this outomatically with nan.

data = {}
data['title'] = soup.find('h1').text.strip()
data['loc'] = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
data['sub_loc'] = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
data.update(dict([li.stripped_strings for li in soup.select('ul.list-group li')]))

Benefits - You can do adjustments simple, filter if you like and export results in a strucured way.

Example

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

baseurl = 'https://aqarmap.com.eg'
headers = {
    'User_Agent' :
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
    }

data = []

def scrape(test_link):
    r = requests.get(test_link , headers=headers)
    soup = bs(r.content,'lxml')

    data = {}
    data['title'] = soup.find('h1').text.strip()
    data['loc'] = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
    data['sub_loc'] = soup.find('span', {'property':'name'}).find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').find_next('span').text.replace('\n','')
    data.update(dict([li.stripped_strings for li in soup.select('ul.list-group li')]))
    return data

urlList = ['https://aqarmap.com.eg/en/listing/3138984-for-rent-cairo-new-cairo-el-narges-el-narges-omarat',
           'https://aqarmap.com.eg/en/listing/3124476-for-rent-cairo-new-cairo-el-narges-el-narges-omarat?source=related-listing-source']

for url in urlList:
    data.append(scrape(url))

pd.DataFrame(data)

Output

title
loc
sub_loc
Floor
Room
Baths
Finish Type
Size (in meters)
Listing ID
Publish Date
Price
Seller Role
Payment Method
Price Per Meter
View

Furnished Apartment For rent in El Narges Omarat
El Narges
El Narges Omarat
3
3
2
SUPER_LUX
180 M²
EG-3138984
09/01/2022
19,000 EGP
Agent
Cash
106 EGP/M²
nan

Furnished Apartment For rent in El Narges Omarat
El Narges
El Narges Omarat
2
2
2
SUPER_LUX
180 M²
EG-3124476
30/12/2021
19,000 EGP
Agent
Cash
106 EGP/M²
Garden


答: If you think about -1 and -2 like about -n then this sets the specified dimension (width, height) to be a multiple of n.

Title: FFMEG option scale=-1 and scale=-2


问:
Using inline view in SQL
I have a database table with employees (emp) with colomns name and salary. By using an inline view query i would like to list name, salary and a new colomn with each employees % of the total salary of all employees (salary/tot_sal*100). I am having trouble understanding the use of views. I tried the following code, but it did not work. Any ideas?</p>
```<code>create view tot_sal as
select sum(sal);

select name, salary, salary/tot_sal*100
from tot_sal
</code>```

Title: Using inline view in SQL

Body:
I have a database table with employees (emp) with colomns name and salary. By using an inline view query i would like to list name, salary and a new colomn with each employees % of the total salary of all employees (salary/tot_sal*100). I am having trouble understanding the use of views. I tried the following code, but it did not work. Any ideas?

create view tot_sal as
select sum(sal);

select name, salary, salary/tot_sal*100
from tot_sal

Body:
Try:

create view tot_sal_view as select name,salary, salary/(select sum(salary) from employees e)*100
from employees;

Given example:

CREATE TABLE employees (
name varchar(50)  ,
salary decimal(10,2)
);

INSERT INTO employees  VALUES
('Steven',24000.00),
('Neena',17000.00),
('Lex',17000.00),
('Alexander',9000.00),
('Bruce',6000.00),
('David',4800.00),
('Valli',4800.00),
('Diana',4200.00),
('Nancy',12000.00),
('Daniel',9000.00),
('John',8200.00),
('Ismael',7700.00),
('Jose Manuel ',7800.00),
('Luis', 6900.00),
('Den',11000.00),
('Alexander',3100.00),
('Shelli',2900.00);

Result:

name         salary salary/(select sum(salary) from employees e)*100
Steven      24000.00    15.444015
Neena       17000.00    10.939511
Lex         17000.00    10.939511
Alexander   9000.00    5.791506
Bruce       6000.00    3.861004
David       4800.00    3.088803
Valli       4800.00    3.088803
Diana       4200.00    2.702703
Nancy       12000.00    7.722008
Daniel      9000.00    5.791506
John        8200.00    5.276705
Ismael      7700.00    4.954955
Jose Manuel 7800.00    5.019305
Luis        6900.00    4.440154
Den         11000.00   7.078507
Alexander   3100.00    1.994852
Shelli      2900.00    1.866152

Check the demo


问:
No module named 'virtualenv.activation.xonsh'
I triyed to execute pipenv shell in a new environtment and I got the following error:

```<code>Loading .env environment variables…
Creating a virtualenv for this project…
Using /home/user/.pyenv/shims/python3.9 (3.9.7) to create virtualenv…
⠋ModuleNotFoundError: No module named 'virtualenv.activation.xonsh'
Error while trying to remove the /home/user/.local/share/virtualenvs/7t env:
No such file or directory

Virtualenv location:
Warning: Your Pipfile requires python_version 3.9, but you are using None (/bin/python).
  $ pipenv check will surely fail.
Spawning environment shell (/usr/bin/zsh). Use 'exit' to leave.
</code>```

I tried to remove pipenv, install python with pienv create an alias to python, but anything works.

Any idea, I got the same error in existing environment, I tried to remove all environments folder but nothing.

Thanks.

答:
By github issue, the solution that works was the following:</p>
```<code>sudo apt-get remove python3-virtualenv
</code>```

Body:
I triyed to execute pipenv shell in a new environtment and I got the following error:

Loading .env environment variables…
Creating a virtualenv for this project…
Using /home/user/.pyenv/shims/python3.9 (3.9.7) to create virtualenv…
⠋ModuleNotFoundError: No module named 'virtualenv.activation.xonsh'
Error while trying to remove the /home/user/.local/share/virtualenvs/7t env:
No such file or directory

Virtualenv location:
Warning: Your Pipfile requires python_version 3.9, but you are using None (/bin/python).
  $ pipenv check will surely fail.
Spawning environment shell (/usr/bin/zsh). Use 'exit' to leave.

I tried to remove pipenv, install python with pienv create an alias to python, but anything works.

Any idea, I got the same error in existing environment, I tried to remove all environments folder but nothing.

Thanks.

Body:
By github issue, the solution that works was the following:

sudo apt-get remove python3-virtualenv


问:
Sorting Algorithm output at end of pass 3
Given the following initially unsorted list:

[77, 101, 40, 43, 81, 129, 85, 144]

Which sorting algorithm produces the following list at the end of Pass Number 3? Is it Bubble, Insertion or Selection?

[40, 43, 77, 81, 85, 101, 129, 144]

Can someone give me a clue on how I can solve this please.

答:
Insertion sort would change the relative order of at most 3 items in 3 passes resulting in the first 3 items being in order and the rest unchanged.  Selection sort would affect only the positions of the first 3 items and the 3 smallest (or greatest) items.  Only the bubble sort would swap other items around.  The movements of 40 and 129 is a telltale sign that points to a Bubble sort.

Note that this may be a trick question because all numbers that need to be shifted are at most 2 positions off except 2 of them (101 & 129 which are the 2nd and 3rd largest and would end up in their right places after 2 passes). A properly implemented Bubble sort would not get to a 3rd pass.  So the answer could be "none of them"


问:
Android Studio unable to Git Push -- I can through terminal
I am no longer able to push to github via Android Studio. Everytime I try I now get this error message:

The operation couldn't be completed. Unable to locate a Java Runtime. Please visit http://www.java.com for information on installing Java. error: failed to push some refs to 'github.com:xxxxxxxxxx'

Not sure what caused the issue, just started happening one morning (although it was after updating Android Studio to Bumblebee).

I can use the terminal to push just fine, but would really like to get this issue fixed as it's just an easier workflow.

答: Enable -> Use credential helper

Body: Enable -> Use credential helper


问:
Use of Linkedlist
i studied that we use LinkedList if we want more number of insertion / deletion ;
And we use ArrayList if we have more retravision.

But my doubt is in programming all insertion needs retrivtion at every time , otherwise insertion is nearly useless. At everytime for manipulating, for calculation every time we need to retrive data.

So why we should use Linkedlist ?

答:
Let’s consider a program that does the following actions:

adds n elements to the end of the list

retrieves the first element from the list n times.

In this case, if you use LinkedList all insertions will take O(1) time and all retrievals will also take O(1).

On the other hand, if you use ArrayList, you may need to increase the array size of the array backing the list multiple times , each times requires to duplicate the array which takes O(n).
When you do the retrievals, depending on the implementation, you may need to decrease the array size multiple times, each time takes O(n) once again.

So as you can see, there are cases where LinkedList has advantages on ArrayList.

This mainly results from the individual operation time complexity of each data structure, as demonstrated above.

Title: Use of Linkedlist


问:
Github API number of watch over time
I am trying to fetch the number of watches over time using Python, I have tried "https://api.github.com/repos/octocat/hello-world/subscription" that is listed on the Github API webpage, but seems no longer work, I am a bit confused. I am just trying to get "created_at" under subscription. Any suggestions? Thank you.</p>

答:
EDIT - as per your first comment and extra requirements: Unfortunately I do not think it is possible to get watchers over time, you can however get the stargazers over time, an example using GitHub's GraphQL API is below. To do so you can use the following:

```<code>import requests

MY_TOKEN = my_token
REPO_NAME = repo_name
REPO_OWNER = repo_owner

query = f'''{{
              repository(name: "{REPO_NAME}", owner: "{REPO_OWNER}") {{
                watchers {{
                  totalCount
                }}
                stargazers(first: 100) {{
                  totalCount
                  edges {{
                    starredAt
                  }}
                }}
              }}
            }}
            '''

headers = {"Authorization": f"token {MY_TOKEN}"}

request = requests.post("https://api.github.com/graphql", json={"query": query}, headers=headers)

print(request.json())
</code>```

Which will output a result like the following:

```<code>{
  "data": {
    "repository": {
      "watchers": {
        "totalCount": 1594
      },
      "stargazers": {
        "totalCount": 53952,
        "edges": [
          {
            "starredAt": "2016-08-15T18:39:55Z"
          },
          {
            "starredAt": "2016-08-15T19:14:32Z"
          }
        ]
      }
    }
  }
}

</code>```

You can easily try out GitHub's GraphQL API in the explorer they provide (one click to run a query). Just use the following query as an example (and replace the repo name and owner as you wish):

```<code>{
  repository(name: "repo_name", owner: "repo_owner") {
    watchers {
      totalCount
    }
    stargazers(first:100) {
      totalCount
      edges {
        starredAt
      }
    }
  }
}
</code>```

Note you should now be careful for pagination (see first:... parameter).

Title: Github API number of watch over time

Body:
EDIT - as per your first comment and extra requirements: Unfortunately I do not think it is possible to get watchers over time, you can however get the stargazers over time, an example using GitHub's GraphQL API is below. To do so you can use the following:

import requests

MY_TOKEN = my_token
REPO_NAME = repo_name
REPO_OWNER = repo_owner

query = f'''{{
              repository(name: "{REPO_NAME}", owner: "{REPO_OWNER}") {{
                watchers {{
                  totalCount
                }}
                stargazers(first: 100) {{
                  totalCount
                  edges {{
                    starredAt
                  }}
                }}
              }}
            }}
            '''

headers = {"Authorization": f"token {MY_TOKEN}"}

request = requests.post("https://api.github.com/graphql", json={"query": query}, headers=headers)

print(request.json())

Which will output a result like the following:

{
  "data": {
    "repository": {
      "watchers": {
        "totalCount": 1594
      },
      "stargazers": {
        "totalCount": 53952,
        "edges": [
          {
            "starredAt": "2016-08-15T18:39:55Z"
          },
          {
            "starredAt": "2016-08-15T19:14:32Z"
          }
        ]
      }
    }
  }
}

You can easily try out GitHub's GraphQL API in the explorer they provide (one click to run a query). Just use the following query as an example (and replace the repo name and owner as you wish):

{
  repository(name: "repo_name", owner: "repo_owner") {
    watchers {
      totalCount
    }
    stargazers(first:100) {
      totalCount
      edges {
        starredAt
      }
    }
  }
}

Note you should now be careful for pagination (see first:... parameter).


问:
How to work around "A catch-all parameter can only appear as the last segment of the route template."
If I have a controller with an action method that uses attribute based routing and declare it like this, all is well:

```<code>    [HttpGet]
    [Route("/dev/info/{*somevalue}")]
    public IActionResult Get(string somevalue) {

        return View();
    }
</code>```

I can route to the above action method for example by specifying a url that ends in /dev/info/hello-world or /dev/info/new-world

However my business requirement is to have a urls that look like this: /dev/hello-world/info or /dev/new-world/info  And there is an endless set of such urls that all need to route to the same action method on the controller.

I thought to set up the attribute based route on the action method as follows:

```<code>    [HttpGet]
    [Route("/dev/{*somevalue}/info/")]
    public IActionResult Get(string somevalue) {

        return View();
    }
</code>```

But when I do that I get the following error as soon as the web project runs:

An unhandled exception occurred while processing the request.
  RouteCreationException: The following errors occurred with attribute routing information:

For action: 'App.SomeController.Get (1-wwwSomeProject)'
  Error: A catch-all parameter can only appear as the last segment of the route template.
  Parameter name: routeTemplate
  Microsoft.AspNetCore.Mvc.Internal.AttributeRoute.GetRouteInfos(IReadOnlyList actions)

There has to be some way to work around this error.  Know a way?

答:
Middleware is the way to achieve this.

If you need an api response is easy to implement inline.

if (app.Environment.IsDevelopment())
{
    app.Use(async (context, next) =>
    {
        Console.WriteLine(context.Request.Path);
        if (context.Request.Path.ToString().EndsWith("/info"))
        {
            // some logic
            await context.Response.WriteAsync("Terminal Middleware.");
            return;
        }

        await next(context);
    });
}
```

If you need to call a controller you can simply edit request path via middleware to achieve your requirement.

You can find an example here: https://stackoverflow.com/a/50010787/3120219

Body:
If I have a controller with an action method that uses attribute based routing and declare it like this, all is well:

    [HttpGet]
    [Route("/dev/info/{*somevalue}")]
    public IActionResult Get(string somevalue) {

        return View();
    }

I can route to the above action method for example by specifying a url that ends in /dev/info/hello-world or /dev/info/new-world

However my business requirement is to have a urls that look like this: /dev/hello-world/info or /dev/new-world/info  And there is an endless set of such urls that all need to route to the same action method on the controller.

I thought to set up the attribute based route on the action method as follows:

    [HttpGet]
    [Route("/dev/{*somevalue}/info/")]
    public IActionResult Get(string somevalue) {

        return View();
    }

But when I do that I get the following error as soon as the web project runs:

An unhandled exception occurred while processing the request.
  RouteCreationException: The following errors occurred with attribute routing information:

For action: 'App.SomeController.Get (1-wwwSomeProject)'
  Error: A catch-all parameter can only appear as the last segment of the route template.
  Parameter name: routeTemplate
  Microsoft.AspNetCore.Mvc.Internal.AttributeRoute.GetRouteInfos(IReadOnlyList actions)

There has to be some way to work around this error.  Know a way?

Body:
Middleware is the way to achieve this.

If you need an api response is easy to implement inline.

if (app.Environment.IsDevelopment())
{
    app.Use(async (context, next) =>
    {
        Console.WriteLine(context.Request.Path);
        if (context.Request.Path.ToString().EndsWith("/info"))
        {
            // some logic
            await context.Response.WriteAsync("Terminal Middleware.");
            return;
        }

        await next(context);
    });
}

If you need to call a controller you can simply edit request path via middleware to achieve your requirement.

You can find an example here: https://stackoverflow.com/a/50010787/3120219


Title: Sorting Algorithm output at end of pass 3

Body:
Given the following initially unsorted list:

[77, 101, 40, 43, 81, 129, 85, 144]

Which sorting algorithm produces the following list at the end of Pass Number 3? Is it Bubble, Insertion or Selection?

[40, 43, 77, 81, 85, 101, 129, 144]

Can someone give me a clue on how I can solve this please.

Body:
Insertion sort:

def insertion_sort(array):
    for i in range(1, len(array)):
        key_item = array[i]
        j = i - 1
        while j >= 0 and array[j] > key_item:
            array[j + 1] = array[j]
            j -= 1
        array[j + 1] = key_item
        print("Step",i,":",array)
    return array

data=[77, 101, 40, 43, 81, 129, 85, 144]
insertion_sort(data)

Output:

Step 1 : [77, 101, 40, 43, 81, 129, 85, 144]
Step 2 : [40, 77, 101, 43, 81, 129, 85, 144]
Step 3 : [40, 43, 77, 101, 81, 129, 85, 144]
Step 4 : [40, 43, 77, 81, 101, 129, 85, 144]
Step 5 : [40, 43, 77, 81, 101, 129, 85, 144]
Step 6 : [40, 43, 77, 81, 85, 101, 129, 144]
Step 7 : [40, 43, 77, 81, 85, 101, 129, 144]

Bubble sort:

def bubble_sort(array):
    n = len(array)
    for i in range(n):
        already_sorted = True
        for j in range(n - i - 1):
            if array[j] > array[j + 1]:
                array[j], array[j + 1] = array[j + 1], array[j]
                already_sorted = False
        if already_sorted:
            break
        print("Step:",n-j-1)
        print(array)
    return array

data = [77, 101, 40, 43, 81, 129, 85, 144]
bubble_sort(data)

Output:

Step: 1
[77, 40, 43, 81, 101, 85, 129, 144]
Step: 2
[40, 43, 77, 81, 85, 101, 129, 144]

Selection Sort:

def selectionSort(array, size):
    for step in range(size):
        min_idx = step

        for i in range(step + 1, size):
            if array[i] < array[min_idx]:
                min_idx = i
        (array[step], array[min_idx]) = (array[min_idx], array[step])
        print("step",step+1,":",end="")

        print(array)

data = [77, 101, 40, 43, 81, 129, 85, 144]
size = len(data)
selectionSort(data, size)

Output:

step 1 :[40, 101, 77, 43, 81, 129, 85, 144]
step 2 :[40, 43, 77, 101, 81, 129, 85, 144]
step 3 :[40, 43, 77, 101, 81, 129, 85, 144]
step 4 :[40, 43, 77, 81, 101, 129, 85, 144]
step 5 :[40, 43, 77, 81, 85, 129, 101, 144]
step 6 :[40, 43, 77, 81, 85, 101, 129, 144]
step 7 :[40, 43, 77, 81, 85, 101, 129, 144]
step 8 :[40, 43, 77, 81, 85, 101, 129, 144]

You can also get more guidelines from the link below how to run algorithms:
https://realpython.com/sorting-algorithms-python/