问:
Python Singleton objects with the same attribute should reference to the same object
I want Python to return the same object when the instances are created with the similar attributes. Also when I am changing some attribute of one instance, that attribute should be synchronized between other instances also.

class Session:
    def __init__(self, id):
        self.id = id
        self.data = None

session1 = Session(1)
session1.data = 202
print(session1.data) # 202
print(id(session1)) # should be 1111

session11 = Session(1)
print(session11.data) # 202
print(id(session11)) # should be the same as session1 -> 1111

session2 = Session(2)
print(id(session2)) # 2222

```

You can see above that I want session1 and session1a be the same object because of Session(1), while session2 is another object because of Session(2).

How could I do it?

答:
You can override the __new__ method to return a cached object for the same parameters.

A weakref.WeakValueDictionary is an appropriate data structure for storing your cached objects, when objects are deleted they will be garbage collected rather than persisting because your cache references them

```<code>from weakref import WeakValueDictionary

class Session:

    _cache = WeakValueDictionary()

    def __new__(cls, id):
        obj = cls._cache.get(id)
        if not obj:
            obj = object.__new__(cls)
            cls._cache[id] = obj
        return obj

    def __init__(self, id):
        self.id = id
</code>```

The same object will be returned for the same id

```<code>s1 = Session(1)
print(id(s1))  # 4532746224
s2 = Session(1)
print(id(s2))  # 4532746224
s3 = Session(2)
print(id(s3))  # 4534405248
</code>```

Body:
I want Python to return the same object when the instances are created with the similar attributes. Also when I am changing some attribute of one instance, that attribute should be synchronized between other instances also.

class Session:
    def __init__(self, id):
        self.id = id
        self.data = None

session1 = Session(1)
session1.data = 202
print(session1.data) # 202
print(id(session1)) # should be 1111

session11 = Session(1)
print(session11.data) # 202
print(id(session11)) # should be the same as session1 -> 1111

session2 = Session(2)
print(id(session2)) # 2222

You can see above that I want session1 and session1a be the same object because of Session(1), while session2 is another object because of Session(2).

How could I do it?

Body:
You can override the __new__ method to return a cached object for the same parameters.

A weakref.WeakValueDictionary is an appropriate data structure for storing your cached objects, when objects are deleted they will be garbage collected rather than persisting because your cache references them

from weakref import WeakValueDictionary

class Session:

    _cache = WeakValueDictionary()

    def __new__(cls, id):
        obj = cls._cache.get(id)
        if not obj:
            obj = object.__new__(cls)
            cls._cache[id] = obj
        return obj

    def __init__(self, id):
        self.id = id

The same object will be returned for the same id

s1 = Session(1)
print(id(s1))  # 4532746224
s2 = Session(1)
print(id(s2))  # 4532746224
s3 = Session(2)
print(id(s3))  # 4534405248


来源: stackexchange

问:
Change quantity of product in django ecommerce website? DJANGO
It's not giving an error. The quantity is being changed only in the first product, even if when I press arrow of second product, the quantity of first product is being changed.
cart.js

```<code>var changeQ = document.getElementsByClassName('increase')

for (i = 0; i < changeQ.length; i++) {
    changeQ[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action
        console.log('productId:', productId, 'Action:', action)

        if (action == 'plus'){
            Increase(productId, action)
        }
        else if(action=='minus'){
            Decrease(productId, action)
        }
    })
}

function Increase(productId,action){
    console.log('Increase')
    var quantity = Number(document.getElementById("quantity").value);
    quantity = quantity+1;
    document.getElementById("quantity").value = quantity;
    console.log(quantity);
}

function Decrease(productId,action){
    var quantity = Number(document.getElementById("quantity").value);
    console.log('Decrease')
    quantity = quantity-1;
    document.getElementById("quantity").value=quantity;

}
</code>```

template

```<code><div class="counter">
    <div class="arrow-up increase" id="arrow-up" data-product="{{item.product.id}}" data-action="plus" ><i class="fa fa-arrow-up"></i></div>
    <div class="quantity"><input type="number" id="quantity" value="1"></div>
    <div class="arrow-down increase" id="arrow-down" data-product="{{item.product.id}}" data-action="minus"><i class="fa fa-arrow-down"></i></div>

  </div>
</code>```

It's in Django. So what can I do to indicate the specific product. Can someone help me to solve this problem, please!

答:
Since you have used document.getElementById() in the Increase and Decrease functions it returns the first element with id='quantity' which is why you are only able to set the quantity for the first product.

So you need to use some value to distinguish between the input tags with id='quantity'. I would suggest adding data-product="{{ item.product.id }}" to the input tag since you are already passing the product id as productId to both the functions.

Thus your template would be some thing like this

```<code><div class="counter">
    <div class="arrow-up increase" id="arrow-up" data-product="{{item.product.id}}" data-action="plus" ><i class="fa fa-arrow-up"></i></div>
    <div class="quantity"><input type="number" id="quantity" value="1" data-product="{{item.product.id}}"></div>
    <div class="arrow-down increase" id="arrow-down" data-product="{{item.product.id}}" data-action="minus"><i class="fa fa-arrow-down"></i></div>
</div>
</code>```

And the Increase and Decrease functions would be modified like so

```<code>function Increase(productId,action){
    console.log('Increase')
    var quantity = Number(document.querySelector(`input[data-product=${productId}]`).value);
    quantity = quantity+1;
    document.querySelector(`input[data-product=${productId}]`).value = quantity;
    console.log(quantity);
}

function Decrease(productId,action){
    var quantity = Number(document.querySelector(`input[data-product=${productId}]`).value);
    console.log('Decrease')
    quantity = quantity-1;
    document.querySelector(`input[data-product=${productId}]`).value=quantity;
}
</code>```

document.querySelector() allows us to use CSS selectors to select elements. Here we use it to select input tags with the data-product attribute equal to the value in productId.

${} is for string interpolation, we can use it to insert the productId into the selector string.

ContentLicense: CC BY-SA 4.0

Body:
It's not giving an error. The quantity is being changed only in the first product, even if when I press arrow of second product, the quantity of first product is being changed.
cart.js

var changeQ = document.getElementsByClassName('increase')

for (i = 0; i < changeQ.length; i++) {
    changeQ[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action
        console.log('productId:', productId, 'Action:', action)

        if (action == 'plus'){
            Increase(productId, action)
        }
        else if(action=='minus'){
            Decrease(productId, action)
        }
    })
}

function Increase(productId,action){
    console.log('Increase')
    var quantity = Number(document.getElementById("quantity").value);
    quantity = quantity+1;
    document.getElementById("quantity").value = quantity;
    console.log(quantity);
}

function Decrease(productId,action){
    var quantity = Number(document.getElementById("quantity").value);
    console.log('Decrease')
    quantity = quantity-1;
    document.getElementById("quantity").value=quantity;

}

template

<input type="number" id="quantity" value="1">

It's in Django. So what can I do to indicate the specific product. Can someone help me to solve this problem, please!

Body:
Since you have used document.getElementById() in the Increase and Decrease functions it returns the first element with id='quantity' which is why you are only able to set the quantity for the first product.

So you need to use some value to distinguish between the input tags with id='quantity'. I would suggest adding data-product="{{ item.product.id }}" to the input tag since you are already passing the product id as productId to both the functions.

Thus your template would be some thing like this

<div class="counter">
    <div class="arrow-up increase" id="arrow-up" data-product="{{item.product.id}}" data-action="plus" ><i class="fa fa-arrow-up"></i></div>
    <div class="quantity"><input type="number" id="quantity" value="1" data-product="{{item.product.id}}"></div>
    <div class="arrow-down increase" id="arrow-down" data-product="{{item.product.id}}" data-action="minus"><i class="fa fa-arrow-down"></i></div>
</div>

And the Increase and Decrease functions would be modified like so

function Increase(productId,action){
    console.log('Increase')
    var quantity = Number(document.querySelector(`input[data-product=${productId}]`).value);
    quantity = quantity+1;
    document.querySelector(`input[data-product=${productId}]`).value = quantity;
    console.log(quantity);
}

function Decrease(productId,action){
    var quantity = Number(document.querySelector(`input[data-product=${productId}]`).value);
    console.log('Decrease')
    quantity = quantity-1;
    document.querySelector(`input[data-product=${productId}]`).value=quantity;
}

document.querySelector() allows us to use CSS selectors to select elements. Here we use it to select input tags with the data-product attribute equal to the value in productId.

${} is for string interpolation, we can use it to insert the productId into the selector string.


问:
How to make a pivot table from a dataframe with multiple columns?
Please help me.

My dataframe looks like this:

date
account
action

2021-01-11
504
login

2021-01-11
504
edit_profile

2021-01-11
504
logout

2021-01-12
11
login

2021-01-12
11
login

2021-01-14
303
edit_profile

2021-01-14
303
logout

What I want to achieve is this:

date
account
login
edit_profile
logout

2021-01-11
504
1
1
1

2021-01-12
11
2
0
0

2021-01-14
303
0
1
1

The first thing I thought about was pivot table, but the problem is that I don't have total count for certain 'account's daily actions. How to count the number of occurrences within a time range for each value? Please help.

答:
For performance, try to avoid loops with pandas. There are plenty of vectorized functions:

```<code>import pandas as pd

#recreating your sample data
from io import StringIO
data1 = """
date         account   action
2021-01-11     504     login
2021-01-11     504     edit_profile
2021-01-11     504     logout
2021-01-12     11      login
2021-01-12     11      login
2021-01-14     303     edit_profile
2021-01-14     303     logout
"""
df = pd.read_csv(StringIO(data1), sep = "\s{2,}", engine="python")
df["date"] = pd.to_datetime(df["date"])

