问:
Multiprocessing with Matplotlib Animation
In short, I am trying to run a live monitoring dashboard while calculating data in the background. Here is the code for my monitoring dashboard:

```<code>import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
import psutil
import collections

# function to update the data
def monitor_machine_metrics(i):
    cpu_metrics.popleft()
    cpu_metrics.append(psutil.cpu_percent(interval=1))
    ram_metrics.popleft()
    ram_metrics.append(psutil.virtual_memory().percent)

    # clear axis
    ax.cla()
    ax1.cla()

    # plot cpu usage
    ax.plot(cpu_metrics)
    ax.text(len(cpu_metrics)-1, cpu_metrics[-1]+2, "{}%".format(cpu_metrics[-1]))
    ax.set_ylim(0,100)

    # plot memory usage
    ax1.plot(ram_metrics)
    ax1.text(len(ram_metrics)-1, ram_metrics[-1]+2, "{}%".format(ram_metrics[-1]))
    ax1.set_ylim(0,100)
    legend = plt.legend(['CPU Usage', 'RAM Usage'], loc='upper left')
    return legend

# start collections with zeros
cpu_metrics = collections.deque(np.zeros(10))
ram_metrics = collections.deque(np.zeros(10))
usage_fig = plt.figure()
ax = plt.subplot()
ax1 = plt.subplot()

def display_dynamic_data(figure, funct, time_interval):
    ani = FuncAnimation(figure, funct, interval=time_interval)
    plt.show()
</code>```

For the sake of keeping this simple, let's pretend I just want to print hi while the dashboard is running.

```<code>if __name__ == '__main__':
    machine_monitoring_process =
    multiprocessing.Process(target=display_dynamic_data,args=(usage_fig, monitor_machine_metrics, 1000))
    machine_monitoring_process.start()

    print('Hi')
</code>```

Since FuncAnimation runs similar to an infinite loop, I purposely designed for this sub-process to be completely decoupled. While 'hi' prints, the figure comes up but no points will be displayed. However, display_dynamic_data works just fine if we just call the function instead of instantiating it as a sub-process. Unfortunately, I need this to run in parallel, since the real code is doing computations in the background.

Is there something that I am missing here?

答:
When you use multiprocessing.Process, a new process with its own memory and objects is created. Code running in the new process has no effect in the original one. If you want to interchange information, you should use queues or other type of information exchange mechanism.

In your example, display_dynamic_data runs in the new process and exits. Remember that you must keep a reference to the FuncAnimation object to prevent it from being garbage collected.

You can check this answer to grasp what happens when you use multiprocessing.

Body:
In short, I am trying to run a live monitoring dashboard while calculating data in the background. Here is the code for my monitoring dashboard:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
import psutil
import collections

# function to update the data
def monitor_machine_metrics(i):
    cpu_metrics.popleft()
    cpu_metrics.append(psutil.cpu_percent(interval=1))
    ram_metrics.popleft()
    ram_metrics.append(psutil.virtual_memory().percent)

    # clear axis
    ax.cla()
    ax1.cla()

    # plot cpu usage
    ax.plot(cpu_metrics)
    ax.text(len(cpu_metrics)-1, cpu_metrics[-1]+2, "{}%".format(cpu_metrics[-1]))
    ax.set_ylim(0,100)

    # plot memory usage
    ax1.plot(ram_metrics)
    ax1.text(len(ram_metrics)-1, ram_metrics[-1]+2, "{}%".format(ram_metrics[-1]))
    ax1.set_ylim(0,100)
    legend = plt.legend(['CPU Usage', 'RAM Usage'], loc='upper left')
    return legend

# start collections with zeros
cpu_metrics = collections.deque(np.zeros(10))
ram_metrics = collections.deque(np.zeros(10))
usage_fig = plt.figure()
ax = plt.subplot()
ax1 = plt.subplot()

def display_dynamic_data(figure, funct, time_interval):
    ani = FuncAnimation(figure, funct, interval=time_interval)
    plt.show()

For the sake of keeping this simple, let's pretend I just want to print hi while the dashboard is running.

if __name__ == '__main__':
    machine_monitoring_process =
    multiprocessing.Process(target=display_dynamic_data,args=(usage_fig, monitor_machine_metrics, 1000))
    machine_monitoring_process.start()

    print('Hi')

Since FuncAnimation runs similar to an infinite loop, I purposely designed for this sub-process to be completely decoupled. While 'hi' prints, the figure comes up but no points will be displayed. However, display_dynamic_data works just fine if we just call the function instead of instantiating it as a sub-process. Unfortunately, I need this to run in parallel, since the real code is doing computations in the background.

Is there something that I am missing here?


来源: stackexchange

问:
Javascript for simple menu expanding
Hi I'm new to JavaScript and I want to code a very simple expanding submenu.

```<code><div id="submenu">
  <ul>
   <li>
     Something
   </li>
   <li>
     Another
   </li>
 </ul>
 <div id="submenu-1" class="submenu-options">
  <ul>
   <li>Something-sub</li>
   <li>Something-sub</li>
   <li>Something-sub</li>
  </ul>
 </div>
 <div id="submenu-2" class="submenu-options">
  <ul>
   <li>Another-sub</li>
   <li>Another-sub</li>
   <li>Another-sub</li>
  </ul>
 </div>
</div>
</code>```

To be more specific, if I hover over something I want the something submenu displayed if the mouse leaves I want it to be hidden again...
I know it has been asked a lot and there are many ways to do this but Google brought up too many unsatisfying answers.
I hope you can spare 10 minutes to help me out of my misery

Regards and thank you!

答:
You do not need java for this just plain CSS will do:</p>

```<code>li#submenu:hover div {
    display: block;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript for simple menu expanding

Body:
Hi I'm new to JavaScript and I want to code a very simple expanding submenu.

     Something

     Another

Something-sub

Something-sub

Something-sub

Another-sub

Another-sub

Another-sub

To be more specific, if I hover over something I want the something submenu displayed if the mouse leaves I want it to be hidden again...
I know it has been asked a lot and there are many ways to do this but Google brought up too many unsatisfying answers.
I hope you can spare 10 minutes to help me out of my misery

Regards and thank you!

Body:
You do not need java for this just plain CSS will do:

li#submenu:hover div {
    display: block;
}


问:
Enable / Disable columns in Intractive Grid conditionally Oracle
I need to Enable/Disable some columns in Intractive grid on conditionally.

For ex:

If my Grid is having columns like

If status is Approved then user can edit the columns and modify, if the status is rejected or cancelled the column should disable automatically..

**Status     Name   Dob   Mobile

Approved     enable the following column to modify or edit

Rejected     disable all the columns name,Dob,mobile

Cancelled    disable all the columns name,Dob,mobile**

if its rejected or cancelled we are not entering or modifying those records

答:
In 21.2 it is possible to create a dynamic action on change of "Status" with action "Disable". Set the action to "Fire on initialization" to ensure the columns are disabled on load and make sure to create an opposite action. On the dynamic action set a client side condition of "Item = Value".
In your case, create a dynamic action with client side condition Item = Value for status "Approved", a true action to enabled the columns and a false action to disable the columns.
I can't test this on earlier versions, but this functionality has been around for a while.</p>

ContentLicense: CC BY-SA 4.0


问:
How can I define a django model's field default value to be another field value?
In my model I have these two fields:

```<code>start_bid = models.IntegerField(default=0)
max_bid =  models.IntegerField(default="the start_bid value")
</code>```

The start_bid will be added by the user once through Django ModelForm. And the max_bid may change and may not.
So I need the first value of 'max_bid' to be the start_bid value entered by the user, then if it changes it will be updated.

In brief, I need the initial value of max_bid to be equal to the start_bid!

Any suggestions?

答:
Here is the solution:</p>
```<code>class Bid(models.Model):
          start_bid = models.IntegerField(default=0)
          max_bid =  models.IntegerField()

          def save(self,*args,**kwargs):
               if not self.max_bid:
                   self.max_bid = self.start_bid

               super(Bid,self).save(*args,**kwargs) #here Bid is my model name. Don't forget to replace Bid with your model name.
</code>```

Body:
In my model I have these two fields:

start_bid = models.IntegerField(default=0)
max_bid =  models.IntegerField(default="the start_bid value")

The start_bid will be added by the user once through Django ModelForm. And the max_bid may change and may not.
So I need the first value of 'max_bid' to be the start_bid value entered by the user, then if it changes it will be updated.

In brief, I need the initial value of max_bid to be equal to the start_bid!

Any suggestions?

Body:
Here is the solution:

class Bid(models.Model):
          start_bid = models.IntegerField(default=0)
          max_bid =  models.IntegerField()

          def save(self,*args,**kwargs):
               if not self.max_bid:
                   self.max_bid = self.start_bid

               super(Bid,self).save(*args,**kwargs) #here Bid is my model name. Don't forget to replace Bid with your model name.


问:
select row in heavy csv
i search how can i select some row with word in line so i use this script

```<code>import pandas
import datetime

df = pandas.read_csv(
    r"C:StockEtablissement_utf8(1)\StockEtablissement_utf8.csv",
    sep=",",
)

communes = ["PERPIGNAN"]

print()

df = df[~df["libelleCommuneEtablissement"].isin(communes)]

