问:
Different output for blank input in search function
I've written a small function for a search bar. Currently if the input doesn't match anything in my array, the function returns the last object in said array (which i made to be empty). I want to change it so that if the input is blank, the function returns "No Result" or something like that. Any ideas why this code isn't working as intended?

let websitePages =
  '{"website_pages":[' +
  '{"name":"Hamza", "path":"/hamza/"},' +
  '{"name":"Jakub", "path":"/jakub/"},' +
  '{"name":"Kevin", "path":"/kevin/"},' +
  '{"name":"Sreeja", "path":"/sreeja/"},' +
  '{"name":"Tristan", "path":"/tristan/"},' +
  '{"name":"Math", "path":"/math/"},' +
  '{"name":"History", "path":"/history/"},' +
  '{"name":"Science", "path":"/sci/"},' +
  '{"name":"Literature", "path":"/lit/"},' +
  '{"name":"Periodic Table", "path":"/periodictable/"},' +
  '{"name":"API Collection", "path":"/api_collection/"},' +
  '{"name":"CRUD", "path":"/crud/"},' +
  '{"name":"Async CRUD", "path":"/crud_api/"},' +
  '{"name":"Database Search", "path":"/crud/search/"},' +
  '{"name":"Search (Database)", "path":"/crud/search/"},' +
  '{"name":"", "path":"//"}]}'; // this object is empty in case the user inputs a blank, so that the previous result is removed and no link is returned

function SearchMain() {
  list = JSON.parse(websitePages);
  input = document.getElementById("SearchInput");
  filter = input.value.toUpperCase(); // the user's input is changed to uppercase so that the search is not case-sensitive
  for (i = 0; i < websitePages.length; i++) {
    // this section goes through the items in my array and checks if the user's input is the same as any object name
    if (
      filter ===
      list.website_pages[i].name.toUpperCase().substring(0, filter.length)
    ) {
      //using substrings allows users to only input part of the page name instead of the whole thing
      link = list.website_pages[i].path;
      document.getElementById("searchResult").innerHTML =
        list.website_pages[i].name;
      document.getElementById("searchResult").href = link;
    } else if (filter === null) {
      document.getElementById("searchResult").innerHTML = "No Results";
      document.getElementById("searchResult").href = "";
    }
  }
}

```

答:
For loop condition should be i < list.website_pages.length, also you should handle two error scenarios. One is input is empty and the search didnot find any valid match. I have updated them in the below fiddle.

Working Fiddle

let websitePages = '{"website_pages":[' +
  '{"name":"Hamza", "path":"/hamza/"},' +
  '{"name":"Jakub", "path":"/jakub/"},' +
  '{"name":"Kevin", "path":"/kevin/"},' +
  '{"name":"Sreeja", "path":"/sreeja/"},' +
  '{"name":"Tristan", "path":"/tristan/"},' +
  '{"name":"Math", "path":"/math/"},' +
  '{"name":"History", "path":"/history/"},' +
  '{"name":"Science", "path":"/sci/"},' +
  '{"name":"Literature", "path":"/lit/"},' +
  '{"name":"Periodic Table", "path":"/periodictable/"},' +
  '{"name":"API Collection", "path":"/api_collection/"},' +
  '{"name":"CRUD", "path":"/crud/"},' +
  '{"name":"Async CRUD", "path":"/crud_api/"},' +
  '{"name":"Database Search", "path":"/crud/search/"},' +
  '{"name":"Search (Database)", "path":"/crud/search/"},' +
  '{"name":"", "path":"//"}]}'; // this object is empty in case the user inputs a blank, so that the previous result is removed and no link is returned

function SearchMain() {
  list = JSON.parse(websitePages);
  input = document.getElementById('SearchInput');
  filter = input.value.toUpperCase(); // the user's input is changed to uppercase so that the search is not case-sensitive
  let isFound = false;
  for (i = 0; i < list.website_pages.length; i++) { // this section goes through the items in my array and checks if the user's input is the same as any object name
    if (filter === list.website_pages[i].name.toUpperCase().substring(0, filter.length)) { //using substrings allows users to only input part of the page name instead of the whole thing
      link = list.website_pages[i].path;
      document.getElementById('searchResult').innerHTML = list.website_pages[i].name;
      document.getElementById('searchResult').href = link;
      isFound = true;
    }
  }
  if (!filter || !isFound) {
    document.getElementById('searchResult').innerHTML = "No Results"
    document.getElementById('searchResult').href = ""
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="SearchInput" />
<button onclick="SearchMain()">SearchMain</button>
</code>```

Simplified solution.

Avoid using for loop and make use of Array.find to find the matching node from the list.

Working Fiddle

let websitePages = '{"website_pages":[' +
  '{"name":"Hamza", "path":"/hamza/"},' +
  '{"name":"Jakub", "path":"/jakub/"},' +
  '{"name":"Kevin", "path":"/kevin/"},' +
  '{"name":"Sreeja", "path":"/sreeja/"},' +
  '{"name":"Tristan", "path":"/tristan/"},' +
  '{"name":"Math", "path":"/math/"},' +
  '{"name":"History", "path":"/history/"},' +
  '{"name":"Science", "path":"/sci/"},' +
  '{"name":"Literature", "path":"/lit/"},' +
  '{"name":"Periodic Table", "path":"/periodictable/"},' +
  '{"name":"API Collection", "path":"/api_collection/"},' +
  '{"name":"CRUD", "path":"/crud/"},' +
  '{"name":"Async CRUD", "path":"/crud_api/"},' +
  '{"name":"Database Search", "path":"/crud/search/"},' +
  '{"name":"Search (Database)", "path":"/crud/search/"},' +
  '{"name":"", "path":"//"}]}'; // this object is empty in case the user inputs a blank, so that the previous result is removed and no link is returned