df1 = df.groupby(by=["date", "account", "action"]).size().unstack(fill_value=0)

print(df1)
</code>```

Sample output:

```<code>action              edit_profile  login  logout
date       account
2021-01-11 504                 1      1       1
2021-01-12 11                  0      2       0
2021-01-14 303                 1      0       1
</code>```

Please note that you now have a MultiIndex dataframe. You can remove the index levels by adding .reset_index()

Body:
For performance, try to avoid loops with pandas. There are plenty of vectorized functions:

import pandas as pd

#recreating your sample data
from io import StringIO
data1 = """
date         account   action
2021-01-11     504     login
2021-01-11     504     edit_profile
2021-01-11     504     logout
2021-01-12     11      login
2021-01-12     11      login
2021-01-14     303     edit_profile
2021-01-14     303     logout
"""
df = pd.read_csv(StringIO(data1), sep = "\s{2,}", engine="python")
df["date"] = pd.to_datetime(df["date"])

df1 = df.groupby(by=["date", "account", "action"]).size().unstack(fill_value=0)

print(df1)

Sample output:

action              edit_profile  login  logout
date       account
2021-01-11 504                 1      1       1
2021-01-12 11                  0      2       0
2021-01-14 303                 1      0       1

Please note that you now have a MultiIndex dataframe. You can remove the index levels by adding .reset_index()


问:
Accessing parent Javascript function from within iframe?
I'm trying to access a function that would update the JQuery UI progress bar located in the parent from within the iframe page. Every time somebody clicks on a link in the iframe page I want it to update the progress bar. I've searched around for answers, and using "window.parent.FunctionName()" is the solution that is given, but for some reason it doesn't seem to work in my situation? Any ideas?

UPDATE: It seems to work in safari, firefox, but not in chrome???

The function that I want to access in the parent page is:

```<code>var percentage = 0;

$('ul li a').one('click', updateBar);

function updateBar() {
    percentage += 8;
    $('.ui-progressbar-value').stop().animate({ width: percentage+"%" }, 500)
    $('.middle').progressbar('option','value', percentage);

    if(percentage > 100) {
        $('ui-progressbar-value').stop().animate({ width: "100%"}, 500);
    }
}
</code>```

The JQuery call that I'm calling from the iframe page is:

```<code>$('#sidenav ul li a').one('click', window.parent.updateBar);
</code>```

答:
try</p>

```<code>$('#sidenav ul li a').one('click',function(){

 window.parent.updateBar();

});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to access a function that would update the JQuery UI progress bar located in the parent from within the iframe page. Every time somebody clicks on a link in the iframe page I want it to update the progress bar. I've searched around for answers, and using "window.parent.FunctionName()" is the solution that is given, but for some reason it doesn't seem to work in my situation? Any ideas?

UPDATE: It seems to work in safari, firefox, but not in chrome???

The function that I want to access in the parent page is:

var percentage = 0;

$('ul li a').one('click', updateBar);

function updateBar() {
    percentage += 8;
    $('.ui-progressbar-value').stop().animate({ width: percentage+"%" }, 500)
    $('.middle').progressbar('option','value', percentage);

    if(percentage > 100) {
        $('ui-progressbar-value').stop().animate({ width: "100%"}, 500);
    }
}

The JQuery call that I'm calling from the iframe page is:

$('#sidenav ul li a').one('click', window.parent.updateBar);

Body:
try

$('#sidenav ul li a').one('click',function(){

 window.parent.updateBar();

});


问:
Save only best weights with huggingface transformers
Currently, I'm building a new transformer-based model with huggingface-transformers, where attention layer is different from the original one. I used run_glue.py to check performance of my model on GLUE benchmark. However, I found that Trainer class of huggingface-transformers saves all the checkpoints that I set, where I can set the maximum number of checkpoints to save. However, I want to save only the weight (or other stuff like optimizers) with best performance on validation dataset, and current Trainer class doesn't seem to provide such thing. (If we set the maximum number of checkpoints, then it removes older checkpoints, not ones with worse performances). Someone already asked about same question on Github, but I can't figure out how to modify the script and do what I want. Currently, I'm thinking about making a custom Trainer class that inherits original one and change the train() method, and it would be great if there's an easy and simple way to do this. Thanks in advance.

答:
This answer could be useful</p>
```<code>training_args = TrainingArguments(
    output_dir=repo_name,
    group_by_length=True,
    length_column_name='input_length',
    per_device_train_batch_size=24,
    gradient_accumulation_steps=2,
    evaluation_strategy="steps",
    num_train_epochs=20,
    fp16=True,
    save_steps=1000,
    save_strategy='steps', # we cannot set it to "no". Otherwise, the model cannot guess the best checkpoint.
    eval_steps=1000,
    logging_steps=1000,
    learning_rate=5e-5,
    warmup_steps=500,
    save_total_limit=3,
    load_best_model_at_end = True # this will let the model save the best checkpoint
)
</code>```

Body:
This answer could be useful

training_args = TrainingArguments(
    output_dir=repo_name,
    group_by_length=True,
    length_column_name='input_length',
    per_device_train_batch_size=24,
    gradient_accumulation_steps=2,
    evaluation_strategy="steps",
    num_train_epochs=20,
    fp16=True,
    save_steps=1000,
    save_strategy='steps', # we cannot set it to "no". Otherwise, the model cannot guess the best checkpoint.
    eval_steps=1000,
    logging_steps=1000,
    learning_rate=5e-5,
    warmup_steps=500,
    save_total_limit=3,
    load_best_model_at_end = True # this will let the model save the best checkpoint
)


问:
Permissions For Google Cloud SQL Import Using Service Accounts
I've exported MySQL Database following the MySQL Export Guide successfully.

Now, I'm trying to import MySQL Database following the MySQL Import Guide.

I've checked the permissions for the service_account_email I'm using, and I have allowed both Admin SQL and Admin Storage permissions.

I was able to successfully activate my service account using this command locally:

```<code>gcloud auth activate-service-account <service_account_email> --key-file=<service_account_json_file>
</code>```

After I ran the command:

```<code>gcloud sql import sql <instance> <gstorage_file> --database=<db_name> --async
</code>```

I got this information:

```<code>{
  "error": {
    "errors": Array[1][
      {
        "domain": "global",
        "reason": "required",
        "message": "Login Required",
        "locationType": "header",
        "location": "Authorization"
      }
    ],
    "code": 401,
    "message": "Login Required"
  }
}
</code>```

Other Things I've Tried

I also tried using the service_account_email of my SQL instance, which came from:

```<code>gcloud sql instances describe <instance_name>
</code>```

But, it seems to have the same error.

Question

Based on the REST API JSON error I'm given, how do I "login" using the service_account_email so I wouldn't get the 401 Error?

答:
According to the google Docs

Describe the instance you are importing to:

gcloud sql instances describe INSTANCE_NAME

Copy the serviceAccountEmailAddress field.

Use gsutil iam to grant the storage.objectAdmin IAM role to the service account for the bucket.

gsutil iam ch serviceAccount:SERVICE-ACCOUNT:objectAdmin gs://BUCKET-NAME

Then Import the database

Body:
I've exported MySQL Database following the MySQL Export Guide successfully.

Now, I'm trying to import MySQL Database following the MySQL Import Guide.

I've checked the permissions for the service_account_email I'm using, and I have allowed both Admin SQL and Admin Storage permissions.

I was able to successfully activate my service account using this command locally:

gcloud auth activate-service-account <service_account_email> --key-file=<service_account_json_file>

After I ran the command:

gcloud sql import sql <instance> <gstorage_file> --database=<db_name> --async

I got this information:

{
  "error": {
    "errors": Array[1][
      {
        "domain": "global",
        "reason": "required",
        "message": "Login Required",
        "locationType": "header",
        "location": "Authorization"
      }
    ],
    "code": 401,
    "message": "Login Required"
  }
}

Other Things I've Tried

I also tried using the service_account_email of my SQL instance, which came from:

gcloud sql instances describe <instance_name>

But, it seems to have the same error.

Question

Based on the REST API JSON error I'm given, how do I "login" using the service_account_email so I wouldn't get the 401 Error?


问:
Imgur application registration link invalid?
I am trying to register my application on Imgur in order to obtain the  client_id and client_secret as according to the documentation, but the link provided in the docs only redirects me to my Imgur account home page.  Has the registration link been changed?

https://api.imgur.com/oauth2/addclient

答: Now it should be working. I registered two apps today.</p>


问:
How to activate and deactivate GameObjects with a delay in Untiy
I am working on a game, that has a keypad puzzle. A specific key combination lights up one by one, which the player must repeat to solve that puzzle. I am going to let the player know what the combination is by activating and deactivating some GameObjects systematically, one by one. As it suggests, there is some time delay between the deactivation of one GameObject and the activation of another. The problem is, in my code, all the GameObjects activate simultaneously instead of one by one, after a delay.

Here is the code:

```<code> public string Generate(int length, float delay)
    {
        // Variables for logic
        string combination = "";
        int prev = -1; int current = 0;
        int rnd = 0;

        for (int i = 0; i < length; i++)
        {
            rnd = Random.Range(0, BUTTONS);
            while (rnd == prev)
            {
                rnd = Random.Range(0, BUTTONS);
            }
            prev = current;
            current = rnd;

            combination += current.ToString();

            // Activation and Deactivation

            StartCoroutine(GenerateDelay(delay, current));
        }
        return combination;
    }

    IEnumerator GenerateDelay(float delay, int index)
    {
        ButtonClicks[index].SetActive(true);
        yield return new WaitForSeconds(delay);
        ButtonClicks[index].SetActive(false);
    }
</code>```

The loop counter specifies the length of the combination. I believe there is something wrong with the Coroutine I made? Since all the objects activate simultaneously.