print()
</code>```

so my script work well with a normal csv

but with a heavy Csv (4Go) the scipt say :

```<code>Traceback (most recent call last):
  File "C:lafinessedufiness.py", line 5, in <module>
    df = pandas.read_csv(r'C:StockEtablissement_utf8(1)\StockEtablissement_utf8.csv',
  File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers\readers.py", line 680, in read_csv
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers\readers.py", line 581, in _read
    return parser.read(nrows)
  File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers\readers.py", line 1250, in read
    index, columns, col_dict = self._engine.read(nrows)
  File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py", line 225, in read
    chunks = self._reader.read_low_memory(nrows)
  File "pandas\_libs\parsers.pyx", line 805, in pandas._libs.parsers.TextReader.read_low_memory
  File "pandas\_libs\parsers.pyx", line 883, in pandas._libs.parsers.TextReader._read_rows
  File "pandas\_libs\parsers.pyx", line 1026, in pandas._libs.parsers.TextReader._convert_column_data
  File "pandas\_libs\parsers.pyx", line 1072, in pandas._libs.parsers.TextReader._convert_tokens
  File "pandas\_libs\parsers.pyx", line 1172, in pandas._libs.parsers.TextReader._convert_with_dtype
  File "pandas\_libs\parsers.pyx", line 1731, in pandas._libs.parsers._try_int64
MemoryError: Unable to allocate 128. KiB for an array with shape (16384,) and data type int64
</code>```

do you know how can i fix this error please?

答:
The pd.read_csv() function has an option to read the file in chunks, rather than loading it all at once.  Use iterator=True and specify a reasonable chunk size (rows per chunk).

import pandas as pd

path = r'C:StockEtablissement_utf8(1)\StockEtablissement_utf8.csv'
it = pd.read_csv(path, sep=',', iterator=True, chunksize=10_000)

communes = ['PERPIGNAN']

filtered_chunks = []
for chunk_df in it:
    chunk_df = chunk_df.query('libelleCommuneEtablissement not in @communes')
    filtered_chunks.append(chunk_df)

df = pd.concat(filtered_chunks)
```

Title: select row in heavy csv

Body:
i search how can i select some row with word in line so i use this script

import pandas
import datetime

df = pandas.read_csv(
    r"C:StockEtablissement_utf8(1)\StockEtablissement_utf8.csv",
    sep=",",
)

communes = ["PERPIGNAN"]

print()

df = df[~df["libelleCommuneEtablissement"].isin(communes)]

print()

so my script work well with a normal csv

but with a heavy Csv (4Go) the scipt say :

Traceback (most recent call last):
  File "C:lafinessedufiness.py", line 5, in <module>
    df = pandas.read_csv(r'C:StockEtablissement_utf8(1)\StockEtablissement_utf8.csv',
  File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers\readers.py", line 680, in read_csv
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers\readers.py", line 581, in _read
    return parser.read(nrows)
  File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers\readers.py", line 1250, in read
    index, columns, col_dict = self._engine.read(nrows)
  File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py", line 225, in read
    chunks = self._reader.read_low_memory(nrows)
  File "pandas\_libs\parsers.pyx", line 805, in pandas._libs.parsers.TextReader.read_low_memory
  File "pandas\_libs\parsers.pyx", line 883, in pandas._libs.parsers.TextReader._read_rows
  File "pandas\_libs\parsers.pyx", line 1026, in pandas._libs.parsers.TextReader._convert_column_data
  File "pandas\_libs\parsers.pyx", line 1072, in pandas._libs.parsers.TextReader._convert_tokens
  File "pandas\_libs\parsers.pyx", line 1172, in pandas._libs.parsers.TextReader._convert_with_dtype
  File "pandas\_libs\parsers.pyx", line 1731, in pandas._libs.parsers._try_int64
MemoryError: Unable to allocate 128. KiB for an array with shape (16384,) and data type int64

do you know how can i fix this error please?


问:
Question on creating templates in coderush
I am looking to start creating some CR templates to fit with my style of coding (such is the power of coderush).

I tried a dummy one yesterday and made an auto prop with two fields, one for the type and one for the name.

This worked as expected with one flaw...

In coderush when I expand a built in template it sets the cursor to the first field. Mine does not, It sets the cursor at the end of the line

```<code>Private <<Field(Type)>> <<Field(Name)>> {get; set}
</code>```

PS: Does anyone know how to type out those teeny tiny angle brackets that they use?

答:
To initialize the caret position, use the Caret text command. To perform the selection, utilize the BlockAnchor text command in coalition with the Caret text command. As a result, your template will look similar to this one:

```<code>Private «Caret»«Field(Type)»«BlockAnchor» «Field(Name)» {get; set}
</code>```

P.S. I'm pasting the template expansion right from the CodeRush Templates Editor, so they are pasted as is. To type those characters here, simply specify their HTML name, for example "laquo" (left double angle quotes) preceeding with & and followed by ; characters (e.g. "& laquo ;"), remove spaces and get this character: «

Body:
I am looking to start creating some CR templates to fit with my style of coding (such is the power of coderush).

I tried a dummy one yesterday and made an auto prop with two fields, one for the type and one for the name.

This worked as expected with one flaw...

In coderush when I expand a built in template it sets the cursor to the first field. Mine does not, It sets the cursor at the end of the line

Private <<Field(Type)>> <<Field(Name)>> {get; set}

PS: Does anyone know how to type out those teeny tiny angle brackets that they use?

Body:
To initialize the caret position, use the Caret text command. To perform the selection, utilize the BlockAnchor text command in coalition with the Caret text command. As a result, your template will look similar to this one:

Private «Caret»«Field(Type)»«BlockAnchor» «Field(Name)» {get; set}

P.S. I'm pasting the template expansion right from the CodeRush Templates Editor, so they are pasted as is. To type those characters here, simply specify their HTML name, for example "laquo" (left double angle quotes) preceeding with & and followed by ; characters (e.g. "& laquo ;"), remove spaces and get this character: «


问:
RestSharp v107: setting Json serialization options
I'm using the new RestSharp v107, which started using the System.Text.Json classes to manage JSON (de)serialization.

This being the case, I thought we would be able to provide our own instance of JsonSerializerOptions to customize how serialization is handled, however I cannot see any settings in the RestClientOptions object to set the json serialization options. Is there a way to do this?

答:
Well, I found out the answer shortly after posting.

All you have to do is:

```<code>httpClient.UseSystemTextJson(new JsonSerializerOptions() { ... });
</code>```

and it's done, simple as that

Body:
Well, I found out the answer shortly after posting.

All you have to do is:

httpClient.UseSystemTextJson(new JsonSerializerOptions() { ... });

and it's done, simple as that


问:
How to make all the bars move smoothly at the same time even though they are moving at different speeds?
I have 5 progress bars that are all moving at the same time all at different speeds.
Their speeds are dynamic and need to be modifiable programmatically which is why this is implemented with JS and not using animations by CSS. Here's a jsfiddle: https://jsfiddle.net/ezg97/ey319g48/7/

The problem is this: The progress bars move choppy, I want them to all move smoothly, I'm not sure how to accomplish this? This is for a game that I'm building.

If they increment at a very small number like 1, they appear to almost be moving smoothly; however, in reality they will be able to move at any rate.

The code is also viewable here:

// array to maintain progress bars
var pbArr = [{
    pid: 'bar1', // parent container id
    speed: 31, // max speed value
    accl: 10, // speed at which it will accelerate
    curr: 0, // current speed
    dist: 0 // total distance/displacement
}, {
    pid: 'bar2',
    speed: 40,
        accl: 1,
    curr: 0,
    dist: 0
}, {
    pid: 'bar3',
    speed: 21,
        accl: 20,
    curr: 0,
    dist: 0
}, {
    pid: 'bar4',
    speed: 35,
        accl: 6,
    curr: 0,
    dist: 0
}, {
    pid: 'bar5',
    speed: 25,
    accl: 16,
    curr: 0,
    dist: 0
}];

var loopCnt = 1; // loop count to maintain width
var pb_timeout; // progress bar timeout function

// create progress bar funtion

var createPB = function () {

    var is_all_pb_complete = true; // flag to check whether all progress bar are completed executed

    for (var i = 0; i < pbArr.length; i++) {
        var childDiv = document.querySelector('#' + pbArr[i].pid + ' div'); // child div

        // When initially starting, set current speed to acceleration speed
        if (pbArr[i].curr === 0) {
            pbArr[i].curr = pbArr[i].accl;
        } else {
            // if the current speed + the acceleration is less than top speed, add more acceleration
            if ((pbArr[i].curr + pbArr[i].accl) < pbArr[i].speed) {
                pbArr[i].curr += pbArr[i].accl;
          }
          // if the current speed + the acceleration is greater than acceleration, then make current speed equal to top speed
          else {
                pbArr[i].curr = pbArr[i].speed;
          }
        }
        // removed output: console.log(pbArr[i]);
        // add the current speed to the distance traveled already
        pbArr[i].dist += pbArr[i].curr;
        var newWidth = pbArr[i].dist; // new width

        //if your new distance traveled is less than 100, add it to the progress bar
        if (newWidth <= 100) {
            is_all_pb_complete = false;
            childDiv.style.width = newWidth + '%';
        } else {
            // if your new distance traveled is greater than or equal to 100, set the prgoress bar to 100%
            childDiv.style.width = '100%';
        }

    }

    if (is_all_pb_complete) { // if true, then clear timeout
        clearTimeout(pb_timeout);
        return;
    }

    loopCnt++; // increment loop count

    // recall function
    pb_timeout = setTimeout(function () {
        createPB();
    }, 1000);
}

// call function to initiate progress bars
createPB();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bar{
    width:200px;
    height:20px;
    background-color:black;
    position:relative;
}
.child{
    position:abosoute;
    top:0px;
    left:0px;
    background-color:red;
    height:20px;
}
.clr{
    width:100%;
    height:2px;
}</code>```

```

答: It helps a little bit adding transition: all 0.1s ease; onto your .child class, but doesn't solve it completely.

Body:
I have 5 progress bars that are all moving at the same time all at different speeds.
Their speeds are dynamic and need to be modifiable programmatically which is why this is implemented with JS and not using animations by CSS. Here's a jsfiddle: https://jsfiddle.net/ezg97/ey319g48/7/

The problem is this: The progress bars move choppy, I want them to all move smoothly, I'm not sure how to accomplish this? This is for a game that I'm building.

If they increment at a very small number like 1, they appear to almost be moving smoothly; however, in reality they will be able to move at any rate.

The code is also viewable here:

// array to maintain progress bars
var pbArr = [{
    pid: 'bar1', // parent container id
    speed: 31, // max speed value
    accl: 10, // speed at which it will accelerate
    curr: 0, // current speed
    dist: 0 // total distance/displacement
}, {
    pid: 'bar2',
    speed: 40,
        accl: 1,
    curr: 0,
    dist: 0
}, {
    pid: 'bar3',
    speed: 21,
        accl: 20,
    curr: 0,
    dist: 0
}, {
    pid: 'bar4',
    speed: 35,
        accl: 6,
    curr: 0,
    dist: 0
}, {
    pid: 'bar5',
    speed: 25,
    accl: 16,
    curr: 0,
    dist: 0
}];

var loopCnt = 1; // loop count to maintain width
var pb_timeout; // progress bar timeout function

// create progress bar funtion

var createPB = function () {

    var is_all_pb_complete = true; // flag to check whether all progress bar are completed executed

    for (var i = 0; i < pbArr.length; i++) {
        var childDiv = document.querySelector('#' + pbArr[i].pid + ' div'); // child div

        // When initially starting, set current speed to acceleration speed
        if (pbArr[i].curr === 0) {
            pbArr[i].curr = pbArr[i].accl;
        } else {
            // if the current speed + the acceleration is less than top speed, add more acceleration
            if ((pbArr[i].curr + pbArr[i].accl) < pbArr[i].speed) {
                pbArr[i].curr += pbArr[i].accl;
          }
          // if the current speed + the acceleration is greater than acceleration, then make current speed equal to top speed
          else {
                pbArr[i].curr = pbArr[i].speed;
          }
        }
        // removed output: console.log(pbArr[i]);
        // add the current speed to the distance traveled already
        pbArr[i].dist += pbArr[i].curr;
        var newWidth = pbArr[i].dist; // new width

        //if your new distance traveled is less than 100, add it to the progress bar
        if (newWidth <= 100) {
            is_all_pb_complete = false;
            childDiv.style.width = newWidth + '%';
        } else {
            // if your new distance traveled is greater than or equal to 100, set the prgoress bar to 100%
            childDiv.style.width = '100%';
        }

    }

    if (is_all_pb_complete) { // if true, then clear timeout
        clearTimeout(pb_timeout);
        return;
    }

    loopCnt++; // increment loop count

    // recall function
    pb_timeout = setTimeout(function () {
        createPB();
    }, 1000);
}

// call function to initiate progress bars
createPB();

.bar{
    width:200px;
    height:20px;
    background-color:black;
    position:relative;
}
.child{
    position:abosoute;
    top:0px;
    left:0px;
    background-color:red;
    height:20px;
}
.clr{
    width:100%;
    height:2px;
}


问:
Google OAuth RefreshError even with Refresh Token present in the Django app
My app running on Django with Django allauth allows signup/login only via Google OAuth. Therefore when a user is registered, his social oauth details are saved to All-auth Social Accounts model and the token data saved in Social Application Tokens model.

We want the users to be logged-in as long as possible, without granting/revoking access regularly.

Question 1: The default expiry is set as 1 hour from the registration time. How can I extend this programmatically and for how long (can it be never-expire?)

Currently, a user logged in at 5:00 and I get the following data from credentials.to_json():

```<code>{
"token": "ya29.A0ARrdaM8YXPM35RXPv7UK-pXLZvWG49T-MgCZ5wMse2ADMXOZJOWFJKMaq1PkobADLptM5YX5mnrliS2yCCESqCk0NTaZJkfe6inK94j6WQMFZWIT_xRyBTOX4W3dUEiuLhHFpQcD5vS-x_Y22pUzxwgI23pp",
"refresh_token": "1//0gYC8oucHhTBVCgYIARAAGBASNwF-L9IrCG7c5IJCBMVznUrytGEFsJbsObAFvmNBoQbHHGA1KESyBWgmudEVogbes8ski87q_5g",
"client_id": "blablabla.apps.googleusercontent.com",
"client_secret": "xyzsecret"}
</code>```

No other data is returned.

At 6:05, the credentials.to_json() is exactly the SAME AS ABOVE.
But to fetch any Google/Youtube API data, I get the following error in server logs:

```<code>google.auth.exceptions.RefreshError: The credentials do not contain the necessary fields need to refresh the access token.
</code>```

Question 02: When there's a Refresh Token available already, why the error?
As per the docs, it refreshes the token automatically few minutes before the expiry. What am I missing?

I already had "access_type": "offline" in the providers settings. I also tried adding  "prompt": "consent", but no effect.

Django Settings:

```<code>INSTALLED_APPS = [
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.google",
    ...
]

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

SOCIALACCOUNT_PROVIDERS = {
    "google": {
        "SCOPE": [
            "profile",
            "email",
            "https://www.googleapis.com/auth/youtube",
            "https://www.googleapis.com/auth/youtube.readonly",
            "https://www.googleapis.com/auth/youtube.upload",
            "https://www.googleapis.com/auth/youtube.force-ssl",
        ],
        "AUTH_PARAMS": {
            "access_type": "offline",
            "prompt": "consent",
        },
    },
}
</code>```

And the Django Views snippet related to OAuth:

```<code>import googleapiclient.discovery
import googleapiclient.errors
from allauth.socialaccount.models import SocialAccount, SocialApp
from google.oauth2.credentials import Credentials

def get_credentials_google(user):
    app_google = SocialApp.objects.get(provider="google")
    account = SocialAccount.objects.get(user=user)
    user_tokens = account.socialtoken_set.first()
    creds = Credentials(
        token=user_tokens.token,
        refresh_token=user_tokens.token_secret,
        client_id=app_google.client_id,
        client_secret=app_google.secret,
    )
    return creds

def get_youtube_account(user):
    api_service_name = "youtube"
    api_version = "v3"
    credentials = get_credentials_google(user)
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials
    )
    return youtube

def get_youtube_videos(request):
    youtube = get_youtube_account(request.user)
    request = youtube.liveBroadcasts().list(
        part="id, snippet, contentDetails, status",
        broadcastStatus="completed",
        broadcastType="all"
    )
    response = request.execute()
    return response
</code>```

Note: There's no front-end framework I'm using django with django template UI.

答:
How can I extend this programmatically and for how long (can it be never-expire?)

You cant access tokens expire after one hour this is standard.  You can use the refresh token to request a new access token as you need

When there's a Refresh Token available already, why the error? As per the docs, it refreshes the token automatically few minutes before the expiry. What am I missing?

Refresh tokens are used to request a new access token approximately five minutes before its due to expire.

google.auth.exceptions.RefreshError: The credentials do not contain the necessary fields need to refresh the access token.

Sounds like your not setting the client object properly. Something here is not set right.  Also remember if your app is still in testing your refresh token will expire after seven days and you will need to reauthorize your test users.

```<code>creds = Credentials(
    token=user_tokens.token,
    refresh_token=user_tokens.token_secret,
    client_id=app_google.client_id,
    client_secret=app_google.secret,
)
</code>```

Body:
My app running on Django with Django allauth allows signup/login only via Google OAuth. Therefore when a user is registered, his social oauth details are saved to All-auth Social Accounts model and the token data saved in Social Application Tokens model.

We want the users to be logged-in as long as possible, without granting/revoking access regularly.

Question 1: The default expiry is set as 1 hour from the registration time. How can I extend this programmatically and for how long (can it be never-expire?)

Currently, a user logged in at 5:00 and I get the following data from credentials.to_json():

{
"token": "ya29.A0ARrdaM8YXPM35RXPv7UK-pXLZvWG49T-MgCZ5wMse2ADMXOZJOWFJKMaq1PkobADLptM5YX5mnrliS2yCCESqCk0NTaZJkfe6inK94j6WQMFZWIT_xRyBTOX4W3dUEiuLhHFpQcD5vS-x_Y22pUzxwgI23pp",
"refresh_token": "1//0gYC8oucHhTBVCgYIARAAGBASNwF-L9IrCG7c5IJCBMVznUrytGEFsJbsObAFvmNBoQbHHGA1KESyBWgmudEVogbes8ski87q_5g",
"client_id": "blablabla.apps.googleusercontent.com",
"client_secret": "xyzsecret"}

No other data is returned.

At 6:05, the credentials.to_json() is exactly the SAME AS ABOVE.
But to fetch any Google/Youtube API data, I get the following error in server logs:

google.auth.exceptions.RefreshError: The credentials do not contain the necessary fields need to refresh the access token.

Question 02: When there's a Refresh Token available already, why the error?
As per the docs, it refreshes the token automatically few minutes before the expiry. What am I missing?

I already had "access_type": "offline" in the providers settings. I also tried adding  "prompt": "consent", but no effect.

Django Settings:

INSTALLED_APPS = [
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.google",
    ...
]

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

SOCIALACCOUNT_PROVIDERS = {
    "google": {
        "SCOPE": [
            "profile",
            "email",
            "https://www.googleapis.com/auth/youtube",
            "https://www.googleapis.com/auth/youtube.readonly",
            "https://www.googleapis.com/auth/youtube.upload",
            "https://www.googleapis.com/auth/youtube.force-ssl",
        ],
        "AUTH_PARAMS": {
            "access_type": "offline",
            "prompt": "consent",
        },
    },
}

And the Django Views snippet related to OAuth:

import googleapiclient.discovery
import googleapiclient.errors
from allauth.socialaccount.models import SocialAccount, SocialApp
from google.oauth2.credentials import Credentials

def get_credentials_google(user):
    app_google = SocialApp.objects.get(provider="google")
    account = SocialAccount.objects.get(user=user)
    user_tokens = account.socialtoken_set.first()
    creds = Credentials(
        token=user_tokens.token,
        refresh_token=user_tokens.token_secret,
        client_id=app_google.client_id,
        client_secret=app_google.secret,
    )
    return creds

def get_youtube_account(user):
    api_service_name = "youtube"
    api_version = "v3"
    credentials = get_credentials_google(user)
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials
    )
    return youtube

def get_youtube_videos(request):
    youtube = get_youtube_account(request.user)
    request = youtube.liveBroadcasts().list(
        part="id, snippet, contentDetails, status",
        broadcastStatus="completed",
        broadcastType="all"
    )
    response = request.execute()
    return response

Note: There's no front-end framework I'm using django with django template UI.

Body:
How can I extend this programmatically and for how long (can it be never-expire?)

You cant access tokens expire after one hour this is standard.  You can use the refresh token to request a new access token as you need

When there's a Refresh Token available already, why the error? As per the docs, it refreshes the token automatically few minutes before the expiry. What am I missing?

Refresh tokens are used to request a new access token approximately five minutes before its due to expire.

google.auth.exceptions.RefreshError: The credentials do not contain the necessary fields need to refresh the access token.

Sounds like your not setting the client object properly. Something here is not set right.  Also remember if your app is still in testing your refresh token will expire after seven days and you will need to reauthorize your test users.

creds = Credentials(
    token=user_tokens.token,
    refresh_token=user_tokens.token_secret,
    client_id=app_google.client_id,
    client_secret=app_google.secret,
)


问:
React Map Method within Map Method
I am trying to include map method in a map method while getting a list as an element from the first map method.

```<code>      {columns &&
        columns.map(column =>
        column.list && column.list?
        (column.list.map((item)=>{
        return (
        <CustomTableCell align="center">{item.name}
        <span>{item.convertMethod(item.id, item.lists)}</span>
        </CustomTableCell>
         );
         })):
        <CustomTableCell align="center"> {column.name} </CustomTableCell>
           ) }
</code>```

Error still exists

答:
```<code>return (
<div className="App">
{
  columns.map(column => {
    return (
      column.list && column.list.length > 0 ? (
        column.list.map(item => {
          return (
            <div key={item.name}>{item.name}</div>
          )
        })
  ): ("")
    )
  })
}
</div>
);
</code>```

demo

Title: React Map Method within Map Method

Body:
I am trying to include map method in a map method while getting a list as an element from the first map method.

      {columns &&
        columns.map(column =>
        column.list && column.list?
        (column.list.map((item)=>{
        return (
        <CustomTableCell align="center">{item.name}
        {item.convertMethod(item.id, item.lists)}
        </CustomTableCell>
         );
         })):
        <CustomTableCell align="center"> {column.name} </CustomTableCell>
           ) }

Error still exists

Body:
return (
<div className="App">
{
  columns.map(column => {
    return (
      column.list && column.list.length > 0 ? (
        column.list.map(item => {
          return (
            <div key={item.name}>{item.name}</div>
          )
        })
  ): ("")
    )
  })
}
</div>
);

demo


问:
My pygame window color is not filling over the screen
Ok it might be ridiculous but I am creating a pygame game and currently I am working on the opening window. Now I have added only 2 buttons to the window; Play and Help.
The Play button works completely fine but the Help button function doesn't. I am not telling that the Help button is not working. The code inside the function is not working. here is my code:

```<code>
class Button:
    # I did not include this because it works completely fine. The problem is in the help window function.
def help_window():
    win.fill((0,0,0)) # Doesn't fill the screen completely. The buttons are still shown.

def main():
   # The main function

def main_menu():
    title_font = pygame.font.SysFont("comicsans", 70)
    run = True
    win.fill((90, 255, 180))
    while run:
        play_button = Button((0,255,0), WIDTH/2 - 100, HEIGHT/2 - 30, 200, 70, "Play")
        play_button.draw(win, (0,0,0))

        help_button = Button((0,255,0), WIDTH/2 - 100, HEIGHT/2 - play_button.height - 120, 200, 70, "Help")
        help_button.draw(win, (0,0,0))

        pygame.display.update()
        pos = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                if play_button.isOver(pos):
                    main()
                elif help_button.isOver(pos):
                    help_window() # The help window function
    pygame.quit()
main_menu()
</code>```

What do I do?

答:
If I understand your problem correctly, the buttons should not appear anymore as soon as the player clicks on the help button.

The problem is that when the player clicks the button this calls win.fill((0,0,0)) but then it the main loop you still draw the buttons (play_button.draw(win, (0,0,0)) and help_button.draw(win, (0,0,0))).

You might need to use a boolean variable to know if your buttons must
be drawned or not:

draw_button = True  # enable buttons drawing
while run:
    if draw_button:
        play_button = Button((0,255,0), WIDTH/2 - 100, HEIGHT/2 - 30, 200, 70, "Play")
        play_button.draw(win, (0,0,0))
        help_button = Button((0,255,0), WIDTH/2 - 100, HEIGHT/2 - play_button.height - 120, 200, 70, "Help")
        help_button.draw(win, (0,0,0))
    pygame.display.update()
    pos = pygame.mouse.get_pos()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            if play_button.isOver(pos):
                main()
            elif help_button.isOver(pos):
                help_window()
                draw_button = False  # stop drawing buttons
```

Body:
Ok it might be ridiculous but I am creating a pygame game and currently I am working on the opening window. Now I have added only 2 buttons to the window; Play and Help.
The Play button works completely fine but the Help button function doesn't. I am not telling that the Help button is not working. The code inside the function is not working. here is my code:

class Button:
    # I did not include this because it works completely fine. The problem is in the help window function.
def help_window():
    win.fill((0,0,0)) # Doesn't fill the screen completely. The buttons are still shown.

def main():
   # The main function

def main_menu():
    title_font = pygame.font.SysFont("comicsans", 70)
    run = True
    win.fill((90, 255, 180))
    while run:
        play_button = Button((0,255,0), WIDTH/2 - 100, HEIGHT/2 - 30, 200, 70, "Play")
        play_button.draw(win, (0,0,0))

        help_button = Button((0,255,0), WIDTH/2 - 100, HEIGHT/2 - play_button.height - 120, 200, 70, "Help")
        help_button.draw(win, (0,0,0))

        pygame.display.update()
        pos = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                if play_button.isOver(pos):
                    main()
                elif help_button.isOver(pos):
                    help_window() # The help window function
    pygame.quit()
main_menu()

What do I do?


问:
Dynamically generate / omit HTML attribute in Twig
I want to generate a div with a specific HTML attribute present or absent in it, in function of if a variable my_var has been defined or not. If it has been defined, its value should be used as the according attribute.

my_var is either not defined or equal to a value consisting of several words separated by a space (software needs these, I know it's not usual...).

I've tried the following:

```<code><div class="container" {{ my_var ? "data-my-var='" ~ {{ my_var }} ~ "'" : ""}}>
</div>
</code>```

But this escapes the quotes I use and yields sth like this in my output, with my_var = hello there how are you:

```<code><div class="container" data-my-var="hello there how are you">
</div>
</code>```

This does not change when I escape the quotes using

```<code>"data-my-var=\"" ~ {{ my_var }} ~ "\""
</code>```

instead of what's written above.

I've also tried to simply omit the quotes, so do sth like:

```<code>"data-my-var=" ~ {{ my_var }}
</code>```

which resulted in the attribute data-my-var being output with no quotes whatsoever; hence only recognizing the first word of the value of my_var.

So how can I reach what I want?

答:
Variables and concatenations with variables are not marked as safe by default. You will need to apply the filter raw to mark the output as safe. Also you can omit the second part if you just return an empty string

```<code><div class="container"{{ my_var ? (' data-my-var="' ~my_var ~ '"')|raw }}>
</div>
</code>```

demo

Another method, as commented by @Bossman is to use an {% if ... %}{% endif %}

Body:
I want to generate a div with a specific HTML attribute present or absent in it, in function of if a variable my_var has been defined or not. If it has been defined, its value should be used as the according attribute.

my_var is either not defined or equal to a value consisting of several words separated by a space (software needs these, I know it's not usual...).

I've tried the following:

But this escapes the quotes I use and yields sth like this in my output, with my_var = hello there how are you:

This does not change when I escape the quotes using

"data-my-var=\"" ~ {{ my_var }} ~ "\""

instead of what's written above.

I've also tried to simply omit the quotes, so do sth like:

"data-my-var=" ~ {{ my_var }}

which resulted in the attribute data-my-var being output with no quotes whatsoever; hence only recognizing the first word of the value of my_var.

So how can I reach what I want?

Body:
Variables and concatenations with variables are not marked as safe by default. You will need to apply the filter raw to mark the output as safe. Also you can omit the second part if you just return an empty string

<div class="container"{{ my_var ? (' data-my-var="' ~my_var ~ '"')|raw }}>
</div>

demo

Another method, as commented by @Bossman is to use an {% if ... %}{% endif %}


问:
Flutter - Warning (CocoaPods not installed Skipping pod install) Even While Installed
I am trying to build a Flutter app with Geolocator plugin on Android Studio.
When I am running the app I have the following warning - that prevents the app from running:

Warning: CocoaPods not installed. Skipping pod install.
CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

Exception: CocoaPods not installed or not in valid state.

I tried every solution i found in the internet (Stackoverflow & GitHub) but nothing seems to work.

Important: When I tried to run the app from Xcode instead of from Android Studio, I had this error:

The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.

So what I did was - Change directory to ios (on the Flutter project) and running:

```<code>pod init
pod install
</code>```

Tried to run again from Xcode and it worked perfectly.
After it works on Xcode I tried to run it from Android Studio and the same error happens to me, preventing the app to launch.

Flutter Doctor:

```<code>[✓] Flutter (Channel stable, 2.2.2, on macOS 11.4 20F71 darwin-x64, locale en-IL)
    • Flutter version 2.2.2 at /Users/idanrefaeli/Developer/flutter
    • Framework revision d79295af24 (5 weeks ago), 2021-06-11 08:56:01 -0700
    • Engine revision 91c9fc8fe0
    • Dart version 2.13.3

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/idanrefaeli/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.5.1, Build version 12E507
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] VS Code (version 1.57.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.23.0

[✓] Connected device (2 available)
    • Idan’s (mobile) • 00008020-0011092101A2002E • ios            • iOS 14.6
    • Chrome (web)    • chrome                    • web-javascript • Google Chrome 91.0.4472.114

! Doctor found issues in 1 category.
</code>```

Extra logs:
'Run' log in Android Studio: pastebin.com/7iYtdcTQ
Also this terminal log after running 'pod install': pastebin.com/1cCNuFYM

-- UPDATE --

I finally was able to run the app, all I did was to copy all the project files to a new project from scratch and it worked.
Maybe it happened because of a certain conflict, since I imported someone else's project (from Angela Yu's Flutter Udemy course).
Anyway, I still didn't find a fix for this fraustrating problem so if anyone recognizes something it would be great!

答:
I had the same problem and I installed cocoapods and it works now.

Just copy and paste this line to install cocoapods:
sudo gem install cocoapods

Restart VSCode and terminals.

And then run your app.

I'm working on MAC with IOS (Iphone 13) emulator.

CocoaPods Guide.

Body:
I am trying to build a Flutter app with Geolocator plugin on Android Studio.
When I am running the app I have the following warning - that prevents the app from running:

Warning: CocoaPods not installed. Skipping pod install.
CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

Exception: CocoaPods not installed or not in valid state.

I tried every solution i found in the internet (Stackoverflow & GitHub) but nothing seems to work.

Important: When I tried to run the app from Xcode instead of from Android Studio, I had this error:

The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.

So what I did was - Change directory to ios (on the Flutter project) and running:

pod init
pod install

Tried to run again from Xcode and it worked perfectly.
After it works on Xcode I tried to run it from Android Studio and the same error happens to me, preventing the app to launch.

Flutter Doctor:

[✓] Flutter (Channel stable, 2.2.2, on macOS 11.4 20F71 darwin-x64, locale en-IL)
    • Flutter version 2.2.2 at /Users/idanrefaeli/Developer/flutter
    • Framework revision d79295af24 (5 weeks ago), 2021-06-11 08:56:01 -0700
    • Engine revision 91c9fc8fe0
    • Dart version 2.13.3

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/idanrefaeli/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.5.1, Build version 12E507
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] VS Code (version 1.57.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.23.0

[✓] Connected device (2 available)
    • Idan’s (mobile) • 00008020-0011092101A2002E • ios            • iOS 14.6
    • Chrome (web)    • chrome                    • web-javascript • Google Chrome 91.0.4472.114

! Doctor found issues in 1 category.

Extra logs:
'Run' log in Android Studio: pastebin.com/7iYtdcTQ
Also this terminal log after running 'pod install': pastebin.com/1cCNuFYM

-- UPDATE --

I finally was able to run the app, all I did was to copy all the project files to a new project from scratch and it worked.
Maybe it happened because of a certain conflict, since I imported someone else's project (from Angela Yu's Flutter Udemy course).
Anyway, I still didn't find a fix for this fraustrating problem so if anyone recognizes something it would be great!


问:
How to run Python files in example folder?
I am creating a Python package and want to make the example files in the example folder runnable with something like python example_file.py. How do I do it? My example_file.py and __init__.py look like below:

# example_file.py
from demandforecast import DemandForecast # module coded in demandforecast.py

if __name__ == '__main__':
    # Example code here
```
<pre class="lang-py prettyprint-override"><code># __init__.py
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
</code>```

When I navigate to the examples directory and run python example_file.py I get the following error:

```<code>Exception has occurred: ModuleNotFoundError
No module named 'demandforecast'
</code>```

This can be solved by adding using the old sys.path.insert() trick mentioned in Importing files from different folder, but I would rather not include the absolute path because this will vary from user to user.

Here is my directory structure:

```<code>├───demandforecast
│       demandforecast.py
│       __init__.py
│
└───examples
        example_file.py
</code>```

I have tried a few posts here, such as Relative imports in Python 3, but without luck. Adding sys.path.append('../') to the example file before the demandforecast import also did not work.

答:
I think your import is simply incorrect, and should be:

```<code>from demandforecast.demandforecast import DemandForecast
</code>```

Since demandforecast is both the package name (the directory is definitely a package, with the __init__.py file) and a module name within that package. (I assume DemandForecast is a class within the demandforecast module.)

Body:
I am creating a Python package and want to make the example files in the example folder runnable with something like python example_file.py. How do I do it? My example_file.py and __init__.py look like below:

# example_file.py
from demandforecast import DemandForecast # module coded in demandforecast.py

if __name__ == '__main__':
    # Example code here

# __init__.py
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))

When I navigate to the examples directory and run python example_file.py I get the following error:

Exception has occurred: ModuleNotFoundError
No module named 'demandforecast'

This can be solved by adding using the old sys.path.insert() trick mentioned in Importing files from different folder, but I would rather not include the absolute path because this will vary from user to user.

Here is my directory structure:

├───demandforecast
│       demandforecast.py
│       __init__.py
│
└───examples
        example_file.py

I have tried a few posts here, such as Relative imports in Python 3, but without luck. Adding sys.path.append('../') to the example file before the demandforecast import also did not work.

Body:
I think your import is simply incorrect, and should be:

from demandforecast.demandforecast import DemandForecast

Since demandforecast is both the package name (the directory is definitely a package, with the __init__.py file) and a module name within that package. (I assume DemandForecast is a class within the demandforecast module.)


问:
Debugging in VSCode in Python, debugger does not respect the breakpoints in class
I am new at programming in python. I use Visual Studio Code. I have some problems with my debugger. When I debug a script, my debugger takes a break at the breakpoints in my script as it should be. But in my script I also create objects from a class. To debug methods of a class (objects created from it), I set breakpoints in the methods.
I expect the debugger to jump there and respect the breakpoints, but that does not happen. I have a really long code, so I tried to shorten it. So in my Code example I set a breakpoint inside the method definition of step(old_state,action). When debugging the script, why doesn't it stop here?

DQN.py
...
...
env = PowerControl() #creates object of the class PowerControl()
..
new_state = env.step(old_state, action)

class PowerControl()
..
  def step(old_state,action)
    ...

    return new_state

    ```
</div>
</div>
</p>
<p>`</p>
<p>It might have to do something with the settings in my launch.json file. It looks like this.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>{
    // Verwendet IntelliSense zum Ermitteln möglicher Attribute.
    // Zeigen Sie auf vorhandene Attribute, um die zugehörigen Beschreibungen anzuzeigen.
    // Weitere Informationen finden Sie unter https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Aktuelle Datei",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}</code>```

Thanks in advance for support.

答:
I don't know if this is the issue, but I noticed that when you defined your class you didn't have a colon at the end of it, same with when you defined your method. Also, inside of classes, the first parameter of a method is typically self.</p>
```<code>DQN.py
...
...
env = PowerControl() #creates object of the class PowerControl()
..
new_state = env.step(old_state, action)

class PowerControl(): # added colon
..
  def step(self, old_state, action): # added colon and self parameter
    ...

    return new_state

</code>```

Body:
I am new at programming in python. I use Visual Studio Code. I have some problems with my debugger. When I debug a script, my debugger takes a break at the breakpoints in my script as it should be. But in my script I also create objects from a class. To debug methods of a class (objects created from it), I set breakpoints in the methods.
I expect the debugger to jump there and respect the breakpoints, but that does not happen. I have a really long code, so I tried to shorten it. So in my Code example I set a breakpoint inside the method definition of step(old_state,action). When debugging the script, why doesn't it stop here?

DQN.py
...
...
env = PowerControl() #creates object of the class PowerControl()
..
new_state = env.step(old_state, action)

class PowerControl()
..
  def step(old_state,action)
    ...

    return new_state

`

It might have to do something with the settings in my launch.json file. It looks like this.

{
    // Verwendet IntelliSense zum Ermitteln möglicher Attribute.
    // Zeigen Sie auf vorhandene Attribute, um die zugehörigen Beschreibungen anzuzeigen.
    // Weitere Informationen finden Sie unter https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Aktuelle Datei",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}

Thanks in advance for support.

Body:
I don't know if this is the issue, but I noticed that when you defined your class you didn't have a colon at the end of it, same with when you defined your method. Also, inside of classes, the first parameter of a method is typically self.

DQN.py
...
...
env = PowerControl() #creates object of the class PowerControl()
..
new_state = env.step(old_state, action)

class PowerControl(): # added colon
..
  def step(self, old_state, action): # added colon and self parameter
    ...

    return new_state


问:
"An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied" when using batch jobs

I have a compute environment with 'ecsInstanceRole'. It contains the policies 'AmazonS3FullAccess' and 'AmazonEC2ContainerServiceforEC2Role'

Since I am using the AmazonS3FullAccess policy, I assume the batch job has permission to list, copy, put etc.
-The image I am using is a custom docker image that has a startup script which uses "aws s3 ls <S3_bucket_URL>"

When I start this image on an EC2 instance, it runs fine and lists the contents of the bucket

when I do the same as a batch job, I get the access denied error seen above.

I dont understand how this is happening.

Things I have tried so far:

having the bucket policy as

.

```<code>{
    "Version": "2012-10-17",
    "Id": "Policy1546414123454",
    "Statement": [
        {
            "Sid": "Stmt1546414471931",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::<Account Id>:root"
            },
            "Action": [
                "s3:ListBucket",
                "s3:ListBucketVersions"
            ],
            "Resource": [
                "arn:aws:s3:::"bucketname",
                "arn:aws:s3:::bucketname/*"
            ]
        }
    ]
}
</code>```

Granted public access to the bucket

答:
Quoting the reply from @JohnRotenstein because I cannot mark it as an answer.

"If you are using IAM Roles, there is no need for a Bucket Policy. (Also, there is a small typo in that policy, before bucketname but I presume that was due to a Copy & Paste error.) It would appear that a role has not been assigned to your ECS task: IAM Roles for Tasks - Amazon Elastic Container Service"

Solution: I had toattach an S3 access policy to my current Job Role.

Body:
I have a compute environment with 'ecsInstanceRole'. It contains the policies 'AmazonS3FullAccess' and 'AmazonEC2ContainerServiceforEC2Role'

Since I am using the AmazonS3FullAccess policy, I assume the batch job has permission to list, copy, put etc.
-The image I am using is a custom docker image that has a startup script which uses "aws s3 ls <S3_bucket_URL>"

When I start this image on an EC2 instance, it runs fine and lists the contents of the bucket

when I do the same as a batch job, I get the access denied error seen above.

I dont understand how this is happening.

Things I have tried so far:

having the bucket policy as

.

{
    "Version": "2012-10-17",
    "Id": "Policy1546414123454",
    "Statement": [
        {
            "Sid": "Stmt1546414471931",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::<Account Id>:root"
            },
            "Action": [
                "s3:ListBucket",
                "s3:ListBucketVersions"
            ],
            "Resource": [
                "arn:aws:s3:::"bucketname",
                "arn:aws:s3:::bucketname/*"
            ]
        }
    ]
}

Granted public access to the bucket


问:
Django web site URLS gets "?next=" randomly after deployed to heroku
After deploying django app on heroku the url after every form submission or link in site been press resulting with "?next=" inserts into the URL address, I don't understand from where it comes and why heroku keep inserting them in a random way, running the application locally just working perfectly.

I've deleted the application from heroku and upload it again, the fault persists.

There's no http errors what so ever. If I keep submitting the form eventually will works.

For example: pressing the log button in the django admin console results with this URL: https://appname.herokuapp.com/admin/login/?next=/admin/login/admin/, hitting it quite a bit will finally make it work with the correct url display: https://mishnayot.herokuapp.com/admin/.

Switching from heroku postgres to AWS RDS postgres didn't help.

Help will be very appreciated.

答:
Well, struggling for days just to understand it's heroku backend issue and there's not enough information that could help me solving it (i did try to contact heroku support directly but I'm on a free account).

Finally I decided to deploy it using elastic beanstalk. The implementation took some time with long learning curve but now my site works and works great!

Thanks for trying to help Tim.

Cheers!


问:
how should name the modifier params in Jetpack compose component which gets two or more modifiers?
If we have a compose component which gets two or more modifiers, how should we handle it ?
I mean the naming of modifiers while lint complains changing the name of modifier parameter

Sample code to figure out easily :

```<code>@Composable
    private fun CompletionSection(iconModifier: Modifier, textModifier: Modifier, isActivated: Boolean, newText: String?) {
        if (isActivated) {
            Icon(
                painter = painterResource(R.drawable.ds_ic_check_circle),
                modifier = iconModifier
                    .wrapContentSize()
                    .padding(top = 18.dp),
                tint = MaterialTheme.colors.positive,
                contentDescription = null
            )
        } else if (!newText.isNullOrBlank()) {
            Surface(
                modifier = textModifier.padding(top = 18.dp),
                shape = RoundedCornerShape(32.dp),
                border = BorderStroke(width = 2.dp, color = MaterialTheme.colors.primary.copy(alpha = 0.6f)),
            ) {
                Text(
                    overflow = TextOverflow.Ellipsis,
                    maxLines = 1,
                    fontSize = 11.sp,
                    color = MaterialTheme.colors.primary.copy(alpha = 0.6f),
                    text = newText,
                    modifier = Modifier
                        .defaultMinSize(minHeight = 20.dp)
                        .wrapContentSize()
                        .padding(horizontal = 6.dp, vertical = 2.dp),
                    style = MaterialTheme.typography.android.caption2
                )
            }
        }
    }