function SearchMain() {
  list = JSON.parse(websitePages);
  input = document.getElementById('SearchInput');
  filter = input.value.toUpperCase(); // the user's input is changed to uppercase so that the search is not case-sensitive
  const matchingNode = filter ? list.website_pages.find(node => filter === node.name.toUpperCase().substring(0, filter.length)) : null;
  if (matchingNode) {
    document.getElementById('searchResult').innerHTML = matchingNode.name;
    document.getElementById('searchResult').href = matchingNode.path;
  }
  else {
    document.getElementById('searchResult').innerHTML = "No Results"
    document.getElementById('searchResult').href = ""
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="SearchInput" />
<button onclick="SearchMain()">SearchMain</button>
</code>```

Body:
For loop condition should be i < list.website_pages.length, also you should handle two error scenarios. One is input is empty and the search didnot find any valid match. I have updated them in the below fiddle.

Working Fiddle

let websitePages = '{"website_pages":[' +
  '{"name":"Hamza", "path":"/hamza/"},' +
  '{"name":"Jakub", "path":"/jakub/"},' +
  '{"name":"Kevin", "path":"/kevin/"},' +
  '{"name":"Sreeja", "path":"/sreeja/"},' +
  '{"name":"Tristan", "path":"/tristan/"},' +
  '{"name":"Math", "path":"/math/"},' +
  '{"name":"History", "path":"/history/"},' +
  '{"name":"Science", "path":"/sci/"},' +
  '{"name":"Literature", "path":"/lit/"},' +
  '{"name":"Periodic Table", "path":"/periodictable/"},' +
  '{"name":"API Collection", "path":"/api_collection/"},' +
  '{"name":"CRUD", "path":"/crud/"},' +
  '{"name":"Async CRUD", "path":"/crud_api/"},' +
  '{"name":"Database Search", "path":"/crud/search/"},' +
  '{"name":"Search (Database)", "path":"/crud/search/"},' +
  '{"name":"", "path":"//"}]}'; // this object is empty in case the user inputs a blank, so that the previous result is removed and no link is returned

function SearchMain() {
  list = JSON.parse(websitePages);
  input = document.getElementById('SearchInput');
  filter = input.value.toUpperCase(); // the user's input is changed to uppercase so that the search is not case-sensitive
  let isFound = false;
  for (i = 0; i < list.website_pages.length; i++) { // this section goes through the items in my array and checks if the user's input is the same as any object name
    if (filter === list.website_pages[i].name.toUpperCase().substring(0, filter.length)) { //using substrings allows users to only input part of the page name instead of the whole thing
      link = list.website_pages[i].path;
      document.getElementById('searchResult').innerHTML = list.website_pages[i].name;
      document.getElementById('searchResult').href = link;
      isFound = true;
    }
  }
  if (!filter || !isFound) {
    document.getElementById('searchResult').innerHTML = "No Results"
    document.getElementById('searchResult').href = ""
  }
}

<input type="text" id="SearchInput" />
<button onclick="SearchMain()">SearchMain</button>
<a id="searchResult"></a>

Simplified solution.

Avoid using for loop and make use of Array.find to find the matching node from the list.

Working Fiddle

let websitePages = '{"website_pages":[' +
  '{"name":"Hamza", "path":"/hamza/"},' +
  '{"name":"Jakub", "path":"/jakub/"},' +
  '{"name":"Kevin", "path":"/kevin/"},' +
  '{"name":"Sreeja", "path":"/sreeja/"},' +
  '{"name":"Tristan", "path":"/tristan/"},' +
  '{"name":"Math", "path":"/math/"},' +
  '{"name":"History", "path":"/history/"},' +
  '{"name":"Science", "path":"/sci/"},' +
  '{"name":"Literature", "path":"/lit/"},' +
  '{"name":"Periodic Table", "path":"/periodictable/"},' +
  '{"name":"API Collection", "path":"/api_collection/"},' +
  '{"name":"CRUD", "path":"/crud/"},' +
  '{"name":"Async CRUD", "path":"/crud_api/"},' +
  '{"name":"Database Search", "path":"/crud/search/"},' +
  '{"name":"Search (Database)", "path":"/crud/search/"},' +
  '{"name":"", "path":"//"}]}'; // this object is empty in case the user inputs a blank, so that the previous result is removed and no link is returned

function SearchMain() {
  list = JSON.parse(websitePages);
  input = document.getElementById('SearchInput');
  filter = input.value.toUpperCase(); // the user's input is changed to uppercase so that the search is not case-sensitive
  const matchingNode = filter ? list.website_pages.find(node => filter === node.name.toUpperCase().substring(0, filter.length)) : null;
  if (matchingNode) {
    document.getElementById('searchResult').innerHTML = matchingNode.name;
    document.getElementById('searchResult').href = matchingNode.path;
  }
  else {
    document.getElementById('searchResult').innerHTML = "No Results"
    document.getElementById('searchResult').href = ""
  }
}

<input type="text" id="SearchInput" />
<button onclick="SearchMain()">SearchMain</button>
<a id="searchResult"></a>


来源: stackexchange

问:
How to bind data from a List<class> to Picker element in Xamarin
I have a list (List<Customer> l_Customer) that gets data from an API. <Customer> class includes fullname that is of string value. How can i get only the full names from that list and display them on the Picker's dropdown list?

答:
I make a simple example for your reference with MVVM.

Xaml:

```<code>  <Picker ItemsSource="{Binding l_Customer}" ItemDisplayBinding="{Binding fullname}"></Picker>
</code>```

Code behind:

```<code>public partial class Page14 : ContentPage
{
    public Page14()
    {
        InitializeComponent();
        this.BindingContext = new CustomerViewModel();
    }
}
public class CustomerViewModel
{
    public List<Customer> l_Customer { get; set; }
    public CustomerViewModel()
    {
        l_Customer = new List<Customer>()
        {
            new Customer(){ fullname="A"},
            new Customer(){ fullname="B"},
            new Customer(){ fullname="C"},
        };
    }
}
public class Customer
{
    public string fullname { get; set; }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I make a simple example for your reference with MVVM.

Xaml:

  <Picker ItemsSource="{Binding l_Customer}" ItemDisplayBinding="{Binding fullname}"></Picker>

Code behind:

public partial class Page14 : ContentPage
{
    public Page14()
    {
        InitializeComponent();
        this.BindingContext = new CustomerViewModel();
    }
}
public class CustomerViewModel
{
    public List<Customer> l_Customer { get; set; }
    public CustomerViewModel()
    {
        l_Customer = new List<Customer>()
        {
            new Customer(){ fullname="A"},
            new Customer(){ fullname="B"},
            new Customer(){ fullname="C"},
        };
    }
}
public class Customer
{
    public string fullname { get; set; }
}


问:
Page refresh error on static website in react
I made a static website application in React. localhost is working. but when I upload it to the server, I get a page not found error when I refresh the page on pages other than the home page. What is the solution?</p>

答:
Create .htaccess file on the Server and past below code in the file:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /subdirectory
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule . /index.html [L]
</IfModule>
</code>```

Body:
Create .htaccess file on the Server and past below code in the file:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /subdirectory
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule . /index.html [L]
</IfModule>


问:
How to add attribute on load and change value when clicking an element with Javascript?
I would like to add attribute "aria-label=test1" when it is fa-chevron-left and "aria-label=test2" on fa-chevron-right.

fa-chevron-left (see image) would be there on load and "aria-label=test1" should be there on load as well (default). The function is to collapse and expand the table of contents.

This element is clickable and I want the aria-label value to change dynamically.

Here is my existing JavaScript code:

function r() {
        const e = document.querySelector(".slide-btn");
        e.getBoundingClientRect().x < window.innerWidth / 2 ? (e.classList.add("left"), e.classList.remove("right")) : (e.classList.remove("left"), e.classList.add("right"));
    }
function s(e) {
          const t = n(),
            c = document.querySelector(".nav-container"),
            o = document.querySelector(".content-container"),
            s = document.querySelector(".slide-btn i.fas");
          switch (e) {
            case "toggle":
              c.classList.toggle("slided"),
                s.classList.toggle("fa-chevron-right"),
                s.classList.toggle("fa-chevron-left"),
                t && o.classList.toggle("slided");
              break;
            case "show":
              c.classList.remove("slided"),
                s.classList.remove("fa-chevron-right"),
                s.classList.add("fa-chevron-left"),
                t && o.classList.add("slided");
              break;
            case "hide":
              if (c.classList.add("slided"), s.classList.add("fa-chevron-right"), s.classList.remove("fa-chevron-left"), t) {
                o.classList.remove("slided");
                const e = document.querySelector(".body-container").getAttribute("activeTopic");
                document.getElementById(e).scrollIntoView()
              }
          }
        }
```
<p>Here is the existing HTML code:</p>
<pre class="lang-html prettyprint-override"><code><div class="slide-btn left" style="height: 749px;">
<i class="fas fa-chevron-left"></i>
</div>
</code>```

I've added this code below s = document.querySelector(".slide-btn i.fas");:

s.setAttribute("aria-label", s.classList.contains("fa-chevron-left") ? "test1" : "test2");
```

However, the attribute and value does not appear on load. It only appears and changes when I click the fa-chevron-left. Is there a way I can make the aria-label show on load and change value when I click fa-chevron-left and fa-chevron-right?

答:
element.matches('.classname') from this method to get true or false. If class name is exist then return true otherwise false. So I used for checking class is exist or not from .matches() method & from .setAttebute() to set attribute value like: element.setAttribute('attribute-name', 'attribute value')

function r() {
    const e = document.querySelector(".slide-btn");
    e.getBoundingClientRect().x < window.innerWidth / 2 ? (e.classList.add("left"), e.classList.remove("right")) : (e.classList.remove("left"), e.classList.add("right"));
}
function s(e) {
    const t = r(), /*n() to r()*/
        c = document.querySelector(".nav-container"),
        o = document.querySelector(".content-container"),
        s = document.querySelector(".slide-btn i.fas");
    switch (e) {
        case "toggle":
            c.classList.toggle("slided");

            /*Check class is exist or not*/
            if(s.matches('.fa-chevron-right')){
                s.classList.remove("fa-chevron-right");
                s.classList.add("fa-chevron-left");
                s.setAttribute("aria-label","test1"); /*add attribute*/
            }else{
                s.classList.remove("fa-chevron-left");
                s.classList.add("fa-chevron-right");
                s.setAttribute("aria-label", "test2"); /*add attribute*/
            }

            t && o.classList.toggle("slided");
            break;
        case "show":
            c.classList.remove("slided"),
            s.classList.remove("fa-chevron-right"),
            s.classList.add("fa-chevron-left"),
            s.setAttribute("aria-label", "test1");

            t && o.classList.add("slided");
            break;
        case "hide":
            if (c.classList.add("slided"), s.classList.add("fa-chevron-right"), s.classList.remove("fa-chevron-left"), t) {
                o.classList.remove("slided");
                const e = document.querySelector(".body-container").getAttribute("activeTopic");
                document.getElementById(e).scrollIntoView()
            }
    }
}

/*show --> On page load */
s("show");

/* toggle --> on click event */
document.querySelector(".slide-btn").addEventListener("click", (() => { s("toggle") }));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css"/>

<div class="nav-container">
    <div class="content-container">
        <div class="slide-btn left" style="height: 749px;">
            <i class="fas fa-chevron-left"></i>
        </div>
    </div>
</div></code>```

Body:
I would like to add attribute "aria-label=test1" when it is fa-chevron-left and "aria-label=test2" on fa-chevron-right.

fa-chevron-left (see image) would be there on load and "aria-label=test1" should be there on load as well (default). The function is to collapse and expand the table of contents.

This element is clickable and I want the aria-label value to change dynamically.

Here is my existing JavaScript code:

function r() {
        const e = document.querySelector(".slide-btn");
        e.getBoundingClientRect().x < window.innerWidth / 2 ? (e.classList.add("left"), e.classList.remove("right")) : (e.classList.remove("left"), e.classList.add("right"));
    }
function s(e) {
          const t = n(),
            c = document.querySelector(".nav-container"),
            o = document.querySelector(".content-container"),
            s = document.querySelector(".slide-btn i.fas");
          switch (e) {
            case "toggle":
              c.classList.toggle("slided"),
                s.classList.toggle("fa-chevron-right"),
                s.classList.toggle("fa-chevron-left"),
                t && o.classList.toggle("slided");
              break;
            case "show":
              c.classList.remove("slided"),
                s.classList.remove("fa-chevron-right"),
                s.classList.add("fa-chevron-left"),
                t && o.classList.add("slided");
              break;
            case "hide":
              if (c.classList.add("slided"), s.classList.add("fa-chevron-right"), s.classList.remove("fa-chevron-left"), t) {
                o.classList.remove("slided");
                const e = document.querySelector(".body-container").getAttribute("activeTopic");
                document.getElementById(e).scrollIntoView()
              }
          }
        }

Here is the existing HTML code:

I've added this code below s = document.querySelector(".slide-btn i.fas");:

s.setAttribute("aria-label", s.classList.contains("fa-chevron-left") ? "test1" : "test2");

However, the attribute and value does not appear on load. It only appears and changes when I click the fa-chevron-left. Is there a way I can make the aria-label show on load and change value when I click fa-chevron-left and fa-chevron-right?

Body:
element.matches('.classname') from this method to get true or false. If class name is exist then return true otherwise false. So I used for checking class is exist or not from .matches() method & from .setAttebute() to set attribute value like: element.setAttribute('attribute-name', 'attribute value')

function r() {
    const e = document.querySelector(".slide-btn");
    e.getBoundingClientRect().x < window.innerWidth / 2 ? (e.classList.add("left"), e.classList.remove("right")) : (e.classList.remove("left"), e.classList.add("right"));
}
function s(e) {
    const t = r(), /*n() to r()*/
        c = document.querySelector(".nav-container"),
        o = document.querySelector(".content-container"),
        s = document.querySelector(".slide-btn i.fas");
    switch (e) {
        case "toggle":
            c.classList.toggle("slided");

            /*Check class is exist or not*/
            if(s.matches('.fa-chevron-right')){
                s.classList.remove("fa-chevron-right");
                s.classList.add("fa-chevron-left");
                s.setAttribute("aria-label","test1"); /*add attribute*/
            }else{
                s.classList.remove("fa-chevron-left");
                s.classList.add("fa-chevron-right");
                s.setAttribute("aria-label", "test2"); /*add attribute*/
            }

            t && o.classList.toggle("slided");
            break;
        case "show":
            c.classList.remove("slided"),
            s.classList.remove("fa-chevron-right"),
            s.classList.add("fa-chevron-left"),
            s.setAttribute("aria-label", "test1");

            t && o.classList.add("slided");
            break;
        case "hide":
            if (c.classList.add("slided"), s.classList.add("fa-chevron-right"), s.classList.remove("fa-chevron-left"), t) {
                o.classList.remove("slided");
                const e = document.querySelector(".body-container").getAttribute("activeTopic");
                document.getElementById(e).scrollIntoView()
            }
    }
}

/*show --> On page load */
s("show");

/* toggle --> on click event */
document.querySelector(".slide-btn").addEventListener("click", (() => { s("toggle") }));

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css"/>

<div class="nav-container">
    <div class="content-container">
        <div class="slide-btn left" style="height: 749px;">
            <i class="fas fa-chevron-left"></i>
        </div>
    </div>
</div>


问:
Existence of a resource within a resource group
How to check the existence of a express route within a resource group. I have list of resource group but not all resource groups have express routes within them. What is the condition that needs to be written to check if there is a express route inside each resource group

rgList ==> List of all the resource groups in a specific subscription

erList ==> List of all the express routes in a specific subscription

```<code>rgList="$(az group list --subscription "sub1" --query [].name --output tsv)"
erList="$(az network express-route list --subscription "sub1" --query [].name --output tsv)"
for i in $rgList; do
    if [[ $(az network express-route list -g "$i" --subscription "sub-network-central-services" --query "[].name | length(@))" > 0 ]]
    then
        for j in $erList; do
            hubname+="$(az network express-route auth list --circuit-name "$j" --resource-group "$i" --query [].authorizations[].name --output tsv)"
        done
    fi
done
</code>```

I am getting the below error
bash: syntax error near unexpected token `done'

答:
As mentioned above, yes there were some syntactical errors while testing in our local environment we have fixed those errors & we have modified the above script as well.

The Modified script will pull the authorization names & Express-route circuit name.

If want to get the list of resource groups which has express-route circuit you can directly refer to Alternative Script in the My solution.

Here is the Modified Bash Script:

hubname=""
rglist=$(az group list --subscription "<subNameorSubId>" --query [].name --output tsv)
erList=$(az network express-route list --subscription "<subNameorSubId>" --query [].name --output tsv)
for i in $rglist;
do
if [[ $(az network express-route list -g $i --subscription "<subNameorSubId>" --query "[].name | length(@)") > 0 ]]
    then
        for j in $erList;
        do
             hubname+=$(az network express-route auth list --circuit-name $j --resource-group $i --query [].name --output tsv)
             echo $j,$hubname
        done
    fi
done
```

<p><strong>Here is the sample output screenshot for reference:</strong></p>
<p><img src="https://i.imgur.com/Nyn0Nng.png" alt="enter image description here" /></p>
<p>Alternatively, you can use the below bash script this will give you the list of resource groups if an express-route circuit is present in it.</p>
<p><strong>Alternative Script:</strong></p>
<pre class="lang-html prettyprint-override"><code> rgList=$(az group list --subscription "<SubNameorSubId>" --query [].name --output tsv)
    for i in $rgList;do
        resourcelist=$(az resource list -g $i --query [].type -o tsv)
        for j in $resourcelist;do
            if [[ $j ==  "Microsoft.Network/expressRouteCircuits" ]]
            then
                echo $i
            fi
        done
    done
</code>```

Here is the Sample Output for reference:

Body:
How to check the existence of a express route within a resource group. I have list of resource group but not all resource groups have express routes within them. What is the condition that needs to be written to check if there is a express route inside each resource group

rgList ==> List of all the resource groups in a specific subscription

erList ==> List of all the express routes in a specific subscription

rgList="$(az group list --subscription "sub1" --query [].name --output tsv)"
erList="$(az network express-route list --subscription "sub1" --query [].name --output tsv)"
for i in $rgList; do
    if [[ $(az network express-route list -g "$i" --subscription "sub-network-central-services" --query "[].name | length(@))" > 0 ]]
    then
        for j in $erList; do
            hubname+="$(az network express-route auth list --circuit-name "$j" --resource-group "$i" --query [].authorizations[].name --output tsv)"
        done
    fi
done

I am getting the below error
bash: syntax error near unexpected token `done'

Body:
As mentioned above, yes there were some syntactical errors while testing in our local environment we have fixed those errors & we have modified the above script as well.

The Modified script will pull the authorization names & Express-route circuit name.

If want to get the list of resource groups which has express-route circuit you can directly refer to Alternative Script in the My solution.

Here is the Modified Bash Script:

hubname=""
rglist=$(az group list --subscription "<subNameorSubId>" --query [].name --output tsv)
erList=$(az network express-route list --subscription "<subNameorSubId>" --query [].name --output tsv)
for i in $rglist;
do
if [[ $(az network express-route list -g $i --subscription "<subNameorSubId>" --query "[].name | length(@)") > 0 ]]
    then
        for j in $erList;
        do
             hubname+=$(az network express-route auth list --circuit-name $j --resource-group $i --query [].name --output tsv)
             echo $j,$hubname
        done
    fi
done

Here is the sample output screenshot for reference:

Alternatively, you can use the below bash script this will give you the list of resource groups if an express-route circuit is present in it.

Alternative Script:

 rgList=$(az group list --subscription "<SubNameorSubId>" --query [].name --output tsv)
    for i in $rgList;do
        resourcelist=$(az resource list -g $i --query [].type -o tsv)
        for j in $resourcelist;do
            if [[ $j ==  "Microsoft.Network/expressRouteCircuits" ]]
            then
                echo $i
            fi
        done
    done

Here is the Sample Output for reference:


问:
When and how can we start forgetting about non-retina display iPhones and iPod Touches?
Now more than one year passed since a retina display device appeared. Does anyone know some numbers how many users still suffer under the low-resolution devices? How long do they use their iPhones or iPods until they realize that a retina display is so much better?

I'm sick of having to create every graphic two times, trashing the binary with all these low-resolution files. I wonder if anyone has stopped supporting low resolution hardware without a big loss.

And: If I wanted to stop supporting low resolution devices, what kind of settings in the info.plist must I make? And what would happen if a low-res device still installs my retina-only app?

答: You can at least wait for Apple to stop providing iOS updates to low-resolution devices (i.e. iPhone 3G S) since it is capable of running iOS 5</p>

ContentLicense: CC BY-SA 3.0


问:
How to setup Serilog with Azure Functions v4 correctly?
I want to use Serilog in an Azure Function v4 (.net 6) (the logs should be sent to Datadog). For this I have installed the following nuget packages:

```<code><PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
<PackageReference Include="Serilog.Sinks.Datadog.Logs" Version="0.3.5" />
</code>```

Below is the configuration in the Startup.cs class:

```<code>public override void Configure(IFunctionsHostBuilder builder)
{
  builder.Services.AddHttpClient();

  //... adding services etc.

  Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("Worker", LogEventLevel.Warning)
    .MinimumLevel.Override("Host", LogEventLevel.Warning)
    .MinimumLevel.Override("System", LogEventLevel.Error)
    .MinimumLevel.Override("Function", LogEventLevel.Error)
    .MinimumLevel.Override("Azure.Storage.Blobs", LogEventLevel.Error)
    .MinimumLevel.Override("Azure.Core", LogEventLevel.Error)
    .Enrich.WithProperty("Application", "Comatic.KrediScan.AzureFunctions")
    .Enrich.FromLogContext()
    .WriteTo.DatadogLogs("XXXXXXXXXXX", configuration: new DatadogConfiguration() { Url = "https://http-intake.logs.datadoghq.eu" }, logLevel:   LogEventLevel.Debug)
    .WriteTo.Console()
    .CreateLogger();

  builder.Services.AddSingleton<ILoggerProvider>(sp => new SerilogLoggerProvider(Log.Logger, true));

  builder.Services.AddLogging(lb =>
  {
    //lb.ClearProviders(); //--> if used nothing works...
    lb.AddSerilog(Log.Logger, true);
  });
</code>```

Basically logging works, but all log statements are written twice (with a few milliseconds difference, Datadog and Console).

Obviously I am doing something fundamentally wrong with the configuration. I don't use appsettings.json, the configuration of Serilog takes place exclusively in the code. I have scoured the entire internet and read just about every article on Serilog and Azure Functions. On Stackoverflow I also read virtually every question about it and tried all the answers. Unfortunately, so far without success.

SO-Questions for example:
Use Serilog with Azure Log Stream

How do I use Serilog with Azure WebJobs?

Serilog enricher Dependency Injection with Azure Functions

https://github.com/hgmauri/sample-azure-functions/blob/main/src/Sample.AzureFunctions.DotNet31/Startup.cs

Is there any example for setting up Serilog with Azure Functions v4 / .net 6?

Thanks a lot for the help!

Michael Hachen

答:
Got it! After replacing all ILogger with ILogger<T> and removing the line builder.Services.AddSingleton<ILoggerProvider>(sp => new SerilogLoggerProvider(Log.Logger, true)); everything worked as expected.

Startup.cs

```<code>Log.Logger = new LoggerConfiguration()
          .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
          .MinimumLevel.Override("Worker", LogEventLevel.Warning)
          .MinimumLevel.Override("Host", LogEventLevel.Warning)
          .MinimumLevel.Override("System", LogEventLevel.Error)
          .MinimumLevel.Override("Function", LogEventLevel.Error)
          .MinimumLevel.Override("Azure.Storage.Blobs", LogEventLevel.Error)
          .MinimumLevel.Override("Azure.Core", LogEventLevel.Error)
          .Enrich.WithProperty("Application", $"xxxxx.AzureFunctions.{builder.GetContext().EnvironmentName}")
          .Enrich.FromLogContext()
          .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
            .WithDefaultDestructurers()
            .WithDestructurers(new[] { new SqlExceptionDestructurer() }))
          .WriteTo.Seq(builder.GetContext().EnvironmentName.Equals("Development", StringComparison.OrdinalIgnoreCase) ? "http://localhost:5341/" : "https://xxxxxx.xx:5341/", LogEventLevel.Verbose)
          .WriteTo.Console(theme: SystemConsoleTheme.Literate)
          .CreateLogger();

      builder.Services.AddLogging(lb =>
      {
        lb.AddSerilog(Log.Logger, true);
      });
</code>```

Body:
I want to use Serilog in an Azure Function v4 (.net 6) (the logs should be sent to Datadog). For this I have installed the following nuget packages:

<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
<PackageReference Include="Serilog.Sinks.Datadog.Logs" Version="0.3.5" />

Below is the configuration in the Startup.cs class:

public override void Configure(IFunctionsHostBuilder builder)
{
  builder.Services.AddHttpClient();

  //... adding services etc.

  Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("Worker", LogEventLevel.Warning)
    .MinimumLevel.Override("Host", LogEventLevel.Warning)
    .MinimumLevel.Override("System", LogEventLevel.Error)
    .MinimumLevel.Override("Function", LogEventLevel.Error)
    .MinimumLevel.Override("Azure.Storage.Blobs", LogEventLevel.Error)
    .MinimumLevel.Override("Azure.Core", LogEventLevel.Error)
    .Enrich.WithProperty("Application", "Comatic.KrediScan.AzureFunctions")
    .Enrich.FromLogContext()
    .WriteTo.DatadogLogs("XXXXXXXXXXX", configuration: new DatadogConfiguration() { Url = "https://http-intake.logs.datadoghq.eu" }, logLevel:   LogEventLevel.Debug)
    .WriteTo.Console()
    .CreateLogger();

  builder.Services.AddSingleton<ILoggerProvider>(sp => new SerilogLoggerProvider(Log.Logger, true));

  builder.Services.AddLogging(lb =>
  {
    //lb.ClearProviders(); //--> if used nothing works...
    lb.AddSerilog(Log.Logger, true);
  });

Basically logging works, but all log statements are written twice (with a few milliseconds difference, Datadog and Console).

Obviously I am doing something fundamentally wrong with the configuration. I don't use appsettings.json, the configuration of Serilog takes place exclusively in the code. I have scoured the entire internet and read just about every article on Serilog and Azure Functions. On Stackoverflow I also read virtually every question about it and tried all the answers. Unfortunately, so far without success.

SO-Questions for example:
Use Serilog with Azure Log Stream

How do I use Serilog with Azure WebJobs?

Serilog enricher Dependency Injection with Azure Functions

https://github.com/hgmauri/sample-azure-functions/blob/main/src/Sample.AzureFunctions.DotNet31/Startup.cs

Is there any example for setting up Serilog with Azure Functions v4 / .net 6?

Thanks a lot for the help!

Michael Hachen

Body:
Got it! After replacing all ILogger with ILogger<T> and removing the line builder.Services.AddSingleton<ILoggerProvider>(sp => new SerilogLoggerProvider(Log.Logger, true)); everything worked as expected.

Startup.cs

Log.Logger = new LoggerConfiguration()
          .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
          .MinimumLevel.Override("Worker", LogEventLevel.Warning)
          .MinimumLevel.Override("Host", LogEventLevel.Warning)
          .MinimumLevel.Override("System", LogEventLevel.Error)
          .MinimumLevel.Override("Function", LogEventLevel.Error)
          .MinimumLevel.Override("Azure.Storage.Blobs", LogEventLevel.Error)
          .MinimumLevel.Override("Azure.Core", LogEventLevel.Error)
          .Enrich.WithProperty("Application", $"xxxxx.AzureFunctions.{builder.GetContext().EnvironmentName}")
          .Enrich.FromLogContext()
          .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
            .WithDefaultDestructurers()
            .WithDestructurers(new[] { new SqlExceptionDestructurer() }))
          .WriteTo.Seq(builder.GetContext().EnvironmentName.Equals("Development", StringComparison.OrdinalIgnoreCase) ? "http://localhost:5341/" : "https://xxxxxx.xx:5341/", LogEventLevel.Verbose)
          .WriteTo.Console(theme: SystemConsoleTheme.Literate)
          .CreateLogger();

      builder.Services.AddLogging(lb =>
      {
        lb.AddSerilog(Log.Logger, true);
      });


问:
How to replace 2 double quotes into single double quotes in dataframe?
I have text file inside there one column having 2 double quotes. I am trying to replacing them but not able to get the result.

Example:

In text file the data is:

```<code>From Date,To Date,Item Number,Item Description
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
</code>```

But while reading this file as dataframe it is showing:

```<code>From Date   To Date     Item Number    Item Description
01/31/2022  02/06/2022   100455       "REMICADE INJ 100MG    "R"      10ML"
01/31/2022  02/06/2022   100455       "REMICADE INJ 100MG    "R"      10ML"
01/31/2022  02/06/2022   100455       "REMICADE INJ 100MG    "R"      10ML"
01/31/2022  02/06/2022   100455       "REMICADE INJ 100MG    "R"      10ML"
</code>```

I am running below code-

```<code>df = pd.read_csv(r"D:\Users\SPate233\Downloads\iMedical\Anamoly Script\dhs\KF_Standard_Customer_Activity_Data_February072022.txt", delimiter =',')
print(df.head())
print(df['Item Description'])
df1 = df.replace({r'"' : ''}, regex = True)
print(df1['Item Description'])
df1.to_csv(r"D:\Users\SPate233\Downloads\iMedical\Anamoly Script\dhs\out.txt", index=False, sep=',')
</code>```

In Output File I am getting below record-

```<code>From Date,To Date,Item Number,Item Description
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
</code>```

答:
This is an effect of the CSV encoding. CSV does not really have a universally accepted spec, but RFC 4180 is an attempt, which states (in section 2.7):

If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote.

So, for example, the text

```<code>"Hello", she said.
</code>```

gets written into the file as

```<code>"""Hello"", she said."
</code>```

Pandas' read_csv and to_csv functions take care of this for you, as does the csv module of the standard library.

Body:
I have text file inside there one column having 2 double quotes. I am trying to replacing them but not able to get the result.

Example:

In text file the data is:

From Date,To Date,Item Number,Item Description
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"

But while reading this file as dataframe it is showing:

From Date   To Date     Item Number    Item Description
01/31/2022  02/06/2022   100455       "REMICADE INJ 100MG    "R"      10ML"
01/31/2022  02/06/2022   100455       "REMICADE INJ 100MG    "R"      10ML"
01/31/2022  02/06/2022   100455       "REMICADE INJ 100MG    "R"      10ML"
01/31/2022  02/06/2022   100455       "REMICADE INJ 100MG    "R"      10ML"

I am running below code-

df = pd.read_csv(r"D:\Users\SPate233\Downloads\iMedical\Anamoly Script\dhs\KF_Standard_Customer_Activity_Data_February072022.txt", delimiter =',')
print(df.head())
print(df['Item Description'])
df1 = df.replace({r'"' : ''}, regex = True)
print(df1['Item Description'])
df1.to_csv(r"D:\Users\SPate233\Downloads\iMedical\Anamoly Script\dhs\out.txt", index=False, sep=',')

In Output File I am getting below record-

From Date,To Date,Item Number,Item Description
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"
01/31/2022,02/06/2022,100455,"REMICADE INJ 100MG    ""R""       10ML"

Body:
This is an effect of the CSV encoding. CSV does not really have a universally accepted spec, but RFC 4180 is an attempt, which states (in section 2.7):

If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote.

So, for example, the text

"Hello", she said.

gets written into the file as

"""Hello"", she said."

Pandas' read_csv and to_csv functions take care of this for you, as does the csv module of the standard library.


问:
How to fix NameError error when calling a function that was already defined?
I have a simple calculator program in Python and I keep getting the NameError even though I already declared the function. And I am not sure why this is occurring. Also, I have another error at Line 25 of the code at the elif statement and it's showing me the invalid syntax error. However, I have checked the indentation and the elif statement and I'm not sure what is wrong with it. Thus, does anyone know what is the reason why this 2 errors occur and how can I fix them? Thank you.

Code:

'''

```<code>def add(first_num, second_num):
    return float(first_num) + float(second_num)

def subtract(first_num, second_num):
    return float(first_num) - float(second_num)

def multiply(first_num, second_num):
    return float(first_num) * float(second_num)

def divide(first_num, second_num):
    return float(first_num) / float(second_num)

def calculator():

    operator = input("Select an operation (+-*/): ")
    first_num = input("Enter the first number: ")
    second_num = input("Enter the second number: ")

    if (operator == "+") :
        result = add(first_num,second_num)
    print(first_num, operator ,second_num, "=" ,result)

    elif (operator == '-'): #invalid syntax error encountered here
        result = subtract(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    elif (operator == '*'):
        result = multiply(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    elif (operator == '-'):
        result = divide(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    else:
        print("Invalid operator entered")
</code>```

'''

Screenshot of errors encountered:

NameError when calling the calculator function in the console

答:
Is it the complete code in file? Cause I cannot see where did you call the function inside the file.

You can do this thing:

create main.py

copy whole above code inside the file

write 'calculate()' on last line

go to terminal and write 'python main.py'

Your solution will start working.

Body:
I have a simple calculator program in Python and I keep getting the NameError even though I already declared the function. And I am not sure why this is occurring. Also, I have another error at Line 25 of the code at the elif statement and it's showing me the invalid syntax error. However, I have checked the indentation and the elif statement and I'm not sure what is wrong with it. Thus, does anyone know what is the reason why this 2 errors occur and how can I fix them? Thank you.

Code:

'''

def add(first_num, second_num):
    return float(first_num) + float(second_num)

def subtract(first_num, second_num):
    return float(first_num) - float(second_num)

def multiply(first_num, second_num):
    return float(first_num) * float(second_num)

def divide(first_num, second_num):
    return float(first_num) / float(second_num)

def calculator():

    operator = input("Select an operation (+-*/): ")
    first_num = input("Enter the first number: ")
    second_num = input("Enter the second number: ")

    if (operator == "+") :
        result = add(first_num,second_num)
    print(first_num, operator ,second_num, "=" ,result)

    elif (operator == '-'): #invalid syntax error encountered here
        result = subtract(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    elif (operator == '*'):
        result = multiply(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    elif (operator == '-'):
        result = divide(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    else:
        print("Invalid operator entered")

'''

Screenshot of errors encountered:

NameError when calling the calculator function in the console


问:
No libtvm.so and libtvm_runtime.so found in TVM Docker Container
I am new to Apache TVM.

I tried to build and launch a docker image named tvm.ci_cpu:latest as described in the tutorial https://tvm.apache.org/docs/install/docker.html#docker-source.

I tried to use the python application tvmc inside docker container as described in the tutorial https://tvm.apache.org/docs/tutorial/tvmc_command_line_driver.html#using-tvmc.

Then I got the following error:

```<code>$ tvmc --help

bash: tvmc: command not found
</code>```

I tried to use the other method mentioned in the article above, but I got the following new error:

```<code>$ python3 -m tvm.driver.tvmc --help

Traceback (most recent call last):
  File "/usr/lib/python3.6/runpy.py", line 183, in _run_module_as_main
    mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
  File "/usr/lib/python3.6/runpy.py", line 109, in _get_module_details
    __import__(pkg_name)
  File "/opt/share0/bob/project/tvm/python/tvm/__init__.py", line 26, in <module>
    from ._ffi.base import TVMError, __version__, _RUNTIME_ONLY
  File "/opt/share0/bob/project/tvm/python/tvm/_ffi/__init__.py", line 28, in <module>
    from .base import register_error
  File "/opt/share0/bob/project/tvm/python/tvm/_ffi/base.py", line 71, in <module>
    _LIB, _LIB_NAME = _load_lib()
  File "/opt/share0/bob/project/tvm/python/tvm/_ffi/base.py", line 51, in _load_lib
    lib_path = libinfo.find_lib_path()
  File "/opt/share0/bob/project/tvm/python/tvm/_ffi/libinfo.py", line 146, in find_lib_path
    raise RuntimeError(message)
RuntimeError: Cannot find libraries: ['libtvm.so', 'libtvm_runtime.so']
List of candidates:
/opt/sgxsdk/lib64/libtvm.so
/opt/share0/bob/project/tvm/libtvm.so
/usr/local/sbin/libtvm.so
/usr/local/bin/libtvm.so
/usr/sbin/libtvm.so
/usr/bin/libtvm.so
/sbin/libtvm.so
/bin/libtvm.so
/opt/rust/bin/libtvm.so
/usr/lib/go-1.10/bin/libtvm.so
/opt/share0/bob/project/tvm/python/tvm/libtvm.so
/opt/share0/bob/project/libtvm.so
/opt/sgxsdk/lib64/libtvm_runtime.so
/opt/share0/bob/project/tvm/libtvm_runtime.so
/usr/local/sbin/libtvm_runtime.so
/usr/local/bin/libtvm_runtime.so
/usr/sbin/libtvm_runtime.so
/usr/bin/libtvm_runtime.so
/sbin/libtvm_runtime.so
/bin/libtvm_runtime.so
/opt/rust/bin/libtvm_runtime.so
/usr/lib/go-1.10/bin/libtvm_runtime.so
/opt/share0/bob/project/tvm/python/tvm/libtvm_runtime.so
/opt/share0/bob/project/libtvm_runtime.so
</code>```

I tried to pull and use the following third-party docker images instead of the ones I built myself:

https://hub.docker.com/r/tvmai/ci-cpu

https://hub.docker.com/r/tvmai/demo-cpu

However, I still met same problems as before.

WHY? I had no idea at all.

Any suggestion? Thanks.

答:
I found pingsutw's answer in https://discuss.tvm.apache.org/t/import-tvm-returns-runtime-error-cant-find-libtvm-so-when-using-docker-demo-cpu-image/5110. After referring to his advice, I tried rebuilding tvm in a container launched from the image tvm.ci_cpu:latest which built by myself.

```<code>pushd path/to/tvm && \
    chmod +x 3rdparty/libbacktrace/configure && \
    mkdir -p cmake-build && \
    cmake -H. -Bcmake-build -DUSE_LLVM=ON && \
    cmake --build cmake-build --target all -- -j 4 && \
    mv cmake-build build && \
    popd
</code>```

After the above, I tried typing the command python3 -m tvm.driver.tvmc --help and got the following output.

```<code>usage: tvmc [-v] [--version] [-h] {run,tune,compile} ...

TVM compiler driver

optional arguments:
  -v, --verbose       increase verbosity
  --version           print the version and exit
  -h, --help          show this help message and exit.

commands:
  {run,tune,compile}
    run               run a compiled module
    tune              auto-tune a model
    compile           compile a model.

TVMC - TVM driver command-line interface
</code>```

As you can see it works now.

Surprisingly, libtvm.so and libtvm_runtime.so are not pre-built in the tvm docker image. Maybe the third-party tvm docker image is broken. Maybe the Dockerfile for building tvm docker image should be updated. Maybe it is designed to be flexibly compiled to meet various needs.

Body:
I am new to Apache TVM.

I tried to build and launch a docker image named tvm.ci_cpu:latest as described in the tutorial https://tvm.apache.org/docs/install/docker.html#docker-source.

I tried to use the python application tvmc inside docker container as described in the tutorial https://tvm.apache.org/docs/tutorial/tvmc_command_line_driver.html#using-tvmc.

Then I got the following error:

$ tvmc --help

bash: tvmc: command not found

I tried to use the other method mentioned in the article above, but I got the following new error:

$ python3 -m tvm.driver.tvmc --help

Traceback (most recent call last):
  File "/usr/lib/python3.6/runpy.py", line 183, in _run_module_as_main
    mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
  File "/usr/lib/python3.6/runpy.py", line 109, in _get_module_details
    __import__(pkg_name)
  File "/opt/share0/bob/project/tvm/python/tvm/__init__.py", line 26, in <module>
    from ._ffi.base import TVMError, __version__, _RUNTIME_ONLY
  File "/opt/share0/bob/project/tvm/python/tvm/_ffi/__init__.py", line 28, in <module>
    from .base import register_error
  File "/opt/share0/bob/project/tvm/python/tvm/_ffi/base.py", line 71, in <module>
    _LIB, _LIB_NAME = _load_lib()
  File "/opt/share0/bob/project/tvm/python/tvm/_ffi/base.py", line 51, in _load_lib
    lib_path = libinfo.find_lib_path()
  File "/opt/share0/bob/project/tvm/python/tvm/_ffi/libinfo.py", line 146, in find_lib_path
    raise RuntimeError(message)
RuntimeError: Cannot find libraries: ['libtvm.so', 'libtvm_runtime.so']
List of candidates:
/opt/sgxsdk/lib64/libtvm.so
/opt/share0/bob/project/tvm/libtvm.so
/usr/local/sbin/libtvm.so
/usr/local/bin/libtvm.so
/usr/sbin/libtvm.so
/usr/bin/libtvm.so
/sbin/libtvm.so
/bin/libtvm.so
/opt/rust/bin/libtvm.so
/usr/lib/go-1.10/bin/libtvm.so
/opt/share0/bob/project/tvm/python/tvm/libtvm.so
/opt/share0/bob/project/libtvm.so
/opt/sgxsdk/lib64/libtvm_runtime.so
/opt/share0/bob/project/tvm/libtvm_runtime.so
/usr/local/sbin/libtvm_runtime.so
/usr/local/bin/libtvm_runtime.so
/usr/sbin/libtvm_runtime.so
/usr/bin/libtvm_runtime.so
/sbin/libtvm_runtime.so
/bin/libtvm_runtime.so
/opt/rust/bin/libtvm_runtime.so
/usr/lib/go-1.10/bin/libtvm_runtime.so
/opt/share0/bob/project/tvm/python/tvm/libtvm_runtime.so
/opt/share0/bob/project/libtvm_runtime.so

I tried to pull and use the following third-party docker images instead of the ones I built myself:

https://hub.docker.com/r/tvmai/ci-cpu

https://hub.docker.com/r/tvmai/demo-cpu

However, I still met same problems as before.

WHY? I had no idea at all.

Any suggestion? Thanks.

Body:
I found pingsutw's answer in https://discuss.tvm.apache.org/t/import-tvm-returns-runtime-error-cant-find-libtvm-so-when-using-docker-demo-cpu-image/5110. After referring to his advice, I tried rebuilding tvm in a container launched from the image tvm.ci_cpu:latest which built by myself.

pushd path/to/tvm && \
    chmod +x 3rdparty/libbacktrace/configure && \
    mkdir -p cmake-build && \
    cmake -H. -Bcmake-build -DUSE_LLVM=ON && \
    cmake --build cmake-build --target all -- -j 4 && \
    mv cmake-build build && \
    popd

After the above, I tried typing the command python3 -m tvm.driver.tvmc --help and got the following output.

usage: tvmc [-v] [--version] [-h] {run,tune,compile} ...

TVM compiler driver

optional arguments:
  -v, --verbose       increase verbosity
  --version           print the version and exit
  -h, --help          show this help message and exit.

commands:
  {run,tune,compile}
    run               run a compiled module
    tune              auto-tune a model
    compile           compile a model.

TVMC - TVM driver command-line interface

As you can see it works now.

Surprisingly, libtvm.so and libtvm_runtime.so are not pre-built in the tvm docker image. Maybe the third-party tvm docker image is broken. Maybe the Dockerfile for building tvm docker image should be updated. Maybe it is designed to be flexibly compiled to meet various needs.


问:
how to call data from database to view by user_role laratrust
I use laratrust as my user role, in the user role there are 1 = superadministrator, 2 = administrator, 3 = perusahaan, then I want to display the names of existing perusahaan in my view, which means calling user = role id 3, then how to call it? I also don't really understand eloquent relationships</p>

答:
You need to get users in this way

```<code>// This will return the users with 'superadministrator' role.
$users = User::whereRoleIs('superadministrator')->get();
</code>```

check the documentation

Body:
You need to get users in this way

// This will return the users with 'superadministrator' role.
$users = User::whereRoleIs('superadministrator')->get();

check the documentation


问:
No such module 'IQKeyboardManagerSwift'
New to Xcode (dabble a little). I paid a developer to build an iOS app for me. He sent me the source code and I have opened it in Xcode 13.2.1. I needed to edit the info.plist to include a description why location was required (got this done). When I try to run the build, I get the error 'no such module 'IQKeyboardManagerSwift'. In AppDelegate, I see 'import IQKeyboardManagerSwift --- No such module 'IQKeyboardManagerSwift'. I went to the Podfile directory and ran 'pod install'. Output says:

Analyzing dependencies

Downloading dependencies

Generating Pods project

Integrating client project

Pod installation complete! There are 7 dependencies from the Podfile and 8 total pods installed.

I'm still getting the error when trying to run the build. I tried cleaning the build folder and running the build again but still, same error. What am I missing?

答: I'm not sure why this happens, but one way to solve your issue is to go into your build settings and define the Framework Search Paths to a folder that contains the frameworks in question. If the frameworks are placed in your project directory, simply set the framework search path to $(SRCROOT) and set it to recursive.</p>

Title: No such module 'IQKeyboardManagerSwift'


问:
VBA Inserts extra parenthesis when copying Module to Another WorkBook
So as the title states VBA is adding an extra set of parenthesis after it moves code over. Why does it do this? And how do i make it stop?

Here is code moving the module:

```<code>Set src = ThisWorkbook.VBProject.VBComponents("Module2").CodeModule
Set dest = ActiveWorkbook.VBProject.VBComponents("Sheet2") _
.CodeModule

dest.DeleteLines 1, dest.CountOfLines
dest.AddFromString src.Lines(1, src.CountOfLines)
</code>```

Here is the code after the output:

```<code>Private Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long

 Private Sub MESSAGEBERX()
      MsgBox ("You did it")
 End Sub
 ()
</code>```

EDIT

turns out I left out the the stuff at the top. It also turns out that the culprit was it. Is it due to the "private function" part? I am still messing around with it but still cant get it to move over without the extra parentheses...

答:
I've had the same problem.
Another workaround is to make the declare part at the top one line, i.e., without "_".</p>

Body:
So as the title states VBA is adding an extra set of parenthesis after it moves code over. Why does it do this? And how do i make it stop?

Here is code moving the module:

Set src = ThisWorkbook.VBProject.VBComponents("Module2").CodeModule
Set dest = ActiveWorkbook.VBProject.VBComponents("Sheet2") _
.CodeModule

dest.DeleteLines 1, dest.CountOfLines
dest.AddFromString src.Lines(1, src.CountOfLines)

Here is the code after the output:

Private Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long

 Private Sub MESSAGEBERX()
      MsgBox ("You did it")
 End Sub
 ()

EDIT

turns out I left out the the stuff at the top. It also turns out that the culprit was it. Is it due to the "private function" part? I am still messing around with it but still cant get it to move over without the extra parentheses...


问:
Select a specific row with the following rows sorted by some value in PostgreSQL
I have a table with id and value:

```<code>id value
1  30
2  20
3  10
4  50
5  30
6  40
</code>```

I want to select a row by id with the following rows sorted by value. If multiple rows have the same value, sort them by id. Technically, it is similar to this question, with the difference that not only the nearest row, but also more.

For example, row with id = 2 with the following three rows:

```<code>id value
2  20
1  30
5  30
6  40
</code>```

I know there are window functions for this, but I don't know which ones to use.

答:
SQL:

```<code>with CTE
as
(
select distinct value from tab order by 1
)
select * from tab where value in (select * from cte where value >= (select value from tab where id=2 ) limit 3) ;
</code>```

Edit 1:
SQL:

```<code>with CTE
as
(
select distinct value from tab order by 1
)
Select * from (select * from tab where value in (select * from cte where value > (select value from tab where id=5 ))  limit 3) subq
union all
select * from tab where id=5;

</code>```

dbfiddle link

Body:
I have a table with id and value:

id value
1  30
2  20
3  10
4  50
5  30
6  40

I want to select a row by id with the following rows sorted by value. If multiple rows have the same value, sort them by id. Technically, it is similar to this question, with the difference that not only the nearest row, but also more.

For example, row with id = 2 with the following three rows:

id value
2  20
1  30
5  30
6  40

I know there are window functions for this, but I don't know which ones to use.

Body:
SQL:

with CTE
as
(
select distinct value from tab order by 1
)
select * from tab where value in (select * from cte where value >= (select value from tab where id=2 ) limit 3) ;

Edit 1:
SQL:

with CTE
as
(
select distinct value from tab order by 1
)
Select * from (select * from tab where value in (select * from cte where value > (select value from tab where id=5 ))  limit 3) subq
union all
select * from tab where id=5;

dbfiddle link


问:
Download a single folder or directory from a GitHub repo
How can I download only a specific folder or directory from a remote Git repo hosted on GitHub?

Say the example GitHub repo lives here:

```<code>git@github.com:foobar/Test.git
</code>```

Its directory structure:

```<code>Test/
├── foo/
│   ├── a.py
│   └── b.py
└── bar/
    ├── c.py
    └── d.py
</code>```

I want to download only the foo folder and not clone the whole Test project.

答:
You cannot; unlike Subversion, where each subdirectory can be checked out individually, Git operates on a whole-repository basis.

For projects where finer-grained access is necessary, you can use submodules -- each submodule is a separate Git project, and thus can be cloned individually.

It is conceivable that a Git front-end (e.g. GitHub's web interface, or gitweb) could choose to provide an interface for you to extract a given folder, but to my knowledge none of them do that (though they do let you download individual files, so if the folder does not contain too many files, that is an option)

Edit - GitHub actually offers access via SVN, which would allow you to do just this (as per comment). See https://github.com/blog/1438-improved-svn-here-to-stay-old-svn-going-away for latest instructions on how to do this

Body:
How can I download only a specific folder or directory from a remote Git repo hosted on GitHub?

Say the example GitHub repo lives here:

git@github.com:foobar/Test.git

Its directory structure:

Test/
├── foo/
│   ├── a.py
│   └── b.py
└── bar/
    ├── c.py
    └── d.py

I want to download only the foo folder and not clone the whole Test project.


问:
What is the exact list of Ansible setup min?
According to the Ansible documentation, the setup module is

This module is automatically called by playbooks to gather useful variables about remote hosts that can be used in playbooks. It can also be executed directly by /usr/bin/ansible to check what variables are available to a host. Ansible provides many facts about the system, automatically.

And there are some parameters which include gather_subset.

If supplied, restrict the additional facts collected to the given subset. Possible values: all, min, hardware, network, virtual, ohai, and facter. Can specify a list of values to specify a larger subset. Values can also be used with an initial ! to specify that that specific subset should not be collected. For instance: !hardware,!network,!virtual,!ohai,!facter. If !all is specified then only the min subset is collected. To avoid collecting even the min subset, specify !all,!min. To collect only specific facts, use !all,!min, and specify the particular fact subsets. Use the filter parameter if you do not want to display some collected facts.

I want to know the exact list of fact that min subset would collect.

Thanks

答:
Q: "I want to know the exact list of facts that the "min" subset would collect."

A: Run the module separately by ansible. You'll see the list of the facts collected by this module

shell> ansible localhost -m setup -a 'gather_subset=min'
```
<hr>
<p>As a side note, the facts differ among the systems. For example, compare the collected minimal facts among FreeBSD and Ubuntu</p>
<pre class="lang-sh prettyprint-override"><code>shell> grep PRETTY_NAME /etc/os-release
PRETTY_NAME="FreeBSD 13.0-RELEASE"
</code>```

Store the output in a file

shell> ansible localhost -m setup -a 'gather_subset=min' > /scratch/freebsd.json
shell> cat /scratch/freebsd.json
localhost | SUCCESS => {
    "ansible_facts": {
```
<p>Remove 'localhost | SUCCESS => ` from the file</p>
<pre class="lang-sh prettyprint-override"><code>shell> cat /scratch/freebsd.json
{
    "ansible_facts": {
</code>```

Create a file with the keys (variables) only

shell> cat freebs.json | jq '.ansible_facts | keys[]' > freebsd_keys.txt
```
<p>Repeat the procedure in Ubuntu and create ubuntu_keys.txt</p>
<pre class="lang-sh prettyprint-override"><code>shell> grep DISTRIB_DESCRIPTION /etc/lsb-release
DISTRIB_DESCRIPTION="Ubuntu 20.04.2 LTS"
</code>```

Diff the files

shell> diff ubuntu_keys.txt freebsd_keys.txt
3d2
< "ansible_cmdline"
6,8d4
< "ansible_distribution_file_parsed"
< "ansible_distribution_file_path"
< "ansible_distribution_file_variety"
25d20
< "ansible_machine_id"
29d23
< "ansible_proc_cmdline"
44,45d37
< "ansible_system_capabilities"
< "ansible_system_capabilities_enforced"
52d43
< "ansible_userspace_architecture"
```
<hr>
<p>There are also differences among the Linux distributions. For example, Ubuntu 20.04 and Centos 8</p>
<pre class="lang-sh prettyprint-override"><code>shell> diff ubuntu_keys.txt centos_keys.txt
38d37
< "ansible_ssh_host_key_ecdsa_public_keytype"
40d38
< "ansible_ssh_host_key_ed25519_public_keytype"
42d39
< "ansible_ssh_host_key_rsa_public_keytype"
</code>```

Body:
Q: "I want to know the exact list of facts that the "min" subset would collect."

A: Run the module separately by ansible. You'll see the list of the facts collected by this module

shell> ansible localhost -m setup -a 'gather_subset=min'

As a side note, the facts differ among the systems. For example, compare the collected minimal facts among FreeBSD and Ubuntu

shell> grep PRETTY_NAME /etc/os-release
PRETTY_NAME="FreeBSD 13.0-RELEASE"

Store the output in a file

shell> ansible localhost -m setup -a 'gather_subset=min' > /scratch/freebsd.json
shell> cat /scratch/freebsd.json
localhost | SUCCESS => {
    "ansible_facts": {

Remove 'localhost | SUCCESS => ` from the file

shell> cat /scratch/freebsd.json
{
    "ansible_facts": {

Create a file with the keys (variables) only

shell> cat freebs.json | jq '.ansible_facts | keys[]' > freebsd_keys.txt

Repeat the procedure in Ubuntu and create ubuntu_keys.txt

shell> grep DISTRIB_DESCRIPTION /etc/lsb-release
DISTRIB_DESCRIPTION="Ubuntu 20.04.2 LTS"

Diff the files

shell> diff ubuntu_keys.txt freebsd_keys.txt
3d2
< "ansible_cmdline"
6,8d4
< "ansible_distribution_file_parsed"
< "ansible_distribution_file_path"
< "ansible_distribution_file_variety"
25d20
< "ansible_machine_id"
29d23
< "ansible_proc_cmdline"
44,45d37
< "ansible_system_capabilities"
< "ansible_system_capabilities_enforced"
52d43
< "ansible_userspace_architecture"

There are also differences among the Linux distributions. For example, Ubuntu 20.04 and Centos 8

shell> diff ubuntu_keys.txt centos_keys.txt
38d37
< "ansible_ssh_host_key_ecdsa_public_keytype"
40d38
< "ansible_ssh_host_key_ed25519_public_keytype"
42d39
< "ansible_ssh_host_key_rsa_public_keytype"


问:
how to hide onStepContinue button for the last step and onStepCancel for the first step on flutter?
This is my first time on flutter framework and Dart programming I have so manny miss of understanding Dart language.

I want to hide onStepContinue button for the last step and onStepCancel for the first step on flutter? this is my code I'm newbe in flutter any help?

```<code>class _MyHomePageState extends State<MyHomePage> {
  int _currentStep = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Stepper(
          controlsBuilder: (BuildContext context, ControlsDetails details) {
            return Row(
              children: <Widget>[
              TextButton(
                onPressed: details.onStepContinue,
                child: const Text('NEXT'),
              ),
              TextButton(
                onPressed: details.onStepCancel,
                child: const Text('BACK'),
              ),
            ],
            );
          },
          steps: const [
            Step(
              title: Text("Step 1"),
              content: Text("Information for step 1"),
            ),
            Step(
              title: Text("Step 2"),
              content: Text("Information for step 2"),
            ),
            Step(
              title: Text("Step 3"),
              content: Text("Information for step 3"),
            ),
          ],
          onStepTapped: (int newIndex){
            setState(() {
              _currentStep = newIndex;
            });
          },
          currentStep: _currentStep,
          onStepContinue: () {
            if (_currentStep != 2) {
              setState(() {
                _currentStep += 1;
              });
            }
          },
          onStepCancel: () {
            if (_currentStep != 0) {
              setState(() {
                _currentStep -= 1;
              });
            }
          },
        ),
      ),
    );
  }
}
</code>```

答:
Wrap your widget using Visibility like this,

```<code>bool goneVisibilty=true;

Visibility(
  child: Text("Gone"),//replace with your widget
  visible: goneVisibility,
),
</code>```

when ever u need to update this widget call setState to update.

```<code>setState((){
goneVisibility=false;
});
</code>```

Body:
This is my first time on flutter framework and Dart programming I have so manny miss of understanding Dart language.

I want to hide onStepContinue button for the last step and onStepCancel for the first step on flutter? this is my code I'm newbe in flutter any help?

class _MyHomePageState extends State<MyHomePage> {
  int _currentStep = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Stepper(
          controlsBuilder: (BuildContext context, ControlsDetails details) {
            return Row(
              children: <Widget>[
              TextButton(
                onPressed: details.onStepContinue,
                child: const Text('NEXT'),
              ),
              TextButton(
                onPressed: details.onStepCancel,
                child: const Text('BACK'),
              ),
            ],
            );
          },
          steps: const [
            Step(
              title: Text("Step 1"),
              content: Text("Information for step 1"),
            ),
            Step(
              title: Text("Step 2"),
              content: Text("Information for step 2"),
            ),
            Step(
              title: Text("Step 3"),
              content: Text("Information for step 3"),
            ),
          ],
          onStepTapped: (int newIndex){
            setState(() {
              _currentStep = newIndex;
            });
          },
          currentStep: _currentStep,
          onStepContinue: () {
            if (_currentStep != 2) {
              setState(() {
                _currentStep += 1;
              });
            }
          },
          onStepCancel: () {
            if (_currentStep != 0) {
              setState(() {
                _currentStep -= 1;
              });
            }
          },
        ),
      ),
    );
  }
}

Body:
Wrap your widget using Visibility like this,

bool goneVisibilty=true;

Visibility(
  child: Text("Gone"),//replace with your widget
  visible: goneVisibility,
),

when ever u need to update this widget call setState to update.

setState((){
goneVisibility=false;
});


问:
Migrating mongo atlas database to Azure data lake storage
I have a use case to migrate mongo cluster on mongo atlas to ADLS Gen 2. I setup a Azure data factory pipeline to test feasibility with 2.9GB data. It took ~18 min with average speed of 2.6MBps. Considering our entire DB is around 10TB in size this speed is not optimal and it would take weeks for the migration

My question is:

Is there a faster way of migrating. It doesn't have to be using data
factory, I simply searched for options and decided to try it out with
ADFS and am open to other tools if the performance is better

In ADFS
I notice one needs to specify collection. But I would be interested
in just specifying the database so the copy option will copy all
collections. Is that option supported or specifying collection is
mandatory?

EDIT:
I updated DIU and parallelCopies attribute but it didn't make any difference to the total time

答:
You can use any of the Copy performance optimization feature to enhance the performance of migration process.

The below image shows the achievable performance.

Also refer Performance tuning steps.

If alone DIU and ParallelCopy not working, you need to use a more powerful compute environment, i.e., Azure IR.

Create a new Azure IR by following this tutorial: create and configure Azure Integration Runtime. Make sure your Region should be near to your stored data location. Under Compute type use Memory Optimized and Core count would be 16 ( + 16 Driver cores) or more.

See the below image for your reference.

Use this newly created IR to run your pipeline. This should work.


问:
How to use two svelte componenets on different pages with distinct ids?
I'd like to use two unrelated svelte compoents on two distincpages of a website say  /cats and /dogs so in main.js I have

```<code>import App from './App.svelte'; //this is empty

import ListCats from './ListCats.svelte';

import ListDogs from './ListDogs.svelte';

new ListCats({
  target: document.querySelector('#list-cats'),
});

new ListDogs({
  target: document.querySelector('#list-dogs'),
});

const app = new App({
    target: document.body
});

export default app;
</code>```

The prblem is that error:

```<code>Uncaught Error: 'target' is a required option
    at new SvelteComponentDev (index.mjs:1993:19)
    at new ListDogs (ListDogs.svelte:76:39)
    at main.js:9:1
    at main.js:24:2
</code>```

This arises becasue /cats page does not have #list-dogs and /dogs does not have #list-cats and both pages import the same bundle.js of svelte.

How can I avoid this problem?

答:
try</p>
```<code>let target = document.querySelector('#list-cats');
if (target) new ListCats({ target });

target = document.querySelector('#list-dogs');
if (target) new ListDogs({ target });
</code>```

Body:
I'd like to use two unrelated svelte compoents on two distincpages of a website say  /cats and /dogs so in main.js I have

import App from './App.svelte'; //this is empty

import ListCats from './ListCats.svelte';

import ListDogs from './ListDogs.svelte';

new ListCats({
  target: document.querySelector('#list-cats'),
});

new ListDogs({
  target: document.querySelector('#list-dogs'),
});

const app = new App({
    target: document.body
});

export default app;

The prblem is that error:

Uncaught Error: 'target' is a required option
    at new SvelteComponentDev (index.mjs:1993:19)
    at new ListDogs (ListDogs.svelte:76:39)
    at main.js:9:1
    at main.js:24:2

This arises becasue /cats page does not have #list-dogs and /dogs does not have #list-cats and both pages import the same bundle.js of svelte.

How can I avoid this problem?

Body:
try

let target = document.querySelector('#list-cats');
if (target) new ListCats({ target });

target = document.querySelector('#list-dogs');
if (target) new ListDogs({ target });


问:
Check whether string is a date Postgresql
Is there any function in PostgreSQL that returns Boolean whether a given string is a date or not just like ISDATE() in MSSQL?

```<code>ISDATE("January 1, 2014")
</code>```

答:
@ntalbs answer is good except in the case of NULL values. I don't want is_date to return true if I pass it a NULL value. This tweak gets around that issue:

```<code>create or replace function is_date(s varchar) returns boolean as $$
begin
  if s is null then
     return false;
  end if;
  perform s::date;
  return true;
exception when others then
  return false;
end;
$$ language plpgsql;
</code>```

Body:
Is there any function in PostgreSQL that returns Boolean whether a given string is a date or not just like ISDATE() in MSSQL?

ISDATE("January 1, 2014")

Body:
@ntalbs answer is good except in the case of NULL values. I don't want is_date to return true if I pass it a NULL value. This tweak gets around that issue:

create or replace function is_date(s varchar) returns boolean as $$
begin
  if s is null then
     return false;
  end if;
  perform s::date;
  return true;
exception when others then
  return false;
end;
$$ language plpgsql;


问:
GitLab Disastry Recovery DB read-only issue
We are setting up GitLab - DR, we have replicated secondary slave from primary Postgres database.

But we are getting READ ONLY issues since DB slave is in read only mode, we can't make DB- READ WRITE since it's secondary.

What should be the standard way to proceed with DR setup for GitLab?

答:
It depends on what you are setting up for GitLab DR: Geo is the official solution since Nov. 2017 (GitLab 10.4)

If you are using Geo (premium or ultimate GitLab instance only), then the documentation would suggest:

The GitLab primary node where the write operations happen will connect to the primary database server, and the secondary nodes which are read-only will connect to the secondary database servers (which are also read-only).

Note:

In database documentation, you may see "primary" being referenced as "master"
and "secondary" as either "slave" or "standby" server (read-only).

We recommend using PostgreSQL replication slots to ensure that the primary retains all the data necessary for the secondaries to recover.

So make sure those replication slots are properly configured.


问:
Has anything changed regarding the background location service in Xamarin.ios?
I'm using Xamarin Forms to develop a solution that needs a permanent background service, which also uses locations. I've  ticked background mode, fetch and always on, but the location updates become less frequent with time. After 20 mins of background processing, the location updates seem random, ranging from 5mins to 1h. Not sure what I'm doing wrong.</p>
```<code>public class LocationManager
    {
        protected CLLocationManager locMgr;
        public event EventHandler<LocationUpdatedEventArgs> LocationUpdated = delegate { };
        public LocationManager()
        {
            locMgr = new CLLocationManager();
            LocMgr.DesiredAccuracy = CLLocation.AccurracyBestForNavigation;
            locMgr.PausesLocationUpdatesAutomatically = false;

            locMgr.ActivityType = CLActivityType.AutomotiveNavigation;
            locMgr.DistanceFilter = CLLocationDistance.FilterNone ;

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                this.locMgr.RequestAlwaysAuthorization();
            }

            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                this.locMgr.AllowsBackgroundLocationUpdates = true;
            }

           LocMgr.StartUpdatingLocation();
        }

        public async void StartLocationUpdates()
        {

            if (CLLocationManager.LocationServicesEnabled)
            {
               if (LocMgr != null)
                {
                    if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
                    {
                        LocMgr.LocationsUpdated += LocationsUpdated;
                    }
                    else
                    {
                        LocMgr.UpdatedLocation += LocationsNewUpdated;
                    }

                    LocMgr.StartUpdatingLocation();

                    LocMgr.Failed += (object sender, NSErrorEventArgs e) => {
                        Console.WriteLine(e.Error);
                    };
                }
            }
            else
            {
                Console.WriteLine("Location services not enabled");
            }
    }
}
</code>```

答:
CLLocationManager provides many options for filtering and configuring location data, including the frequency of updates. In this example, set the DesiredAccuracy to update whenever the location changes by a meter. For more information on configuring location update frequency and other preferences, refer to the CLLocationManager Class Reference in the Apple documentation: https://developer.apple.com/documentation/corelocation/cllocationmanager

```<code>if (CLLocationManager.LocationServicesEnabled) {
    //set the desired accuracy, in meters
    LocMgr.DesiredAccuracy = 1;
    LocMgr.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) =>
    {
        // fire our custom Location Updated event
        LocationUpdated (this, new LocationUpdatedEventArgs (e.Locations [e.Locations.Length - 1]));
    };
    LocMgr.StartUpdatingLocation();
}
</code>```

Sample link: https://learn.microsoft.com/en-us/samples/xamarin/ios-samples/location/

Body:
I'm using Xamarin Forms to develop a solution that needs a permanent background service, which also uses locations. I've  ticked background mode, fetch and always on, but the location updates become less frequent with time. After 20 mins of background processing, the location updates seem random, ranging from 5mins to 1h. Not sure what I'm doing wrong.

public class LocationManager
    {
        protected CLLocationManager locMgr;
        public event EventHandler<LocationUpdatedEventArgs> LocationUpdated = delegate { };
        public LocationManager()
        {
            locMgr = new CLLocationManager();
            LocMgr.DesiredAccuracy = CLLocation.AccurracyBestForNavigation;
            locMgr.PausesLocationUpdatesAutomatically = false;

            locMgr.ActivityType = CLActivityType.AutomotiveNavigation;
            locMgr.DistanceFilter = CLLocationDistance.FilterNone ;

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                this.locMgr.RequestAlwaysAuthorization();
            }

            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                this.locMgr.AllowsBackgroundLocationUpdates = true;
            }

           LocMgr.StartUpdatingLocation();
        }

        public async void StartLocationUpdates()
        {

            if (CLLocationManager.LocationServicesEnabled)
            {
               if (LocMgr != null)
                {
                    if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
                    {
                        LocMgr.LocationsUpdated += LocationsUpdated;
                    }
                    else
                    {
                        LocMgr.UpdatedLocation += LocationsNewUpdated;
                    }

                    LocMgr.StartUpdatingLocation();

                    LocMgr.Failed += (object sender, NSErrorEventArgs e) => {
                        Console.WriteLine(e.Error);
                    };
                }
            }
            else
            {
                Console.WriteLine("Location services not enabled");
            }
    }
}

Body:
CLLocationManager provides many options for filtering and configuring location data, including the frequency of updates. In this example, set the DesiredAccuracy to update whenever the location changes by a meter. For more information on configuring location update frequency and other preferences, refer to the CLLocationManager Class Reference in the Apple documentation: https://developer.apple.com/documentation/corelocation/cllocationmanager

if (CLLocationManager.LocationServicesEnabled) {
    //set the desired accuracy, in meters
    LocMgr.DesiredAccuracy = 1;
    LocMgr.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) =>
    {
        // fire our custom Location Updated event
        LocationUpdated (this, new LocationUpdatedEventArgs (e.Locations [e.Locations.Length - 1]));
    };
    LocMgr.StartUpdatingLocation();
}

Sample link: https://learn.microsoft.com/en-us/samples/xamarin/ios-samples/location/


问:
Apollo mutate without Hook in React custom Hook
I'm calling a custom hook within a React Component:

```<code>const [CallMe, { loading, data, error }] = useCustomHook({
    onCompleted(res) {
        console.log(res)
    },
    onError(err) {
        console.log(err)
    },
})
</code>```

Which is initiated via an onClick event:

```<code>onClick={() => CallMe() }
</code>```

The custom hook consists of the following:

```<code>export function useCustomHook({ onCompleted, onError }) {

/**
 * Use State
 */

const [loading, setLoading] = useState(false)
const [data, setData] = useState(null)
const [error, setError] = useState(null)

/**
 * Get Thing
 */

function GetThing() {
    setLoading(true)
    callExternalApi
        .method()
        .then(({ data, error }) => {
            setLoading(false)
            if (error) {
                setError(error)
                onError(error)
            }
            if (data) {
                CALL TO MUTATION NEEDED HERE (NON HOOK)
            }
        })
}

return [GetThing, { loading: loading, data: data, error: error }]
}
</code>```

When data has successfully been returned I want to fire a Mutation, however I don't want this to be done via the useMutation Apollo hook.

Therefore my question is how would I fire this mutation in a none hook manner that will still allow me to update the Apollo Cache on response all within this custom hook?

I understand that I can simply do a HTTP request via Fetch, but this wont give me the inMemoryCache advantage that Im using with throughout the app. Would I have to intializeApollo within the custom hook?

Any thoughts or suggestions are welcome.

答:
It would appear that within my custom hook I can import Apollo Client, this then gives me the ability to use mutations and queries.

```<code>import { useApolloClient } from '@apollo/client'
</code>```

Then within your exported custom hook:

```<code>client
        .mutate({
            mutation:MUTATION,
            variables: {
                Input: input,
            },
        })
        .catch((error) => {
            console.log(error)
        })
        .then((result) => {
            console.log(result)})
</code>```

Body:
I'm calling a custom hook within a React Component:

const [CallMe, { loading, data, error }] = useCustomHook({
    onCompleted(res) {
        console.log(res)
    },
    onError(err) {
        console.log(err)
    },
})

Which is initiated via an onClick event:

onClick={() => CallMe() }

The custom hook consists of the following:

export function useCustomHook({ onCompleted, onError }) {

/**
 * Use State
 */

const [loading, setLoading] = useState(false)
const [data, setData] = useState(null)
const [error, setError] = useState(null)

/**
 * Get Thing
 */

function GetThing() {
    setLoading(true)
    callExternalApi
        .method()
        .then(({ data, error }) => {
            setLoading(false)
            if (error) {
                setError(error)
                onError(error)
            }
            if (data) {
                CALL TO MUTATION NEEDED HERE (NON HOOK)
            }
        })
}

return [GetThing, { loading: loading, data: data, error: error }]
}

When data has successfully been returned I want to fire a Mutation, however I don't want this to be done via the useMutation Apollo hook.

Therefore my question is how would I fire this mutation in a none hook manner that will still allow me to update the Apollo Cache on response all within this custom hook?

I understand that I can simply do a HTTP request via Fetch, but this wont give me the inMemoryCache advantage that Im using with throughout the app. Would I have to intializeApollo within the custom hook?

Any thoughts or suggestions are welcome.

Body:
It would appear that within my custom hook I can import Apollo Client, this then gives me the ability to use mutations and queries.

import { useApolloClient } from '@apollo/client'

Then within your exported custom hook:

client
        .mutate({
            mutation:MUTATION,
            variables: {
                Input: input,
            },
        })
        .catch((error) => {
            console.log(error)
        })
        .then((result) => {
            console.log(result)})


问:
Any reason C#'s List<T> Class, not having save or update method?
C#'s List<T> class here doesn't have a Save() or Update() method. Is there any technical reason behind this?

What @MarcGravell & @Charles mentioned in Answer/Comment section, is something I'm trying to do.

If the question is clear to @MarcGravell & @Charles, I'm wondering what makes individuals like @Llama to make pretty easy statement "Question does not make sense"? Is this some kind trick to close the ticket & reduce one's workload?

To be even more specific, how to update & save the changes to specific item in the collection?

答:
If by Save() or Update() you mean some kind of database backend, perhaps persisting the changes, then:

A list has no concept of a database

Most lists aren't involved in anything related to a database

Adding the tracking necessary would significantly increase the memory required, and decrease the performance

For a feature that isn't required basically all of the time

And which would require vastly different logic for different kinds of backend storage, which the list can't know about

If you want this kind of feature: use an ORM such as EF, LLBLGenPro, or anything else. That's what they provide. A list is basically a fancy veneer over an oversized array, and nothing else, which is fine: because most of the time, that's what you want.


问:
same data provider for chart and data grid
I want to display the same data in a chart and a data grid. I want to use the same data provider for both of them to reduce the amount of SQL queries.

How do I transform the database structure into the chart structure and into the table structure using ActionScript?*

Database structure in JSON format:

```<code>[
    {key:, year:, value:},
    {key:, year:, value:}
]
</code>```

Data provider structure required by a chart:

```<code>[
    {series1:, series2:, year:},
    {series1:, series2:, year:}
]
</code>```

Data provider structure required by data grid:

```<code>[
    {key:, year2000:, year2001:, ...},
    {key:, year2000:, year2001:, ...}
]
</code>```

答:
You can create a simple  Util Class that parse the data and return  it a specidic componenet

for example

dataGrid.dataProvider = DataUtil.parseForDG(SQLData);
chatData = DataUtil.parseForChat(SQLData);

etc.....

Body:
I want to display the same data in a chart and a data grid. I want to use the same data provider for both of them to reduce the amount of SQL queries.

How do I transform the database structure into the chart structure and into the table structure using ActionScript?*

Database structure in JSON format:

[
    {key:, year:, value:},
    {key:, year:, value:}
]

Data provider structure required by a chart:

[
    {series1:, series2:, year:},
    {series1:, series2:, year:}
]

Data provider structure required by data grid:

[
    {key:, year2000:, year2001:, ...},
    {key:, year2000:, year2001:, ...}
]


问:
how to create responsive webcam cards that grows and shrinks following the number of people?
I'm learning Django so I'm a bit off on the front-end and i was hoping i can find help

I want to create a video chat website where a bunch of people can join the chat room, but I'm stuck with the UI.

I'm looking to make the first cam (mine) big until someone else joins and they get shrunk to the same size.

Also, I'd like the size of everything to be the height of the page, The size of the webcam shrinks and not the other way around.

I searched everywhere for a template but I haven't found
I couldn't even deliver my question to google

答:
Its very simple first just collect the no. of people and using python print this logic in between of the page

first collect the no. of people and store in a variable suppose a
after this if a updates by +1 then print div with height (height of the container in which webcam cards are there)px / a and width (width of the container in which webcam cards are there)px / a this will change the size of the div.

I hope you find it correct. I do not know Django but logics are same in every language. So, I have just told you the logic and now you can frame your code :)


问:
Find the last value in a "rolled-over" sequence with a stored procedure?
Suppose I had a set of alpha-character identifiers of a set length, e.g. always five letters, and they are assigned in such a way that they are always incremented sequentially (GGGGZ --> GGGHA, etc.).   Now, if I get to ZZZZZ, since the length is fixed, I must "roll over" to AAAAA.  I might have a contiguous block from ZZZAA through AAAAM.  I want to write a sproc that will give me the "next" identifier, in this case AAAAN.

If I didn't have this "rolling over" issue, of course, I'd just ORDER BY DESC and grab the top result.  But I'm at a bit of a loss now -- and it doesn't help at all that SQL is not my strongest language.

If I have to I can move this to my C# calling code, but a sproc would be a better fit.

ETA: I would like to avoid changing the schema (new column or new table); I'd rather just be able to "figure it out".  I might even prefer to do it brute force (e.g. start at the lowest value and increment until I find a "hole"), even though that could get expensive.  If you have an answer that does not modify the schema, it'd be a better solution for my needs.

答: I think I'd have tried to store the sequence as an integer, then translate it to string. Or else store a parallel integer column that is incremented at the same time as the alpha value. Either way, you could sort on the integer column.</p>

OwnerDisplayName: Coderer

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Coderer

OwnerDisplayName: John Saunders


问:
How to handle youtube api method errors in python?
When I do the PlaylistItems.insert() method, how can I handle the videoNotFound error? In addition, how can I handle other errors at the same time like IndexError?

```<code>try:
    result = youtube.playlistItems().insert(
        part = "snippet",
        body = {
            "snippet": {
                "playlistId": MY_PLAYLIST_ID,
                "resourceId": {
                    "kind": "youtube#video",
                    "videoId": MY_VIDEO_ID
                }
            }
        }
    ).execute()
    print(my_list[100])
except:
    #handle videoNotFound error
    #handle print(my_list[100]) if it raises an Index Error
</code>```

答:
I found my answer on the google api client for python here.</p>
```<code>import googleapiclient.errors
try:
    result = youtube.playlistItems().insert(
        part = "snippet",
        body = {
            "snippet": {
                "playlistId": MY_PLAYLIST_ID,
                "resourceId": {
                    "kind": "youtube#video",
                    "videoId": MY_VIDEO_ID
                }
            }
        }
    ).execute()
    print(my_list[100])
except googleapiclient.errors.HttpError as e:
    if e.error_details[0]["reason"] == "videoNotFound":
        print("Video not found.")
except IndexError:
    print("IndexError occurred")
</code>```

Body:
When I do the PlaylistItems.insert() method, how can I handle the videoNotFound error? In addition, how can I handle other errors at the same time like IndexError?

try:
    result = youtube.playlistItems().insert(
        part = "snippet",
        body = {
            "snippet": {
                "playlistId": MY_PLAYLIST_ID,
                "resourceId": {
                    "kind": "youtube#video",
                    "videoId": MY_VIDEO_ID
                }
            }
        }
    ).execute()
    print(my_list[100])
except:
    #handle videoNotFound error
    #handle print(my_list[100]) if it raises an Index Error

Body:
I found my answer on the google api client for python here.

import googleapiclient.errors
try:
    result = youtube.playlistItems().insert(
        part = "snippet",
        body = {
            "snippet": {
                "playlistId": MY_PLAYLIST_ID,
                "resourceId": {
                    "kind": "youtube#video",
                    "videoId": MY_VIDEO_ID
                }
            }
        }
    ).execute()
    print(my_list[100])
except googleapiclient.errors.HttpError as e:
    if e.error_details[0]["reason"] == "videoNotFound":
        print("Video not found.")
except IndexError:
    print("IndexError occurred")