Here is the result in the game as well:

We can see, only one button should turn green at a time, but all of them do in this case. Any solutions?

答:
something alot easier then a coroutine is invoking a function, basically create a function to activate/deactivate the wanted object and whenever you want to call it do:

```<code>Invoke("FUNCTIONNAME", TIME);
</code>```

and it will run the function specified after the TIME.

Body:
I am working on a game, that has a keypad puzzle. A specific key combination lights up one by one, which the player must repeat to solve that puzzle. I am going to let the player know what the combination is by activating and deactivating some GameObjects systematically, one by one. As it suggests, there is some time delay between the deactivation of one GameObject and the activation of another. The problem is, in my code, all the GameObjects activate simultaneously instead of one by one, after a delay.

Here is the code:

 public string Generate(int length, float delay)
    {
        // Variables for logic
        string combination = "";
        int prev = -1; int current = 0;
        int rnd = 0;

        for (int i = 0; i < length; i++)
        {
            rnd = Random.Range(0, BUTTONS);
            while (rnd == prev)
            {
                rnd = Random.Range(0, BUTTONS);
            }
            prev = current;
            current = rnd;

            combination += current.ToString();

            // Activation and Deactivation

            StartCoroutine(GenerateDelay(delay, current));
        }
        return combination;
    }

    IEnumerator GenerateDelay(float delay, int index)
    {
        ButtonClicks[index].SetActive(true);
        yield return new WaitForSeconds(delay);
        ButtonClicks[index].SetActive(false);
    }

The loop counter specifies the length of the combination. I believe there is something wrong with the Coroutine I made? Since all the objects activate simultaneously.

Here is the result in the game as well:

We can see, only one button should turn green at a time, but all of them do in this case. Any solutions?

Body:
something alot easier then a coroutine is invoking a function, basically create a function to activate/deactivate the wanted object and whenever you want to call it do:

Invoke("FUNCTIONNAME", TIME);

and it will run the function specified after the TIME.


问:
Creation of init cloud-based VMs(proxmox and terraform)
I want to create 3 VMs (with terraform in proxmox) each with their configuration (ram / cpu / disk) and I want to know if I have created a template (to be cloned later in the terraform file) of a size to give prevents others from having a different configuration

example if I put a vm (1cpu / 2 g ram / 10 G disk) and convert it to templete
[I can't or i can] use it to deploy a VMs (3 cpu and 8G ram and 50 G disk)

if yes how i can do it , thanks for ur help .

答:
Please see my repo:
https://github.com/redhug1/R710

and my notes/documents within may have the answers to your question (and a lot more beside):

17 - R710 Proxmox Ubuntu cloud-init image - Terraform - Ansible

18 - R710 Proxmox - Samba shares for W10 and W10 hosts file for WSL

19 - R710 Proxmox Terraform VMs with different - CPU count - RAM and Disks


问:
Doing multiple sorts across more than one line of code?
I have an array that stores the order that I want to sort a list by.

```<code>SortOrderArray: "Color", "Volume", "Weight"
</code>```

So I want to order my list by Color, Volume, then Weight

```<code>MyList.OrderBy(a=>a.Color).ThenBy(a=>a.Volume).ThenBy(a=>a.Weight).ToList();
</code>```

So that's pretty good.  Now, I want to be able to write a function that does this sorting based on the sortOrder array I send in:

```<code>public List<row> GetSortedList(List<row> list, string[] sortOrder){
    ???
}
</code>```

I can't figure out how to do this without writing a linq query for every combination of sortOrders (27 different queries just seems like the worst way to accomplish this, and has a fairly high possibility of me making a tiny mistake).  I would like to be able to just write 3 linq queries that reorders the list according to each of the 3 sorting methods, something like this:

```<code>switch(sortOrder[0]){
    Sort by the first sort method
}
switch(sortOrder[1]){
    Sort by the second sort method
}
switch(sortOrder[2]){
    Sort by the third sort method
}
</code>```

But if I try doing the above code, it just resorts it each time, instead of doing sub-sorts after the one above it.  Hope that is clear, any help would be appreciated.

答: Have a look at this post from Scott Guthrie: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx</p>

Body:
I have an array that stores the order that I want to sort a list by.

SortOrderArray: "Color", "Volume", "Weight"

So I want to order my list by Color, Volume, then Weight

MyList.OrderBy(a=>a.Color).ThenBy(a=>a.Volume).ThenBy(a=>a.Weight).ToList();

So that's pretty good.  Now, I want to be able to write a function that does this sorting based on the sortOrder array I send in:

public List<row> GetSortedList(List<row> list, string[] sortOrder){
    ???
}

I can't figure out how to do this without writing a linq query for every combination of sortOrders (27 different queries just seems like the worst way to accomplish this, and has a fairly high possibility of me making a tiny mistake).  I would like to be able to just write 3 linq queries that reorders the list according to each of the 3 sorting methods, something like this:

switch(sortOrder[0]){
    Sort by the first sort method
}
switch(sortOrder[1]){
    Sort by the second sort method
}
switch(sortOrder[2]){
    Sort by the third sort method
}

But if I try doing the above code, it just resorts it each time, instead of doing sub-sorts after the one above it.  Hope that is clear, any help would be appreciated.


问:
C++ Esp32 functional infinite loop
So I've such of a code:

```<code>void B();
void C();

void A() {
  Serial.println("Looping");
  B();
}

void B() {
  C();
}

void C() {
  A();
}

void setup() {
  Serial.begin(115200);
  A();
}

void loop() {

};
</code>```

and it works just fine, but when I want to add a condition, like this:

```<code>bool flag = false;

void B();
void C();

void A() {
  Serial.println("Looping");
  if(flag)
    B();
  else
    C();
}

void B() {
  flag = false;
  A();
}

void C() {
  flag = true;
  A();
}

void setup() {
  Serial.begin(115200);
  A();
}

void loop() {

};
</code>```

After a while my esp32 throws a backtrace and reboots:

```<code>Guru Meditation Error: Core  1 panic'ed (Unhandled debug exception)
Debug exception reason: Stack canary watchpoint triggered
</code>```

I need some kind of solution to run B() or C() and "forget" about A() body, as I understood this problem.

UDP
It's just a skelet of a real code, I'm using FreeRTOS (xTaskCreate, ...) to run the logic,
I`ve an idea:

```<code>1) Create 2 Tasks (one of them will be running)
2) Later pass the function I want to call, delete running
3) Such way by switching tasks it should work
</code>```

I've such logic in a project:

```<code>
void B();
void C();

void A() {
  if(server.connect())
    while(server.isConnected()) {
      //makeUpdate, receive new messages
    }

  //  as it fails, make reconnect
  //check wifi connection
    if(wifi)
      B();
    else
      C();
}

void B() {
  // Update Connection With Wifi
  // Go back to connect
  A();
}

void C() {
  // Update Connection With Gprs
  // Go back to connect
  A();
}

void setup() {
  Serial.begin(115200);
  A();
}

void loop() {

};
</code>```

答:
Calling functions like that will cause an infinite recursion, exhaust the stack and make the whole thing crash.

You could call all the functions from inside loop() and other functions just return which function should be called next.

char A() {
  Serial.println("Looping");
  if(flag)
    return 'B';
  else
    return 'C';
}

char B() {
  // Update Connection With Wifi
  // Go back to connect
  return 'A';
}

char C() {
  // Update Connection With Gprs
  // Go back to connect
  return 'A';
}

void setup() {
  Serial.begin(115200);
}

void loop() {
  static char next_function = 'A';
  switch(next_function) {
    case 'A': next_function = A(); break;
    case 'B': next_function = B(); break;
    case 'C': next_function = C(); break;
  }
}
```

Title: C++ Esp32 functional infinite loop

Body:
So I've such of a code:

void B();
void C();

void A() {
  Serial.println("Looping");
  B();
}

void B() {
  C();
}

void C() {
  A();
}

void setup() {
  Serial.begin(115200);
  A();
}

void loop() {

};

and it works just fine, but when I want to add a condition, like this:

bool flag = false;

void B();
void C();

void A() {
  Serial.println("Looping");
  if(flag)
    B();
  else
    C();
}

void B() {
  flag = false;
  A();
}

void C() {
  flag = true;
  A();
}

void setup() {
  Serial.begin(115200);
  A();
}

void loop() {

};

After a while my esp32 throws a backtrace and reboots:

Guru Meditation Error: Core  1 panic'ed (Unhandled debug exception)
Debug exception reason: Stack canary watchpoint triggered

I need some kind of solution to run B() or C() and "forget" about A() body, as I understood this problem.

UDP
It's just a skelet of a real code, I'm using FreeRTOS (xTaskCreate, ...) to run the logic,
I`ve an idea:

1) Create 2 Tasks (one of them will be running)
2) Later pass the function I want to call, delete running
3) Such way by switching tasks it should work

I've such logic in a project:

void B();
void C();

void A() {
  if(server.connect())
    while(server.isConnected()) {
      //makeUpdate, receive new messages
    }

  //  as it fails, make reconnect
  //check wifi connection
    if(wifi)
      B();
    else
      C();
}

void B() {
  // Update Connection With Wifi
  // Go back to connect
  A();
}

void C() {
  // Update Connection With Gprs
  // Go back to connect
  A();
}

void setup() {
  Serial.begin(115200);
  A();
}

void loop() {

};


问:
Ceph cluster down, Reason OSD Full - not starting up
Cephadm Pacific v16.2.7
Our Ceph cluster  is stuck pgs degraded and osd are down
Reason:- OSD's got filled up

Things we tried

Changed vale to to maximum possible combination (not sure if done right ?)
backfillfull < nearfull, nearfull < full, and full < failsafe_full

ceph-objectstore-tool - tried to delte some pgs to recover space

tried to mount osd and delete pg's to recover some space, but not sure how to do it in bluestore .

Global Recovery Event - stuck for ever

```<code>
ceph -s