</code>```

Here, where the function is used →

```<code>ConstraintLayout(
    modifier = Modifier.fillMaxSize(),
    constraintSet = decoupledConstraints(
        marginSpacing02 = marginSpacing02,
        marginSpacing01 = marginSpacing01,
        entity = entity
    )
) {

    CompletionSection(
        iconModifier = Modifier.layoutId("completedIcon"),
        textModifier = Modifier.layoutId("newTextField"),
        isActivated = isActivated,
        newText = newText
    )
}
</code>```

答:
I assume the reason for this kind of warning is because you usually have one modifier that has to be applied to the whole view. Having an other modifier in arguments is kind of OK, but, for example if you need to apply Modifier.align, you had to duplicate it.

In your case, when you look from where you're using this function, it's hard to tell which modifier will be applied and which is not - it depends on other parameters and you have to know the logic.

I think at least it could have one generic modifier named modifier, which would apply for both views, and two named ones - in my opinion this would make the API a bit more predictable. You can chain modifiers like this: modifier.then(iconModifier).yourModifier()

Anyway, you can suppress it:

```<code>@SuppressLint("ModifierParameter")
@Composable
// ...
</code>```

Body:
If we have a compose component which gets two or more modifiers, how should we handle it ?
I mean the naming of modifiers while lint complains changing the name of modifier parameter

Sample code to figure out easily :

@Composable
    private fun CompletionSection(iconModifier: Modifier, textModifier: Modifier, isActivated: Boolean, newText: String?) {
        if (isActivated) {
            Icon(
                painter = painterResource(R.drawable.ds_ic_check_circle),
                modifier = iconModifier
                    .wrapContentSize()
                    .padding(top = 18.dp),
                tint = MaterialTheme.colors.positive,
                contentDescription = null
            )
        } else if (!newText.isNullOrBlank()) {
            Surface(
                modifier = textModifier.padding(top = 18.dp),
                shape = RoundedCornerShape(32.dp),
                border = BorderStroke(width = 2.dp, color = MaterialTheme.colors.primary.copy(alpha = 0.6f)),
            ) {
                Text(
                    overflow = TextOverflow.Ellipsis,
                    maxLines = 1,
                    fontSize = 11.sp,
                    color = MaterialTheme.colors.primary.copy(alpha = 0.6f),
                    text = newText,
                    modifier = Modifier
                        .defaultMinSize(minHeight = 20.dp)
                        .wrapContentSize()
                        .padding(horizontal = 6.dp, vertical = 2.dp),
                    style = MaterialTheme.typography.android.caption2
                )
            }
        }
    }

Here, where the function is used →

ConstraintLayout(
    modifier = Modifier.fillMaxSize(),
    constraintSet = decoupledConstraints(
        marginSpacing02 = marginSpacing02,
        marginSpacing01 = marginSpacing01,
        entity = entity
    )
) {

    CompletionSection(
        iconModifier = Modifier.layoutId("completedIcon"),
        textModifier = Modifier.layoutId("newTextField"),
        isActivated = isActivated,
        newText = newText
    )
}

Body:
I assume the reason for this kind of warning is because you usually have one modifier that has to be applied to the whole view. Having an other modifier in arguments is kind of OK, but, for example if you need to apply Modifier.align, you had to duplicate it.

In your case, when you look from where you're using this function, it's hard to tell which modifier will be applied and which is not - it depends on other parameters and you have to know the logic.

I think at least it could have one generic modifier named modifier, which would apply for both views, and two named ones - in my opinion this would make the API a bit more predictable. You can chain modifiers like this: modifier.then(iconModifier).yourModifier()

Anyway, you can suppress it:

@SuppressLint("ModifierParameter")
@Composable
// ...


问:
Azure Data Factory - Import excel file with dynamic range2
I have a scenario where I'm converting Excel to CSV/TXT my excel file is formatted,which means main content starts at let's say A12 but end cell is dynamic( like Y400 or y700 etc..) that we don't know, in that case is there a possibility in ADF to define Excel range.</p>

答:
Use a DataFlow and follow the below steps:

1.Add your excel/CSV Source data set( Insert 'FileName' in column to save filename
2. add filter activity and insert 'length(trim(replace(trim(replace(replace(replace(replace(replace( toString(array(columns())  ),'null','' ), ',',''),FileName,''),'[',''),']','')),'""',''))) !=  0'
3. Boom!! empty rows are gone.


问:
What causes this syntax error when creating a table?
I am trying to create a table in MySQL, but I am getting an error. The code is looking OK to me, but I don't know why I am getting the error.

This is the code :

```<code>CREATE TABLE usage (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_location     VARCHAR(20) ,
    time_spent      INT
);
</code>```

The error that I am getting:

```<code>Query 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_locatio' at line 1
</code>```

答:
Try putting backticks around usage. It seems to be a keyword.

CREATE TABLE `usage` (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_location     VARCHAR(20) ,
    time_spent      INT
);
```