cluster:
    id:     a089a4b8-2691-11ec-849f-07cde9cd0b53
    health: HEALTH_WARN
            6 failed cephadm daemon(s)
            1 hosts fail cephadm check
            Reduced data availability: 362 pgs inactive, 6 pgs down, 287 pgs peering, 48 pgs stale
            Degraded data redundancy: 5756984/22174447 objects degraded (25.962%), 91 pgs degraded, 84 pgs undersized
            13 daemons have recently crashed
            3 slow ops, oldest one blocked for 31 sec, daemons [mon.raspi4-8g-18,mon.raspi4-8g-20] have slow ops.

  services:
    mon: 5 daemons, quorum raspi4-8g-20,raspi4-8g-25,raspi4-8g-18,raspi4-8g-10,raspi4-4g-23 (age 2s)
    mgr: raspi4-8g-18.slyftn(active, since 3h), standbys: raspi4-8g-12.xuuxmp, raspi4-8g-10.udbcyy
    osd: 19 osds: 15 up (since 2h), 15 in (since 2h); 6 remapped pgs

  data:
    pools:   40 pools, 636 pgs
    objects: 4.28M objects, 4.9 TiB
    usage:   6.1 TiB used, 45 TiB / 51 TiB avail
    pgs:     56.918% pgs not active
             5756984/22174447 objects degraded (25.962%)
             2914/22174447 objects misplaced (0.013%)
             253 peering
             218 active+clean
             57  undersized+degraded+peered
             25  stale+peering
             20  stale+active+clean
             19  active+recovery_wait+undersized+degraded+remapped
             10  active+recovery_wait+degraded
             7   remapped+peering
             7   activating
             6   down
             2   active+undersized+remapped
             2   stale+remapped+peering
             2   undersized+remapped+peered
             2   activating+degraded
             1   active+remapped+backfill_wait
             1   active+recovering+undersized+degraded+remapped
             1   undersized+peered
             1   active+clean+scrubbing+deep
             1   active+undersized+degraded+remapped+backfill_wait
             1   stale+active+recovery_wait+undersized+degraded+remapped

  progress:
    Global Recovery Event (2h)
      [==========..................] (remaining: 4h)

'''
</code>```

答:
Some versions of BlueStore were susceptible to BlueFS log growing extremely large - beyond the point of making booting OSD impossible. This state is indicated by booting that takes very long and fails in _replay function.

This can be fixed by::
ceph-bluestore-tool fsck –path osd path –bluefs_replay_recovery=true

It is advised to first check if rescue process would be successful::
ceph-bluestore-tool fsck –path osd path –bluefs_replay_recovery=true –bluefs_replay_recovery_disable_compact=true

If above fsck is successful fix procedure can be applied

Special Thank you to, this has been solved with the help of a dewDrive Cloud backup faculty Member

Body:
Cephadm Pacific v16.2.7
Our Ceph cluster  is stuck pgs degraded and osd are down
Reason:- OSD's got filled up

Things we tried

Changed vale to to maximum possible combination (not sure if done right ?)
backfillfull < nearfull, nearfull < full, and full < failsafe_full

ceph-objectstore-tool - tried to delte some pgs to recover space

tried to mount osd and delete pg's to recover some space, but not sure how to do it in bluestore .

Global Recovery Event - stuck for ever

ceph -s

cluster:
    id:     a089a4b8-2691-11ec-849f-07cde9cd0b53
    health: HEALTH_WARN
            6 failed cephadm daemon(s)
            1 hosts fail cephadm check
            Reduced data availability: 362 pgs inactive, 6 pgs down, 287 pgs peering, 48 pgs stale
            Degraded data redundancy: 5756984/22174447 objects degraded (25.962%), 91 pgs degraded, 84 pgs undersized
            13 daemons have recently crashed
            3 slow ops, oldest one blocked for 31 sec, daemons [mon.raspi4-8g-18,mon.raspi4-8g-20] have slow ops.

  services:
    mon: 5 daemons, quorum raspi4-8g-20,raspi4-8g-25,raspi4-8g-18,raspi4-8g-10,raspi4-4g-23 (age 2s)
    mgr: raspi4-8g-18.slyftn(active, since 3h), standbys: raspi4-8g-12.xuuxmp, raspi4-8g-10.udbcyy
    osd: 19 osds: 15 up (since 2h), 15 in (since 2h); 6 remapped pgs

  data:
    pools:   40 pools, 636 pgs
    objects: 4.28M objects, 4.9 TiB
    usage:   6.1 TiB used, 45 TiB / 51 TiB avail
    pgs:     56.918% pgs not active
             5756984/22174447 objects degraded (25.962%)
             2914/22174447 objects misplaced (0.013%)
             253 peering
             218 active+clean
             57  undersized+degraded+peered
             25  stale+peering
             20  stale+active+clean
             19  active+recovery_wait+undersized+degraded+remapped
             10  active+recovery_wait+degraded
             7   remapped+peering
             7   activating
             6   down
             2   active+undersized+remapped
             2   stale+remapped+peering
             2   undersized+remapped+peered
             2   activating+degraded
             1   active+remapped+backfill_wait
             1   active+recovering+undersized+degraded+remapped
             1   undersized+peered
             1   active+clean+scrubbing+deep
             1   active+undersized+degraded+remapped+backfill_wait
             1   stale+active+recovery_wait+undersized+degraded+remapped

  progress:
    Global Recovery Event (2h)
      [==========..................] (remaining: 4h)

'''


问:
Python abstract classes - how to discourage instantiation?
I come from a C# background where the language has some built in "protect the developer" features.  I understand that Python takes the "we're all adults here" approach and puts responsibility on the developer to code thoughtfully and carefully.

That said, Python suggests conventions like a leading underscore for private instance variables.  My question is, is there a particular convention for marking a class as abstract other than just specifying it in the docstrings?  I haven't seen anything in particular in the python style guide that mentions naming conventions for abstract classes.

I can think of 3 options so far but I'm not sure if they're good ideas:

Specify it in the docstring above the class (might be overlooked)

Use a leading underscore in the class name (not sure if this is universally understood)

Create a def __init__(self): method on the abstract class that raises an error (not sure if this negatively impacts inheritance, like if you want to call a base constructor)

Is one of these a good option or is there a better one?  I just want to make sure that other developers know that it is abstract and so if they try to instantiate it they should accept responsibility for any strange behavior.

答:
In Python 3.x, your class can inherit from abc.ABC.
This will make your class non-instantiable and your IDE will warn you if you try to do so.

```<code>import abc

class SomeAbstractClass(abc.ABC):
    @abc.abstractmethod
    def some_abstract_method(self):
        raise NotImplementedError

    @property
    @abc.abstractmethod
    def some_abstract_property(self):
        raise NotImplementedError
</code>```

This has first been suggested in PEP 3119.

Body:
In Python 3.x, your class can inherit from abc.ABC.
This will make your class non-instantiable and your IDE will warn you if you try to do so.

import abc

class SomeAbstractClass(abc.ABC):
    @abc.abstractmethod
    def some_abstract_method(self):
        raise NotImplementedError

    @property
    @abc.abstractmethod
    def some_abstract_property(self):
        raise NotImplementedError

This has first been suggested in PEP 3119.


问:
AngularJS SPA edit button function
I'm new to AngularJS, currently I am trying to create a spa for tracking expenses as a simple project but I have some problems with my code.

I managed to do the most of the function but I got stuck at the edit button and edit function. I am trying to make an inline edit function because I already have a form input.

Here is the html and js code:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Expenses Tracker</title>
    <link rel="stylesheet" href="bootstrap.min.css">
    <link href="style.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-default navbar-fixed-top" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <span class="navbar-brand"><img src="logo.png" class="brand" height="40" />
                 Simple Expenses App Tracker</span>
            </div>
        </div>
    </nav>

    <div class="main" ng-app="myList" ng-controller="myListController">

        <img src="logo.png" class="logo">

    <form ng-submit="newItem()" class="form">
        <input required type="number" placeholder="Amount" ng-model="amount">
        <input required type="text" placeholder="Description" ng-model="description">
        <input type="submit" value="Submit" class="btn btn-success">
    </form>
        <ul>
            <li ng-repeat="item in items">
                <span  class="pull-left"> {{item.amount}} den.</span> {{item.description}}
                <span class="buttons">
                    <input type="button" value="Edit" class="btn btn-primary" >
                    <input type="button" ng-click="deleteItem($index)" value="Delete" class="btn btn-danger">
                </span>
            </li>
            <br>
            <li><span class="total">{{totalPrice()}} den.</span> <span class="expense"> Total Expenses</span></li>
        </ul>

    </div>

    <script src="bootstrap.min.js"></script>
    <script src="angular.min.js"></script>
    <script src="angular-route.min.js"></script>
    <script src="app.js"></script>
</body>
</html>
</code>```
```<code>var myApp = angular.module("myList", []);

myApp.controller("myListController", function($scope) {
    $scope.items = [];

    $scope.newItem = function() {
        $scope.items.push({description:$scope.description, amount: $scope.amount});
        $scope.description = '';
        $scope.amount = 0
    };

    $scope.deleteItem = function(index) {
        $scope.items.splice(index, 1);
    }

    $scope.totalPrice = function() {
        var total = 0;
        for(count=0; count<$scope.items.length;count++){
            total += $scope.items[count].amount;
        }
        return total;
    };

});

</code>```

答:
You could try something like:

$scope.editItem = function(index) {
    $scope.amount = $scope.items[index].amount;
    $scope.description = $scope.items[index].description;
    $scope.deleteItem(index);
}
```