Body:
I am trying to create a table in MySQL, but I am getting an error. The code is looking OK to me, but I don't know why I am getting the error.

This is the code :

CREATE TABLE usage (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_location     VARCHAR(20) ,
    time_spent      INT
);

The error that I am getting:

Query 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_locatio' at line 1


问:
Apache Pulsar on hybrid cloud
I want to use Apache Pulsar on a hybrid cloud where I want to deploy Apache Pulsar cluster on cloud.My subscriber will be on cloud and consumer will be deployed on premises. Is it possible to have this sort of configuration for pulsar? If yes, what configurations need to be done to have subscriber on cloud and consumer on premise?</p>

答:
Yes.   As long as you have access, you will have no issues.

StreamNative Cloud does it with OAuth.

Here are some references

https://github.com/streamnative/examples/tree/master/cloud/go

https://streamnative.io/blog/engineering/2021-11-17-building-edge-applications-with-apache-pulsar/

https://github.com/tspannhw/SpeakerProfile/tree/main/2021/talks

Title: Apache Pulsar on hybrid cloud


答:
Composables are designed to accept only one Modifier, so the lint won't be satifsfied no matter how you rename them.

The Composable is something like a unit of interface, and it having multiple modifiers is leaking its inner workings to the outer composables that use it.

Title: how should name the modifier params in Jetpack compose component which gets two or more modifiers?