I also recommend you read this book:
https://www.newline.co/ng-book/modern-ng1/

Try to move away from using $scope for bindings and user components. Unless you really don't care where this project goes.

Title: AngularJS SPA edit button function

Body:
I'm new to AngularJS, currently I am trying to create a spa for tracking expenses as a simple project but I have some problems with my code.

I managed to do the most of the function but I got stuck at the edit button and edit function. I am trying to make an inline edit function because I already have a form input.

Here is the html and js code:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Expenses Tracker</title>
    <link rel="stylesheet" href="bootstrap.min.css">
    <link href="style.css" rel="stylesheet">

                 Simple Expenses App Tracker

    <form ng-submit="newItem()" class="form">
        <input required type="number" placeholder="Amount" ng-model="amount">
        <input required type="text" placeholder="Description" ng-model="description">
        <input type="submit" value="Submit" class="btn btn-success">
    </form>

                 {{item.amount}} den. {{item.description}}

                    <input type="button" value="Edit" class="btn btn-primary" >
                    <input type="button" ng-click="deleteItem($index)" value="Delete" class="btn btn-danger">

{{totalPrice()}} den.  Total Expenses

var myApp = angular.module("myList", []);

myApp.controller("myListController", function($scope) {
    $scope.items = [];

    $scope.newItem = function() {
        $scope.items.push({description:$scope.description, amount: $scope.amount});
        $scope.description = '';
        $scope.amount = 0
    };

    $scope.deleteItem = function(index) {
        $scope.items.splice(index, 1);
    }

    $scope.totalPrice = function() {
        var total = 0;
        for(count=0; count<$scope.items.length;count++){
            total += $scope.items[count].amount;
        }
        return total;
    };

});

Body:
You could try something like:

$scope.editItem = function(index) {
    $scope.amount = $scope.items[index].amount;
    $scope.description = $scope.items[index].description;
    $scope.deleteItem(index);
}

I also recommend you read this book:
https://www.newline.co/ng-book/modern-ng1/

Try to move away from using $scope for bindings and user components. Unless you really don't care where this project goes.


问:
Perl: How to test if any value (even zero) has been assigned to a hash key
Is there a correct way of testing if a particular hash key has already been assigned any value, even if this value is zero? I have been working with a statement like this:

```<code>%hash=();
$hash{a}=1;
$hash{b}=0;
if($hash{$key}) { do something }
</code>```

but this gives the same result for keys that have neven been touched and those that have been assigned the value 0 (e.g. both $hash{b} and $hash{c} evaluate as 'false'). Is there a way of telling the difference between those two ?

答:
You can use defined() to check if the key actually exists in the hash:

```<code>if (defined($hash{$key})) { do('something'); };
</code>```

Body:
Is there a correct way of testing if a particular hash key has already been assigned any value, even if this value is zero? I have been working with a statement like this:

%hash=();
$hash{a}=1;
$hash{b}=0;
if($hash{$key}) { do something }

but this gives the same result for keys that have neven been touched and those that have been assigned the value 0 (e.g. both $hash{b} and $hash{c} evaluate as 'false'). Is there a way of telling the difference between those two ?

Body:
You can use defined() to check if the key actually exists in the hash:

if (defined($hash{$key})) { do('something'); };


问:
Add column value in panda data frame if certain condition is met
I have two lists:

```<code>    required=["api.gotinder.com","data.gotinder.com"]
    not_required=["graph.facebook.com","launches.appsflyer.com"]

</code>```

If the value in requested_server_name column is in required list then it should be labeled as Required if the value in requested_server_name column is in not_required list then it should be labeled as Not_Required

What I am doing at the moment:

```<code>for j in required:
    conditions = [
        (frame['requested_server_name'] == j)
        ]
    values = ["Required"]
    frame['label'] = np.select(conditions, values)

for k in not_required:
    conditions = [
        (frame['requested_server_name'] == k)
        ]
    values = ["Not_Required"]
    frame['label'] = np.select(conditions, values)
</code>```

What am I doing wrong?? It only populates the label for launches.appsflyer.com.

答:
Create a dict then reverse keys and values to create a mapping dict. Finally use replace to apply the mapping:

```<code>d = {'required': ["api.gotinder.com", "data.gotinder.com"],
     'not_required': ["graph.facebook.com", "launches.appsflyer.com"]}

MAP = {v: k for k, l in d.items() for v in l}

frame['label'] = frame['requested_server_name'].replace(MAP)
</code>```

Body:
I have two lists:

    required=["api.gotinder.com","data.gotinder.com"]
    not_required=["graph.facebook.com","launches.appsflyer.com"]

If the value in requested_server_name column is in required list then it should be labeled as Required if the value in requested_server_name column is in not_required list then it should be labeled as Not_Required

What I am doing at the moment:

for j in required:
    conditions = [
        (frame['requested_server_name'] == j)
        ]
    values = ["Required"]
    frame['label'] = np.select(conditions, values)

for k in not_required:
    conditions = [
        (frame['requested_server_name'] == k)
        ]
    values = ["Not_Required"]
    frame['label'] = np.select(conditions, values)

What am I doing wrong?? It only populates the label for launches.appsflyer.com.

Body:
Create a dict then reverse keys and values to create a mapping dict. Finally use replace to apply the mapping:

d = {'required': ["api.gotinder.com", "data.gotinder.com"],
     'not_required': ["graph.facebook.com", "launches.appsflyer.com"]}

MAP = {v: k for k, l in d.items() for v in l}

frame['label'] = frame['requested_server_name'].replace(MAP)


问:
Implementing Postgres Sql in Apache Airflow
I have Apache-Airflow implemented on an Ubuntu version 18.04.3 server. When I set it up, I used the sql lite generic database, and this uses the sequential executor. I did this just to play around and get used to the system. Now I'm trying to use the Local Executor, and will need to transition my database from sqlite to the recommended postgres sql. </p>

<p>Does anybody know how to make this transition? All of the tutorials I've found entail setting up Airflow with postgres sql from the beginning. I know there are a ton of moving parts and I'm scared of messsing up what I currently have running. Anybody who knows how to do this or can point me at where to look is much appreciated. Thanks!   </p>

答:
Another option other than adding to the airflow.cfg file

is to set the ENV varibale AIRFLOW__CORE__SQL_ALCHEMY_CONN to the postgresql server you want.

Example: export AIRFLOW__CORE__SQL_ALCHEMY_CONN_SECRET=sql_alchemy_conn

Or you can set it in your Dockerfile setting.

See documentation here

Body:
I have Apache-Airflow implemented on an Ubuntu version 18.04.3 server. When I set it up, I used the sql lite generic database, and this uses the sequential executor. I did this just to play around and get used to the system. Now I'm trying to use the Local Executor, and will need to transition my database from sqlite to the recommended postgres sql.

Does anybody know how to make this transition? All of the tutorials I've found entail setting up Airflow with postgres sql from the beginning. I know there are a ton of moving parts and I'm scared of messsing up what I currently have running. Anybody who knows how to do this or can point me at where to look is much appreciated. Thanks!


问:
Google Sheets <> Coinmarket cap API dynamic sheet
)

What I would like to do is extend this piece of code to make it less hard coded but dynamic. It maybe easier to hard code the coinmarketcap api key.

I would like to do the following in google sheets (its not allowing me to pass argument in function and debug it so I dont know what is happening, its coming back undefined)

name
price

BTC
41665

ADA
1.9

I would like to pass the name of the coin and return the price, so the function would be =getcryptoprice(name)

Any help would be greatly appreciated.

```<code>function getCryptoPrice() {
  var sh1=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");
  var sh2=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");

  //Make sure that you got the API key from Coinmarketcap API dashboard and paste it in sheet_1 on cell A1
  var apiKey=sh1.getRange(1, 1).getValue();

  var url="https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC"
  var requestOptions = {
  method: 'GET',
  uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
  qs: {
    start: 1,
    limit: 5000,
    convert: 'USD'
  },
  headers: {
    'X-CMC_PRO_API_KEY': apiKey
  },
  json: true,
  gzip: true
};

  var httpRequest= UrlFetchApp.fetch(url, requestOptions);
  var getContext= httpRequest.getContentText();

  var parseData=JSON.parse(getContext);
  sh2.getRange(1, 2).setValue(parseData.data.BTC.quote.USD.price)
</code>```

答:
You can change parseData.data.BTC.quote.USD.price to parseData.data[code].quote.USD.price with code = BTC

Try this : =getCryptoPrice("BTC")

```<code>function getCryptoPrice(code) {
  var sh1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");
  var sh2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");

  //Make sure that you got the API key from Coinmarketcap API dashboard and paste it in sheet_1 on cell A1
  var apiKey = sh1.getRange(1, 1).getValue();

  var url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol="+code
  var requestOptions = {
    method: 'GET',
    uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
    qs: {
      start: 1,
      limit: 5000,
      convert: 'USD'
    },
    headers: {
      'X-CMC_PRO_API_KEY': apiKey
    },
    json: true,
    gzip: true
  };

  var httpRequest = UrlFetchApp.fetch(url, requestOptions);
  var getContext = httpRequest.getContentText();

  var parseData = JSON.parse(getContext);
  return(parseData.data[code].quote.USD.price)

}
</code>```

edit : to refresh

method #1
you can refresh values by adding a dummy parameter as a checkbox in A1 for instance and include in the second argument of the function as =getCryptoPrice("BTC",$A$1)

then, define a trigger (each hour) in this custom function

```<code>function refresh(){
  var chk = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange('A1')
  chk.setValue(!chk.getValue())
}
</code>```

method #2
same formula =getCryptoPrice("BTC",$A$1) with =now() in A1. Then go to settings for the spreadsheet, calculation tab, choose recalculation on change and every hour