问:
How do I join two queries in SQL using UNION ALL operation?
everyone.

This is my first query

```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC ;
</code>```

And this is my second query

```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;
</code>```

So, I just want to know what do I have to do to join these queries using UNION ALL (and not any JOIN operator). Cz the next is not working for me.

```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC
UNION ALL
SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;
</code>```

Thank u'all, community.
(I really appreciate any kind of feedback).

答:
Remove the ORDER BY from the top query.

This will error:

```<code>SELECT 1 AS i
ORDER BY i
UNION ALL
SELECT 2 AS i
ORDER BY i
</code>```

This will not:

```<code>SELECT 1 AS i
UNION ALL
SELECT 2 AS i
ORDER BY i
</code>```

Body:
everyone.

This is my first query

SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC ;

And this is my second query

SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;

So, I just want to know what do I have to do to join these queries using UNION ALL (and not any JOIN operator). Cz the next is not working for me.

SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC
UNION ALL
SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;

Thank u'all, community.
(I really appreciate any kind of feedback).

Body:
Remove the ORDER BY from the top query.

This will error:

SELECT 1 AS i
ORDER BY i
UNION ALL
SELECT 2 AS i
ORDER BY i

This will not:

SELECT 1 AS i
UNION ALL
SELECT 2 AS i
ORDER BY i


问:
MKAnnotationView: Memory leak
I'm using the following code to make a pin for annotation:

```<code>- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)           annotation
{
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorGreen;
    annView.animatesDrop=TRUE;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);

    return annView;
}
</code>```

Everything works perfectly, however Analyze in XCode shows memory leak in this code. In fact, I see it too cos I allocated object and then did not released it.
How can I avoid memory leak here?

答:
You didn't wrote, but I think analyzer tells you what it leaks here:

```<code>MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]
                                 initWithAnnotation:annotation
                                    reuseIdentifier:@"currentloc"];
</code>```

Thats because you need autorelease item:

```<code>MKPinAnnotationView *annView=[[[MKPinAnnotationView alloc]
                                  initWithAnnotation:annotation
                                     reuseIdentifier:@"currentloc"] autorelease];
</code>```

UPDATE

Also you don't reuse created annotations, try do this:

```<code>MKPinAnnotationView *annView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"currentloc"];
if(annView == nil)
    annView = annView=[[[MKPinAnnotationView alloc]
                         initWithAnnotation:annotation
                            reuseIdentifier:@"currentloc"] autorelease];
</code>```

Title: MKAnnotationView: Memory leak

Body:
I'm using the following code to make a pin for annotation:

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)           annotation
{
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorGreen;
    annView.animatesDrop=TRUE;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);

    return annView;
}