Body:
)

What I would like to do is extend this piece of code to make it less hard coded but dynamic. It maybe easier to hard code the coinmarketcap api key.

I would like to do the following in google sheets (its not allowing me to pass argument in function and debug it so I dont know what is happening, its coming back undefined)

name
price

BTC
41665

ADA
1.9

I would like to pass the name of the coin and return the price, so the function would be =getcryptoprice(name)

Any help would be greatly appreciated.

function getCryptoPrice() {
  var sh1=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");
  var sh2=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");

  //Make sure that you got the API key from Coinmarketcap API dashboard and paste it in sheet_1 on cell A1
  var apiKey=sh1.getRange(1, 1).getValue();

  var url="https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC"
  var requestOptions = {
  method: 'GET',
  uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
  qs: {
    start: 1,
    limit: 5000,
    convert: 'USD'
  },
  headers: {
    'X-CMC_PRO_API_KEY': apiKey
  },
  json: true,
  gzip: true
};

  var httpRequest= UrlFetchApp.fetch(url, requestOptions);
  var getContext= httpRequest.getContentText();

  var parseData=JSON.parse(getContext);
  sh2.getRange(1, 2).setValue(parseData.data.BTC.quote.USD.price)

Body:
You can change parseData.data.BTC.quote.USD.price to parseData.data[code].quote.USD.price with code = BTC

Try this : =getCryptoPrice("BTC")

function getCryptoPrice(code) {
  var sh1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");
  var sh2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");

  //Make sure that you got the API key from Coinmarketcap API dashboard and paste it in sheet_1 on cell A1
  var apiKey = sh1.getRange(1, 1).getValue();

  var url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol="+code
  var requestOptions = {
    method: 'GET',
    uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
    qs: {
      start: 1,
      limit: 5000,
      convert: 'USD'
    },
    headers: {
      'X-CMC_PRO_API_KEY': apiKey
    },
    json: true,
    gzip: true
  };

  var httpRequest = UrlFetchApp.fetch(url, requestOptions);
  var getContext = httpRequest.getContentText();

  var parseData = JSON.parse(getContext);
  return(parseData.data[code].quote.USD.price)

}

edit : to refresh

method #1
you can refresh values by adding a dummy parameter as a checkbox in A1 for instance and include in the second argument of the function as =getCryptoPrice("BTC",$A$1)

then, define a trigger (each hour) in this custom function

function refresh(){
  var chk = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange('A1')
  chk.setValue(!chk.getValue())
}

method #2
same formula =getCryptoPrice("BTC",$A$1) with =now() in A1. Then go to settings for the spreadsheet, calculation tab, choose recalculation on change and every hour


问:
Extracting filesnames in bash with regex
Can please someone help me to set up a regular expression.

I have a large LaTeX3 TeXDoc file.  LaTeX3 TeXDoc defines the macro \TestFiles{}, which should be used, to list the names of files, which itself should be used as an unit tests.  You can name more than one file between the braces.  So \TestFiles{foo-bar} and \TestFiles{foo-bar, bar+baz,foo_bar_baz} are syntactical correct use cases for this macro.

I would like to write a bash script, to extract all the uni test files, named in the \TestFiles{} macros, to compile them with pdflatex and check, if pdflatex will be able to produce an output file successfully.

I have something like this in my script:

function get_filenames () {
  ## This regex works but is not sensible enough
  # regex='\\TestFiles{(.*)}'
  ## This works also, but is again not precise enough
  regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
  ## This should give more than one matching group
  ## (separated by ", " or ","), but this regex doesn't
  ## work.  I have no idea why or how to modify, to get
  ## it working

  while read -r line ; do
    if [[ $line =~ $regex ]] ; then
      i=1
        while [ $i -le 3 ]; do
          echo "Match $i: \"${BASH_REMATCH[$i]}\""
          i=$(( i + 1 ))
        done
      echo
    fi
  done < mystyle.dtx
}
```
<p>Here is an excerpt of the DTX file</p>
<pre class="lang-latex prettyprint-override"><code>\TestFiles{foo-bar}

\TestFiles{foo-bar, bar+baz,foo_bar_baz}
</code>```

(You can store this as mystyle.dtx, in order to reproduce the next example.)

Using the above noted examples, my script gives me the following results:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar, bar+baz,foo_bar_baz"
Match 2: ""
Match 3: ""

```
<p>I wasn't able, to modify my <code>regex</code> expression, to split the content of the last <code>\TestFiles{foo-bar, bar+baz,foo_bar_baz}</code> example into three matching results.</p>
<p>I tried a regular expression like this <code>regex='\\TestFiles{([[:alnum:]+-_]*)[,]+[ ]*}'</code>.  I thought the <code>[:alnum:]+-_]*</code> would match the filenames.  As far as I understand regular expressions, the <code>(...)</code> should form a group, that should be listed afterwards in the bash array <code>BASH_REMATCH[$i]</code>.</p>
<p>The part <code>[,]+</code> should reflect that every file name must be separated by at least one comma.  Between the filenames there might be some white space, so something like <code>[[:space:]]*</code> or at least <code>[ ]*</code> should represent this.  The quantifier <code>*</code> means any repetition, ranging from 0 to ..., while <code>+</code> should at least appear one or more times.</p>
<p>But that regular expression did not work at all, if had no matching results.</p>
<p>How must <code>regex</code> be defined, to store each filenames as a matching group?  I am searching for the correct regular expression, to get this result:</p>
<pre class="lang-sh prettyprint-override"><code>get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar"
Match 2: "bar+baz"
Match 3: "foo_bar_baz"

</code>```

EDIT: in my real world files, there may be (and are) more than tree test files.

Thanks in advance.

答:
```<code>## This should give more than one matching group
regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
</code>```

The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.

Your regex only has 1 "parenthesized subexpression" - which is why everything ends up in BASH_REMATCH[1]

```<code>$ regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
$ [[ $line =~ $regex ]]
$ declare -p BASH_REMATCH
declare -a BASH_REMATCH=(
    [0]="\\TestFiles{foo-bar, bar+baz,foo_bar_baz}"
    [1]="foo-bar, bar+baz,foo_bar_baz"
)
</code>```

As you're trying to match an unknown number of filenames you would have to "dynamically" create your regex so it contains the needed amount of groups.

```<code>$ regex='\\TestFiles{([^, }]+)([,}] ?)'
$ [[ $line =~ $regex ]]
$ declare -p BASH_REMATCH
declare -a BASH_REMATCH=(
    [0]="\\TestFiles{foo-bar, "
    [1]="foo-bar"
    [2]=", "
)
</code>```

Add another group and see if it still matches:

```<code>$ regex+='([^, }]+)([,}] ?)'
$ [[ $line =~ $regex ]]
$ declare -p BASH_REMATCH
declare -a BASH_REMATCH=(
    [0]="\\TestFiles{foo-bar, bar+baz,"
    [1]="foo-bar"
    [2]=", "
    [3]="bar+baz"
    [4]=","
)
</code>```

You could keep looping until the regex no longer matches - or perhaps a simpler approach would be to count the number of , characters on the line.

```<code>regex='\\TestFiles{([^, }]+)([,}] ?)'
line='\TestFiles{foo-bar, bar+baz,foo_bar_baz}'
commas=${line//[!,]}

for ((i=0; i<${#commas}; i++))
do
    regex+='([^, }]+)([,}] ?)'
done

[[ $line =~ $regex ]]
</code>```

Which results in:

```<code>$ declare -p BASH_REMATCH
declare -a BASH_REMATCH=(
    [0]="\\TestFiles{foo-bar, bar+baz,foo_bar_baz}"
    [1]="foo-bar"
    [2]=", "
    [3]="bar+baz"
    [4]=","
    [5]="foo_bar_baz"
    [6]="}"
)
</code>```

Alternative approach using IFS

You can set IFS=', ' and have bash do the splitting for you.

```<code>line='\TestFiles{foo-bar, bar+baz,foo_bar_baz}'

[[ $line = \\TestFiles{* ]] && {
    # Remove leading '\Testfiles{'
    # Remove trailing }
    line=${line#*{}
    line=${line%}}

    IFS=', ' read -a filenames <<< "$line"

    declare -p filenames
}
</code>```
```<code>declare -a filenames=([0]="foo-bar" [1]="bar+baz" [2]="foo_bar_baz}}")
</code>```

Body:
Can please someone help me to set up a regular expression.

I have a large LaTeX3 TeXDoc file.  LaTeX3 TeXDoc defines the macro \TestFiles{}, which should be used, to list the names of files, which itself should be used as an unit tests.  You can name more than one file between the braces.  So \TestFiles{foo-bar} and \TestFiles{foo-bar, bar+baz,foo_bar_baz} are syntactical correct use cases for this macro.

I would like to write a bash script, to extract all the uni test files, named in the \TestFiles{} macros, to compile them with pdflatex and check, if pdflatex will be able to produce an output file successfully.

I have something like this in my script:

function get_filenames () {
  ## This regex works but is not sensible enough
  # regex='\\TestFiles{(.*)}'
  ## This works also, but is again not precise enough
  regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
  ## This should give more than one matching group
  ## (separated by ", " or ","), but this regex doesn't
  ## work.  I have no idea why or how to modify, to get
  ## it working

  while read -r line ; do
    if [[ $line =~ $regex ]] ; then
      i=1
        while [ $i -le 3 ]; do
          echo "Match $i: \"${BASH_REMATCH[$i]}\""
          i=$(( i + 1 ))
        done
      echo
    fi
  done < mystyle.dtx
}

Here is an excerpt of the DTX file

\TestFiles{foo-bar}

\TestFiles{foo-bar, bar+baz,foo_bar_baz}

(You can store this as mystyle.dtx, in order to reproduce the next example.)

Using the above noted examples, my script gives me the following results:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar, bar+baz,foo_bar_baz"
Match 2: ""
Match 3: ""

I wasn't able, to modify my regex expression, to split the content of the last \TestFiles{foo-bar, bar+baz,foo_bar_baz} example into three matching results.

I tried a regular expression like this regex='\\TestFiles{([[:alnum:]+-_]*)[,]+[ ]*}'.  I thought the [:alnum:]+-_]* would match the filenames.  As far as I understand regular expressions, the (...) should form a group, that should be listed afterwards in the bash array BASH_REMATCH[$i].

The part [,]+ should reflect that every file name must be separated by at least one comma.  Between the filenames there might be some white space, so something like [[:space:]]* or at least [ ]* should represent this.  The quantifier * means any repetition, ranging from 0 to ..., while + should at least appear one or more times.

But that regular expression did not work at all, if had no matching results.

How must regex be defined, to store each filenames as a matching group?  I am searching for the correct regular expression, to get this result:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar"
Match 2: "bar+baz"
Match 3: "foo_bar_baz"

EDIT: in my real world files, there may be (and are) more than tree test files.

Thanks in advance.

Body:
## This should give more than one matching group
regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'

The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.

Your regex only has 1 "parenthesized subexpression" - which is why everything ends up in BASH_REMATCH[1]

$ regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
$ [[ $line =~ $regex ]]
$ declare -p BASH_REMATCH
declare -a BASH_REMATCH=(
    [0]="\\TestFiles{foo-bar, bar+baz,foo_bar_baz}"
    [1]="foo-bar, bar+baz,foo_bar_baz"
)

As you're trying to match an unknown number of filenames you would have to "dynamically" create your regex so it contains the needed amount of groups.

$ regex='\\TestFiles{([^, }]+)([,}] ?)'
$ [[ $line =~ $regex ]]
$ declare -p BASH_REMATCH
declare -a BASH_REMATCH=(
    [0]="\\TestFiles{foo-bar, "
    [1]="foo-bar"
    [2]=", "
)

Add another group and see if it still matches:

$ regex+='([^, }]+)([,}] ?)'
$ [[ $line =~ $regex ]]
$ declare -p BASH_REMATCH
declare -a BASH_REMATCH=(
    [0]="\\TestFiles{foo-bar, bar+baz,"
    [1]="foo-bar"
    [2]=", "
    [3]="bar+baz"
    [4]=","
)

You could keep looping until the regex no longer matches - or perhaps a simpler approach would be to count the number of , characters on the line.