Everything works perfectly, however Analyze in XCode shows memory leak in this code. In fact, I see it too cos I allocated object and then did not released it.
How can I avoid memory leak here?

Body:
You didn't wrote, but I think analyzer tells you what it leaks here:

MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]
                                 initWithAnnotation:annotation
                                    reuseIdentifier:@"currentloc"];

Thats because you need autorelease item:

MKPinAnnotationView *annView=[[[MKPinAnnotationView alloc]
                                  initWithAnnotation:annotation
                                     reuseIdentifier:@"currentloc"] autorelease];

UPDATE

Also you don't reuse created annotations, try do this:

MKPinAnnotationView *annView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"currentloc"];
if(annView == nil)
    annView = annView=[[[MKPinAnnotationView alloc]
                         initWithAnnotation:annotation
                            reuseIdentifier:@"currentloc"] autorelease];


问:
XCBUtil.PropertyListConversionError in Xcode
When I try to run my project, I get this error, pointing to my localized .strings file:

read failed: The operation couldn’t be completed. (XCBUtil.PropertyListConversionError error 1.)

What can I do to fix this issue?

答: For me I got error XCBUtil.PropertyListConversionError error 2.). It happened for combination INFOPLIST_OTHER_PREPROCESSOR_FLAGS = -traditional and INFOPLIST_PREFIX_HEADER which contained comments started with //. So I fixed it by changing comments to old style: /* */


问:
How do I put a description in an aws lambda thru aws web console
From AWS, I created a lambda in aws console the description is blank after it was created, is there any way to edit and put a description from the aws web console? I can't find if there's any field to do that.

here's the screenshot

答:
For odd reasons at the moment of this post, you can find this setting in a surprising place

Lambda >

Functions >

YourLambdaName >

Configuration >

Execution role > Edit >

Basic settings > Description

After you enter a description the name of the field is changed from Execution role to General configuration. Probably in near future AWS is going to change this UI behavior


答: "usage" cannot be used as a table name. It is a special code defined in MYSQL.</p>

Title: What causes this syntax error when creating a table?


答:
"order by" is not supported before "union all". Hope it is working for you.</p>
```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND
AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
UNION ALL
SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;
</code>```

Title: How do I join two queries in SQL using UNION ALL operation?

Body:
"order by" is not supported before "union all". Hope it is working for you.

SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND
AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
UNION ALL
SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;


问:
Why does my sonarqube give 0% coverage while I have unit tests?
So I am using SonarQube to improve my code. The problem is that I keep getting 0% coverage. I think my build.gradle file is not correct, but I am not sure that is the problem. Can anyone check for me if my build.gradle is correct or not so that if this is not the problem I keep looking what else is the problem.

My build.gradle:

```<code>plugins {
    id 'org.springframework.boot' version '2.4.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id "org.sonarqube" version "3.2.0"
    id 'jacoco'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '15'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    implementation('io.jsonwebtoken:jjwt:0.2')
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compile 'junit:junit:4.12'
    implementation 'org.modelmapper:modelmapper:2.4.1'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation 'org.eclipse.jgit:org.eclipse.jgit:5.4.2.201908231537-r'
    /**
     * JUnit jupiter with mockito.
     */
    testCompile group: 'org.mockito', name: 'mockito-junit-jupiter', version: '2.19.0'

    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.19.0'
    testCompile group: 'org.springframework.security', name: 'spring-security-test', version: '5.1.6.RELEASE'
}

sonarqube{
    properties{
        property 'sonarjava.source', '1.8'
        property 'sonar.java.coveragePlugin', 'jacoco'
        property 'sonar.jacoco.reportPaths', 'build/reports/jacoco/test/jacocoTestReport.xml'
        property 'sonar.java.test.binaries'
    }
}
test {
    useJUnitPlatform()
}
</code>```

Thanks in advance!

答:
Add jacocoTestReport task in build.gradle

```<code>jacocoTestReport {
reports {
    xml.enabled true
}
</code>```

}

Run -->

```<code>gradle build jacocoTestReport sonarqube
</code>```

This SonarSource Guide might help you to understand it better
https://community.sonarsource.com/t/coverage-test-data-importing-jacoco-coverage-report-in-xml-format/12151

Check build.gradle in this sample project provided in SonarQube documentation -- https://github.com/SonarSource/sonar-scanning-examples/blob/master/sonarqube-scanner-gradle/gradle-basic/build.gradle

Body:
So I am using SonarQube to improve my code. The problem is that I keep getting 0% coverage. I think my build.gradle file is not correct, but I am not sure that is the problem. Can anyone check for me if my build.gradle is correct or not so that if this is not the problem I keep looking what else is the problem.

My build.gradle:

plugins {
    id 'org.springframework.boot' version '2.4.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id "org.sonarqube" version "3.2.0"
    id 'jacoco'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '15'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    implementation('io.jsonwebtoken:jjwt:0.2')
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compile 'junit:junit:4.12'
    implementation 'org.modelmapper:modelmapper:2.4.1'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation 'org.eclipse.jgit:org.eclipse.jgit:5.4.2.201908231537-r'
    /**
     * JUnit jupiter with mockito.
     */
    testCompile group: 'org.mockito', name: 'mockito-junit-jupiter', version: '2.19.0'

    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.19.0'
    testCompile group: 'org.springframework.security', name: 'spring-security-test', version: '5.1.6.RELEASE'
}

sonarqube{
    properties{
        property 'sonarjava.source', '1.8'
        property 'sonar.java.coveragePlugin', 'jacoco'
        property 'sonar.jacoco.reportPaths', 'build/reports/jacoco/test/jacocoTestReport.xml'
        property 'sonar.java.test.binaries'
    }
}
test {
    useJUnitPlatform()
}

Thanks in advance!

Body:
Add jacocoTestReport task in build.gradle

jacocoTestReport {
reports {
    xml.enabled true
}

}

Run -->

gradle build jacocoTestReport sonarqube

This SonarSource Guide might help you to understand it better
https://community.sonarsource.com/t/coverage-test-data-importing-jacoco-coverage-report-in-xml-format/12151

Check build.gradle in this sample project provided in SonarQube documentation -- https://github.com/SonarSource/sonar-scanning-examples/blob/master/sonarqube-scanner-gradle/gradle-basic/build.gradle


问:
Why is 'undefined' returned when comparing an function argument to a string from a function?
I created cpuPlay to call either rock, paper, or scissors, whenever a random number between 0-2 is called. This function works properly, but rps() is the function that I can't seem to build properly after 3 days of doing this. No matter how I build this, it seems I keep on getting one of four answers when I call rps(). The answers I get are either 'rock','paper','scissors','undefined'.