regex='\\TestFiles{([^, }]+)([,}] ?)'
line='\TestFiles{foo-bar, bar+baz,foo_bar_baz}'
commas=${line//[!,]}

for ((i=0; i<${#commas}; i++))
do
    regex+='([^, }]+)([,}] ?)'
done

[[ $line =~ $regex ]]

Which results in:

$ declare -p BASH_REMATCH
declare -a BASH_REMATCH=(
    [0]="\\TestFiles{foo-bar, bar+baz,foo_bar_baz}"
    [1]="foo-bar"
    [2]=", "
    [3]="bar+baz"
    [4]=","
    [5]="foo_bar_baz"
    [6]="}"
)

Alternative approach using IFS

You can set IFS=', ' and have bash do the splitting for you.

line='\TestFiles{foo-bar, bar+baz,foo_bar_baz}'

[[ $line = \\TestFiles{* ]] && {
    # Remove leading '\Testfiles{'
    # Remove trailing }
    line=${line#*{}
    line=${line%}}

    IFS=', ' read -a filenames <<< "$line"

    declare -p filenames
}

declare -a filenames=([0]="foo-bar" [1]="bar+baz" [2]="foo_bar_baz}}")


问:
Fetch multiple twitter users timeline for no-authenticate account
Is there a way for no-authenticate user to managed his own list (in code) say I have a list of user screen name, is there any api that can I pass the list of users and return timeline for those users ? I have look into https://dev.twitter.com/docs/api/1/get/statuses/user_timeline but multiple user is not supported and in this post Combining multiple Twitter user timelines into one request they said about list and bot account, but from my understanding twitter limited 20 lists fro 1 account, so this seem not practical for > 20 users based app.  </p>

答:
The list idea is just fine. You don't have to create new list to every user in your app. Add unique users you want to follow to non-full list (1 list can have up to 500 members) or create new list. Then poll all your lists few times an hour - then just sort out which screen_names to show to which your users.

I have managed to collect the statuses of ~55000 twitter users by using only 6 bot accounts.


问:
Mongoose - How to require two Schema files from eachother without circular dependency error?
In my Node.js project, I have two schemas, ProductSchema and ReviewSchema. They are located in different files. In Product.js (which contains the ProductSchema), I have a .pre remove hook, that removes all the reviews associated with the product. For this to work, I have to require Review.js (which contains the ReviewSchema). So far so good, but I wanted to implement a hook in the ReviewSchema to fire a review's been created/edited/deleted to update the product's avarageRating field. For this, I referenced Review.js, thus creating a circular dependency error between Review.js and Product.js.

// Product.js

```<code>const Review = require("./Review");

[...]

ProductSchema.pre("remove", function (next) {
    // ...remove all Reviews that reference it ...
    Review.deleteMany({ product: this._id });
    next();
});

module.exports = new mongoose.model("Product", ProductSchema);
</code>```

// Review.js

```<code>const Product = require("./Product");

[...]

ReviewSchema.post("save", async function () {
  const reviewsAboutProduct = await Review.find({ product: this.product });

  const total = reviewsAboutProduct.reduce((prevValue, review) => {
    return prevValue + review.rating;
  }, 0);

  const averageRating = total / reviewsAboutProduct.length;
  console.log(total, averageRating);
// below is the line referenced in the response error message
  const product = Product.findOne({_id: product});
  product.averageRating = averageRating;
  product.save();
});

const Review = mongoose.model("Review", ReviewSchema);
module.exports = Review;
</code>```

I think because of this circular dependency, I get the following error:

```<code>(node:8696) Warning: Accessing non-existent property 'findOne' of module exports inside circular dependency
</code>```

And in the response:

```<code>```ReferenceError: Cannot access 'product' before initialization
    at model.<anonymous> (\models\Review.js:47:42)
```

What should I do? Thank you for your time and help.

答:
This solution suggested by vicki helped me to solve this problem.

Review.js file:

```<code>const Review = mongoose.model("Review", ReviewSchema);
module.exports = Review;
const Product = require("./Product");
</code>```

Product.js file:

```<code>module.exports = new mongoose.model("Product", ProductSchema);
const Review = require("./Review");
</code>```

Body:
In my Node.js project, I have two schemas, ProductSchema and ReviewSchema. They are located in different files. In Product.js (which contains the ProductSchema), I have a .pre remove hook, that removes all the reviews associated with the product. For this to work, I have to require Review.js (which contains the ReviewSchema). So far so good, but I wanted to implement a hook in the ReviewSchema to fire a review's been created/edited/deleted to update the product's avarageRating field. For this, I referenced Review.js, thus creating a circular dependency error between Review.js and Product.js.

// Product.js

const Review = require("./Review");

[...]

ProductSchema.pre("remove", function (next) {
    // ...remove all Reviews that reference it ...
    Review.deleteMany({ product: this._id });
    next();
});

module.exports = new mongoose.model("Product", ProductSchema);

// Review.js

const Product = require("./Product");

[...]

ReviewSchema.post("save", async function () {
  const reviewsAboutProduct = await Review.find({ product: this.product });

  const total = reviewsAboutProduct.reduce((prevValue, review) => {
    return prevValue + review.rating;
  }, 0);

  const averageRating = total / reviewsAboutProduct.length;
  console.log(total, averageRating);
// below is the line referenced in the response error message
  const product = Product.findOne({_id: product});
  product.averageRating = averageRating;
  product.save();
});

const Review = mongoose.model("Review", ReviewSchema);
module.exports = Review;

I think because of this circular dependency, I get the following error:

(node:8696) Warning: Accessing non-existent property 'findOne' of module exports inside circular dependency

And in the response:

ReferenceError: Cannot access 'product' before initialization
    at model.<anonymous> (\models\Review.js:47:42)

What should I do? Thank you for your time and help.

Body:
This solution suggested by vicki helped me to solve this problem.

Review.js file:

const Review = mongoose.model("Review", ReviewSchema);
module.exports = Review;
const Product = require("./Product");

Product.js file:

module.exports = new mongoose.model("Product", ProductSchema);
const Review = require("./Review");


问:
Firebase serve error: Port 5000 is not open. Could not start functions emulator
I'm trying to serve firebase functions locally, but when I run firebase serve or firebase emulators:start the error message is: "Port 5000 is not open, could not start functions emulator."

I'm using Windows 10, so I've tried to change the port number, check if the port is blocked by Firewall and I create a new rule in Firewall to ports 5000-5010 but none of this approaches worked for me.

答:
Port 5000 and 7000 are taken by airplay on MacOS Monterey.

Switch off Airplay Receiver as suggested here or

update firebase.json with a different port

```<code>"emulators": {

    "hosting": {
      "port": 5004
    }
}
</code>```

Body:
Port 5000 and 7000 are taken by airplay on MacOS Monterey.

Switch off Airplay Receiver as suggested here or

update firebase.json with a different port

"emulators": {

    "hosting": {
      "port": 5004
    }
}


问:
How to access my json data from API using c# xamarin
I try to receive my data from my API point, but everytime I receive message:

```<code>    result  Id = 1, Status = WaitingForActivation, Method = {null}
</code>```

This is my ResService_HQ_AHS class:

```<code>using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using HydroMeteoAnalyzer.Models.API;
using Newtonsoft.Json;

namespace HydroMeteoAnalyzer.Services
{
    public class RestService_HQ_AHS
    {
        HttpClient _client;

        public RestService_HQ_AHS()
        {
            _client = new HttpClient();
        }

        public async Task<HQ_AHS> Get_HQ_AHS(string query)
        {
            HQ_AHS HQ_Data = new HQ_AHS();

            try
            {
                var response = await _client.GetAsync(query);
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    HQ_Data = JsonConvert.DeserializeObject<HQ_AHS>(content);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\t\tERROR {0}", ex.Message);
            }

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

Here is the object from json:

```<code>using System;
namespace HydroMeteoAnalyzer.Models.API
{
    public class HQ_AHS
    {
        public int Station { get; set; }
        public string Ime { get; set; }
    }
}
</code>```

Here is my Constants class with API EndPoint:

```<code>using System;
namespace HydroMeteoAnalyzer.Models.API
{
    public class Constants
    {
        public static string EndPoint = "http://194.141.118.43/api/stations";
    }
}
</code>```

Here is my page which I try to receive the data from Json file:

```<code>    using System;
using System.Collections.Generic;
using HydroMeteoAnalyzer.Models.API;
using HydroMeteoAnalyzer.Services;
using Xamarin.Forms;

namespace HydroMeteoAnalyzer.Models.Hydro
{
    public partial class HQ_AHS : ContentPage
    {
        RestService_HQ_AHS  _restServiceStations;
        public HQ_AHS ()
        {
            InitializeComponent ();
            _restServiceStations = new RestService_HQ_AHS();
            CheckStation_HQ_AHS();
        }

        string GenerateRequestUriStations(string endpoint)
        {
            string requestUri = endpoint;
            requestUri += $"stations";

            return requestUri;
        }

        public void CheckStation_HQ_AHS()
        {
            var result = _restServiceStations.Get_HQ_AHS(Constants.EndPoint);

            var test = result;
        }
    }
}
</code>```

Everytime I receive null on my test and receive message:result  Id = 1, Status = WaitingForActivation, Method = {null}  and In the RestService_HQ_AHS cannot enter in the If statement..

This is the API point: http://194.141.118.43/api/stations

What do I need to change to get my data from the API ?

答:
The problem is that you're not awaiting the response from Get_HQ_AHS.  This needs to be awaited in the CheckStation_HQ_AHS method.  Update the signature to async Task too (async void should generally be avoided):

```<code>public async Task CheckStation_HQ_AHS()
{
    var result = await _restServiceStations.Get_HQ_AHS(Constants.EndPoint);
    ...
}
</code>```

Additionally, the json response is a list/array of type List<HQ_AHS>, so you should try deserializing using:

```<code>var content = await response.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<List<HQ_AHS>>(content);
//                       deserialize to list here ^^^
</code>```

You haven't shown HQ_Data so not sure how the response maps to that class, but you should be able to deserialize using the above code.

Body:
I try to receive my data from my API point, but everytime I receive message:

    result  Id = 1, Status = WaitingForActivation, Method = {null}

This is my ResService_HQ_AHS class:

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using HydroMeteoAnalyzer.Models.API;
using Newtonsoft.Json;

namespace HydroMeteoAnalyzer.Services
{
    public class RestService_HQ_AHS
    {
        HttpClient _client;

        public RestService_HQ_AHS()
        {
            _client = new HttpClient();
        }

        public async Task<HQ_AHS> Get_HQ_AHS(string query)
        {
            HQ_AHS HQ_Data = new HQ_AHS();

            try
            {
                var response = await _client.GetAsync(query);
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    HQ_Data = JsonConvert.DeserializeObject<HQ_AHS>(content);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\t\tERROR {0}", ex.Message);
            }

            return HQ_Data;
        }
    }
}

Here is the object from json:

using System;
namespace HydroMeteoAnalyzer.Models.API
{
    public class HQ_AHS
    {
        public int Station { get; set; }
        public string Ime { get; set; }
    }
}

Here is my Constants class with API EndPoint:

using System;
namespace HydroMeteoAnalyzer.Models.API
{
    public class Constants
    {
        public static string EndPoint = "http://194.141.118.43/api/stations";
    }
}

Here is my page which I try to receive the data from Json file:

    using System;
using System.Collections.Generic;
using HydroMeteoAnalyzer.Models.API;
using HydroMeteoAnalyzer.Services;
using Xamarin.Forms;

namespace HydroMeteoAnalyzer.Models.Hydro
{
    public partial class HQ_AHS : ContentPage
    {
        RestService_HQ_AHS  _restServiceStations;
        public HQ_AHS ()
        {
            InitializeComponent ();
            _restServiceStations = new RestService_HQ_AHS();
            CheckStation_HQ_AHS();
        }

        string GenerateRequestUriStations(string endpoint)
        {
            string requestUri = endpoint;
            requestUri += $"stations";

            return requestUri;
        }

        public void CheckStation_HQ_AHS()
        {
            var result = _restServiceStations.Get_HQ_AHS(Constants.EndPoint);

            var test = result;
        }
    }
}

Everytime I receive null on my test and receive message:result  Id = 1, Status = WaitingForActivation, Method = {null}  and In the RestService_HQ_AHS cannot enter in the If statement..

This is the API point: http://194.141.118.43/api/stations

What do I need to change to get my data from the API ?

Body:
The problem is that you're not awaiting the response from Get_HQ_AHS.  This needs to be awaited in the CheckStation_HQ_AHS method.  Update the signature to async Task too (async void should generally be avoided):

public async Task CheckStation_HQ_AHS()
{
    var result = await _restServiceStations.Get_HQ_AHS(Constants.EndPoint);
    ...
}

Additionally, the json response is a list/array of type List<HQ_AHS>, so you should try deserializing using:

var content = await response.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<List<HQ_AHS>>(content);
//                       deserialize to list here ^^^

You haven't shown HQ_Data so not sure how the response maps to that class, but you should be able to deserialize using the above code.


问:
Basic Inheritance in Java
I'm currently learning and working on an exercise for class. I'm able to get a printout that resembles what I need, but the data isn't populating with test inputs. Name comes back null, Age: 0 and ID: 0.

Here's the scenario:

Assign courseStudent's name with Smith, age with 20, and ID with 9999. Use the printAll member method and a separate println statement to output courseStudents's data. Sample output from the given program:

Name: Smith, Age: 20, ID: 9999

// ===== Code from file PersonData.java =====
public class PersonData {
   private int ageYears;
   private String lastName;

   public void setName(String userName) {
      lastName  = userName;
   }

   public void setAge(int numYears) {
      ageYears = numYears;
   }

   // Other parts omitted

   public void printAll() {
      System.out.print("Name: " + lastName);
      System.out.print(", Age: "  + ageYears);
   }
}
// ===== end =====

// ===== Code from file StudentData.java =====
public class StudentData extends PersonData {
   private int idNum;

   public void setID(int studentId) {
      idNum = studentId;
   }

   public int getID() {
      return idNum;
   }
}
// ===== end =====

// ===== Code from file StudentDerivationFromPerson.java =====
public class StudentDerivationFromPerson {
   public static void main (String [] args) {
      StudentData courseStudent = new StudentData();

      courseStudent.printAll();
      System.out.println(", ID: " + courseStudent.getID());

   }
}
// ===== end =====
```
<p>I'm sure that I'm overlooking something simple, but I'm not sure what. My code is the just the last few lines:</p>
<pre class="lang-java prettyprint-override"><code>courseStudent.printAll();
System.out.println(", ID: " + courseStudent.getID());
</code>```

答:
You need to add set values so you don’t get null and 0 as output.
The correct answer is:</p>
```<code>courseStudent.setID(9999);
courseStudent.setName(“Smith”);
courseStudent.setAge(20);
courseStudent.printAll();
System.out.print(“, ID: “ + courseStudent.getID());
System.out.println(“”);
</code>```

Title: Basic Inheritance in Java

Body:
I'm currently learning and working on an exercise for class. I'm able to get a printout that resembles what I need, but the data isn't populating with test inputs. Name comes back null, Age: 0 and ID: 0.

Here's the scenario:

Assign courseStudent's name with Smith, age with 20, and ID with 9999. Use the printAll member method and a separate println statement to output courseStudents's data. Sample output from the given program:

Name: Smith, Age: 20, ID: 9999

// ===== Code from file PersonData.java =====
public class PersonData {
   private int ageYears;
   private String lastName;

   public void setName(String userName) {
      lastName  = userName;
   }

   public void setAge(int numYears) {
      ageYears = numYears;
   }

   // Other parts omitted

   public void printAll() {
      System.out.print("Name: " + lastName);
      System.out.print(", Age: "  + ageYears);
   }
}
// ===== end =====

// ===== Code from file StudentData.java =====
public class StudentData extends PersonData {
   private int idNum;

   public void setID(int studentId) {
      idNum = studentId;
   }

   public int getID() {
      return idNum;
   }
}
// ===== end =====

// ===== Code from file StudentDerivationFromPerson.java =====
public class StudentDerivationFromPerson {
   public static void main (String [] args) {
      StudentData courseStudent = new StudentData();

      courseStudent.printAll();
      System.out.println(", ID: " + courseStudent.getID());

   }
}
// ===== end =====

I'm sure that I'm overlooking something simple, but I'm not sure what. My code is the just the last few lines:

courseStudent.printAll();
System.out.println(", ID: " + courseStudent.getID());

Body:
You need to add set values so you don’t get null and 0 as output.
The correct answer is:

courseStudent.setID(9999);
courseStudent.setName(“Smith”);
courseStudent.setAge(20);
courseStudent.printAll();
System.out.print(“, ID: “ + courseStudent.getID());
System.out.println(“”);