Before I thought it was because I used .toLowerCase() on playerChoice, but either way, this function has been giving the same results. If you keep on running rps('paper'), it eventually shows. I'm not sure how I should go any further with this problem, or maybe I'm not supposed to be able to compare.  I don't even know anymore.

```<code>function cpuPlay(){
    let numberGen = Math.floor(Math.random() * 3)

  if (numberGen === 0){
    return 'rock'
  }
  if (numberGen === 1){
    return 'paper'
  }
  if (numberGen === 2){
    return 'scissors'
  }
}
// cpuPlay()

function rps(playersChoice){
  if(playersChoice == 'paper' && cpuPlay() == 'rock'){
    console.log('rock')
  } else if (playersChoice == 'paper' && cpuPlay() == 'paper'){
    console.log('paper')
  } else if (playersChoice == 'paper' &&  cpuPlay() == 'scissors'){
    console.log('scissors');
  }
}
rps('paper')
</code>```

答:
You are calling cpuPlay() in each expression so it is possible that every conditional fails, because cpuPlay() value is changing, you can try this:

function cpuPlay(){
    let numberGen = Math.floor(Math.random() * 3)

  if (numberGen === 0){
    return 'rock'
  }
  if (numberGen === 1){
    return 'paper'
  }
  if (numberGen === 2){
    return 'scissors'
  }
}

function rps(playersChoice){
  let currentCpuPlay = cpuPlay()
  if(playersChoice == 'paper' && currentCpuPlay == 'rock'){
    console.log('rock')
  } else if (playersChoice == 'paper' && currentCpuPlay == 'paper'){
    console.log('paper')
  } else if (playersChoice == 'paper' &&  currentCpuPlay == 'scissors'){
    console.log('scissors');
  }
}
rps('paper')```

Body:
I created cpuPlay to call either rock, paper, or scissors, whenever a random number between 0-2 is called. This function works properly, but rps() is the function that I can't seem to build properly after 3 days of doing this. No matter how I build this, it seems I keep on getting one of four answers when I call rps(). The answers I get are either 'rock','paper','scissors','undefined'.

Before I thought it was because I used .toLowerCase() on playerChoice, but either way, this function has been giving the same results. If you keep on running rps('paper'), it eventually shows. I'm not sure how I should go any further with this problem, or maybe I'm not supposed to be able to compare.  I don't even know anymore.

function cpuPlay(){
    let numberGen = Math.floor(Math.random() * 3)

  if (numberGen === 0){
    return 'rock'
  }
  if (numberGen === 1){
    return 'paper'
  }
  if (numberGen === 2){
    return 'scissors'
  }
}
// cpuPlay()

function rps(playersChoice){
  if(playersChoice == 'paper' && cpuPlay() == 'rock'){
    console.log('rock')
  } else if (playersChoice == 'paper' && cpuPlay() == 'paper'){
    console.log('paper')
  } else if (playersChoice == 'paper' &&  cpuPlay() == 'scissors'){
    console.log('scissors');
  }
}
rps('paper')


问:
build a parse tree from if statement
My goal is to be able to say if a particular JSON objects matches a particular set of rules that are stored in a .yaml file.
A rule is similar to something that we can find in an if statement. For example:

```<code>if( A and B OR C):
   #do something
</code>```

where A, B and C are some conditions, for example to check if one attribute of the JSON object is greater than 0 (just an example).

I would like to build the corresponding parse tree of a particular if statement.
In such a tree, the nodes would be the logical operators, namely AND and OR and the leaves would be the actual conditions. Let's consider the following condition:
(((A and B) OR (C AND B AND D AND E)) AND F). That would give us the following parse tree:

After building such a tree, one would iterate from the far left of the tree (or far right, does not matter) and start performing the tests. If we start for example in the far left of the tree, that would be the leaf A. One verifies if A is satisfied, if it is not, then the JSON object does not match the rule since its parent is an AND operator, if it does, one would move to the second test, namely the condition B. Then check the conditions C, B and D and so on until you perform all the tests.

What approach can I use to build such trees ? Are there  existing parsers that I can use to achieve this ?
If there is a better way to achieve this, I would like to hear it.
Thank you!

答:
You will indeed need to parse the text in some way.

I would suggest relying on a regular expression to tokenise the input, so that you get the following tokens:

(

)

AND

OR

Anything else will be considered an atomic condition.

Then iterate those tokens and use a stack or recursion to build the tree.

From your other questions I see you use Python, so in Python you could create a class for each operator (OR, AND) and let it inherit from list. Such a list will either have as members strings (leaves of the tree) or more OR or AND list instances. So the whole tree is actually a nested list structure.

Here is how you would implement those list-based classes:

# A generic class from which all operators derive
class Node(list):
    @property
    def label(self):
        return self.__class__.__name__

    def __repr__(self):
        return self.label + super().__repr__()

# Subclass for each operator: no additional logic is needed
class AND(Node): pass
class OR(Node): pass
```
<p>Here is the parser:</p>
<pre class="lang-py prettyprint-override"><code>import re

def parse(s):
    # Rely completely on the operators that have been defined as subclasses of Node
    Operators = { cls.__name__ : cls for cls in Node.__subclasses__() }
    # Create a regular expression based on those operator names (AND, OR)
    regex = r"\s*([()]|" + "|".join(fr"\b{operator}\b" for operator in Operators.keys()) + ")\s*"
    # Tokenise the input
    tokens = iter((token for token in re.split(regex, s, flags=re.IGNORECASE) if token))

    def dfs(end=")"):
        operator = ""
        operands = []
        while True:
            token = next(tokens, "")
            if not token or token == ")":
                raise ValueError(f"Operand expected, but got '{token}'")
            operands.append(dfs() if token == "(" else token)
            token = next(tokens, "")
            if token == end:
                return Operators[operator](operands) if operator else operands[0]
            utoken = token.upper()
            if utoken in Operators:
                if operator and utoken != operator:
                    raise ValueError("Use parentheses to indicate operator precedence")
                operator = utoken
            else:
                raise ValueError(f"{', '.join(Node.keys())} expected, but got '{token}'")
    return dfs("")
</code>```

Use it as follows:

# Example run
s = "(((A and B) OR (C AND B AND D AND E)) AND F)"
tree = parse(s)
print(tree)
# Demo on how to address specific nodes in the tree
print(tree.label, tree[0].label, tree[0][0].label, tree[0][0][0])
```

Title: build a parse tree from if statement

Body:
My goal is to be able to say if a particular JSON objects matches a particular set of rules that are stored in a .yaml file.
A rule is similar to something that we can find in an if statement. For example:

if( A and B OR C):
   #do something

where A, B and C are some conditions, for example to check if one attribute of the JSON object is greater than 0 (just an example).

I would like to build the corresponding parse tree of a particular if statement.
In such a tree, the nodes would be the logical operators, namely AND and OR and the leaves would be the actual conditions. Let's consider the following condition:
(((A and B) OR (C AND B AND D AND E)) AND F). That would give us the following parse tree:

After building such a tree, one would iterate from the far left of the tree (or far right, does not matter) and start performing the tests. If we start for example in the far left of the tree, that would be the leaf A. One verifies if A is satisfied, if it is not, then the JSON object does not match the rule since its parent is an AND operator, if it does, one would move to the second test, namely the condition B. Then check the conditions C, B and D and so on until you perform all the tests.

What approach can I use to build such trees ? Are there  existing parsers that I can use to achieve this ?
If there is a better way to achieve this, I would like to hear it.
Thank you!

Body:
You will indeed need to parse the text in some way.

I would suggest relying on a regular expression to tokenise the input, so that you get the following tokens:

(

)

AND

OR

Anything else will be considered an atomic condition.

Then iterate those tokens and use a stack or recursion to build the tree.

From your other questions I see you use Python, so in Python you could create a class for each operator (OR, AND) and let it inherit from list. Such a list will either have as members strings (leaves of the tree) or more OR or AND list instances. So the whole tree is actually a nested list structure.

Here is how you would implement those list-based classes:

# A generic class from which all operators derive
class Node(list):
    @property
    def label(self):
        return self.__class__.__name__

    def __repr__(self):
        return self.label + super().__repr__()

# Subclass for each operator: no additional logic is needed
class AND(Node): pass
class OR(Node): pass

Here is the parser:

import re

def parse(s):
    # Rely completely on the operators that have been defined as subclasses of Node
    Operators = { cls.__name__ : cls for cls in Node.__subclasses__() }
    # Create a regular expression based on those operator names (AND, OR)
    regex = r"\s*([()]|" + "|".join(fr"\b{operator}\b" for operator in Operators.keys()) + ")\s*"
    # Tokenise the input
    tokens = iter((token for token in re.split(regex, s, flags=re.IGNORECASE) if token))

    def dfs(end=")"):
        operator = ""
        operands = []
        while True:
            token = next(tokens, "")
            if not token or token == ")":
                raise ValueError(f"Operand expected, but got '{token}'")
            operands.append(dfs() if token == "(" else token)
            token = next(tokens, "")
            if token == end:
                return Operators[operator](operands) if operator else operands[0]
            utoken = token.upper()
            if utoken in Operators:
                if operator and utoken != operator:
                    raise ValueError("Use parentheses to indicate operator precedence")
                operator = utoken
            else:
                raise ValueError(f"{', '.join(Node.keys())} expected, but got '{token}'")
    return dfs("")

Use it as follows:

# Example run
s = "(((A and B) OR (C AND B AND D AND E)) AND F)"
tree = parse(s)
print(tree)
# Demo on how to address specific nodes in the tree
print(tree.label, tree[0].label, tree[0][0].label, tree[0][0][0])