问:
How to read highspeed Serial-data using Python?
I am working on a project to display sensor data on Python GUI. Sensor data is coming at a rate of 2kHz on serial port using Arduino. I was using pyserial (using readline()) to read the sensor data on my laptop. After hours of debugging I found that python was able to read around 400 samples/sec i.e. reading frequency is around 400Hz.

Is there any way to read the serial data at higher rate with the help of python?

Thanks in Advance.

答:
Assuming the sensor is designed to transmit 2kHz data and is doing so properly, my guess is that the time your Python code is taking to read a data sample, process the data, update a plot, etc is the limiting factor. Are you reading and processing samples one at a time?  Is there a smart way to read all of the available in a big chunk reducing the number of individual read/process steps?

Are you plotting the data in "real time"? If so, plot updates are slow.


来源: stackexchange

问:
Toggle style properties with JavaScript by commenting-out CSS attributes
I want to send a list of properties to a function that will temporarily disable (via comments) those properties.  The purpose is similar to what is accomplished by Chrome Dev Tools when inspecting the style of an element, except that the user will not check/uncheck boxes, instead, the action will be performed by JavaScript.

```<code>function disableProperties(el, properties) {
    var property; // property value pair
    var cssStr = el.style.cssText.replace(/; /g, ";");

    for (let i = 0; i < properties.length; i++) {
        property = properties[i] + ": " + eval("el.style." + properties[i]) + ";";
        cssStr = cssStr.replace(property, "/* " + property + " */");
    }

    el.setAttribute("style", cssStr);
}

function restoreProperties(el, properties) {
    var outHtml = el.outerHTML;
    var key = 'style="';
    var idx1 = outHtml.indexOf(key) + key.length;
    var idx2 = outHtml.indexOf('"', idx1);
    var style = outHtml.substring(idx1, idx2);

    for (let i = 0; i < properties.length; i++) {
        str = "/* " + properties[i];
        let a = style.indexOf(str);
        let b = style.indexOf(" */", a + a.length) + 3;
        let comment = style.substring(a, b);
        let property = (comment).replace("/*", "").replace("*/", "");

        style = style.replace(comment, property);
    }

    el.style.cssText = style;
}
</code>```

When elements are created, their style is embedded in the HTML instead of external CSS files.  It is important that the properties are only temporarily disabled; their earlier values must be preserved.

UPDATE:
I thought my comment code was not working because I was trying to retrieve the comment by asking for el.style.cssText; however, the comment was only available through outerHTML.

The code below is functional, but I'm sure that could be cleaned up.  If you have suggestions on how I can improve this code, please advise.  Here is a fiddle to demonstrate one example of how I am using the code.

答:
Expanding on Volts deleted answer, use data attributes to store the initial state of your element. You can then that information to reset the values. One catch is that the style property is read only, so if we want to reset all style properties, we have to loop all the properties.

This is much cleaner than hacking comments in and out. This works with styles set inline and with classes.

const disableProperties = (el, properties) => {
  //store the style so we can restore it

  el.dataset.styles = JSON.stringify(el.style);
  console.log(JSON.parse(el.dataset.styles));
  properties.forEach(property => {
    el.style[property] = "unset";
  })
}

const enableProperties = (el, properties) => {
  //Get our saved initial state
  let styles = JSON.parse(el.dataset.styles);
  console.log(styles);
  properties.forEach(property => {
    el.style[property] = styles[property];
  })
}

const restoreAll = (el) => {
  let styles = JSON.parse(el.dataset.styles);
  console.log(styles);
  /*You might think the following line should work, but the styles property is read only*/
  /*el.style = styles;*/
  /*So loop our properties instead*/
  for(prop in styles){
    if(styles.hasOwnProperty(prop)){
      el.style[prop] = styles[prop];
    }
  }
}

document.querySelector('.child').addEventListener("click", function() {
  disableProperties(this.parentNode, ["top", "left"])
})

let enableButtons = document.querySelectorAll(".enable");

for (var i = 0; i < enableButtons.length; i++) {
  enableButtons[i].addEventListener("click", function(event) {
    let property = this.dataset.restore;
    let target = document.querySelector(this.dataset.target);
    enableProperties(target, property.split(","));
  });
}

document.getElementById("restoreAll").addEventListener("click", function() {
  restoreAll(document.querySelector(".parent"));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
  /*top: 50px;*/
  left: 50px;
  position: absolute;
}

.child {
  background: red;
  width: 50px;
  height: 50px;
}

.container {position:relative; height:200px;}</code>```

Click the square before restoring

<button id="restoreLeft" class="enable" data-restore="left" data-target=".parent">Restore Left</button>
<button id="restoreTop" class="enable" data-restore="top" data-target=".parent">Restore top</button>
<button id="restoreAll">RestoreAll</button>```

ContentLicense: CC BY-SA 4.0

Body:
I want to send a list of properties to a function that will temporarily disable (via comments) those properties.  The purpose is similar to what is accomplished by Chrome Dev Tools when inspecting the style of an element, except that the user will not check/uncheck boxes, instead, the action will be performed by JavaScript.

function disableProperties(el, properties) {
    var property; // property value pair
    var cssStr = el.style.cssText.replace(/; /g, ";");

    for (let i = 0; i < properties.length; i++) {
        property = properties[i] + ": " + eval("el.style." + properties[i]) + ";";
        cssStr = cssStr.replace(property, "/* " + property + " */");
    }

    el.setAttribute("style", cssStr);
}

function restoreProperties(el, properties) {
    var outHtml = el.outerHTML;
    var key = 'style="';
    var idx1 = outHtml.indexOf(key) + key.length;
    var idx2 = outHtml.indexOf('"', idx1);
    var style = outHtml.substring(idx1, idx2);

    for (let i = 0; i < properties.length; i++) {
        str = "/* " + properties[i];
        let a = style.indexOf(str);
        let b = style.indexOf(" */", a + a.length) + 3;
        let comment = style.substring(a, b);
        let property = (comment).replace("/*", "").replace("*/", "");

        style = style.replace(comment, property);
    }

    el.style.cssText = style;
}

When elements are created, their style is embedded in the HTML instead of external CSS files.  It is important that the properties are only temporarily disabled; their earlier values must be preserved.

UPDATE:
I thought my comment code was not working because I was trying to retrieve the comment by asking for el.style.cssText; however, the comment was only available through outerHTML.

The code below is functional, but I'm sure that could be cleaned up.  If you have suggestions on how I can improve this code, please advise.  Here is a fiddle to demonstrate one example of how I am using the code.

Body:
Expanding on Volts deleted answer, use data attributes to store the initial state of your element. You can then that information to reset the values. One catch is that the style property is read only, so if we want to reset all style properties, we have to loop all the properties.

This is much cleaner than hacking comments in and out. This works with styles set inline and with classes.

const disableProperties = (el, properties) => {
  //store the style so we can restore it

  el.dataset.styles = JSON.stringify(el.style);
  console.log(JSON.parse(el.dataset.styles));
  properties.forEach(property => {
    el.style[property] = "unset";
  })
}

const enableProperties = (el, properties) => {
  //Get our saved initial state
  let styles = JSON.parse(el.dataset.styles);
  console.log(styles);
  properties.forEach(property => {
    el.style[property] = styles[property];
  })
}

const restoreAll = (el) => {
  let styles = JSON.parse(el.dataset.styles);
  console.log(styles);
  /*You might think the following line should work, but the styles property is read only*/
  /*el.style = styles;*/
  /*So loop our properties instead*/
  for(prop in styles){
    if(styles.hasOwnProperty(prop)){
      el.style[prop] = styles[prop];
    }
  }
}

document.querySelector('.child').addEventListener("click", function() {
  disableProperties(this.parentNode, ["top", "left"])
})

let enableButtons = document.querySelectorAll(".enable");

for (var i = 0; i < enableButtons.length; i++) {
  enableButtons[i].addEventListener("click", function(event) {
    let property = this.dataset.restore;
    let target = document.querySelector(this.dataset.target);
    enableProperties(target, property.split(","));
  });
}

document.getElementById("restoreAll").addEventListener("click", function() {
  restoreAll(document.querySelector(".parent"));
});

.parent {
  /*top: 50px;*/
  left: 50px;
  position: absolute;
}

.child {
  background: red;
  width: 50px;
  height: 50px;
}

.container {position:relative; height:200px;}

Click the square before restoring

<div class="container">
  <div class="parent" style="top:50px;">
    <div class="child">
    </div>
  </div>
</div>
<button id="restoreLeft" class="enable" data-restore="left" data-target=".parent">Restore Left</button>
<button id="restoreTop" class="enable" data-restore="top" data-target=".parent">Restore top</button>
<button id="restoreAll">RestoreAll</button>


问:
Python Datastructure Suggestion
i am building a small search engine to search a collection of pdfs. From each pdf i extract a set of tokens and store it in database. I do not want to store duplicate tokens in database, instead i want to store count of each token in the database. Does python has any special datastructure that do not store duplicates but stores the counts of each token?</p>

答:
You could always implement an object for every file, giving it a number of methods, like open and display and etc etc. You could then define __hash__ and __eq__ for the object, this would allow you to store items in a set, causing the duplicates to just update a single instance inside the set.

This is just another way of doing something by no means is it the best method.

ContentLicense: CC BY-SA 3.0

Title: Python Datastructure Suggestion


问:
How do I reset the numbers after calculating the Total
How will I clear the total after the first calculation?
I want it to reset if I add a new item after the first calculation. Right now it's adding it to the previous one.
For example, for the first calculation (item1 + item2) = total
if I add another item, it becomes (item1 + item 2) + (item1 + item2 + item3) = total

What I want is for it to reset and calculate the new total with the new item added.

 var count = 0;
    var tax = 0.05;
    var taxFeild = document.getElementById("Tax");
    var checkBoxes = document.getElementById("checkBoxes");
    var checks=document.querySelectorAll('.items');
    var ItemTotal=document.getElementById('ItemTotal');
    var Total=document.getElementById('TotalWithTax');
    var btn = document.getElementById("btn");

function Calculate()
      {

       for(var i =0 ;i< checks.length;i++)
         {
           if(checks[i].checked)
             {
               count+=parseFloat(checks[i].value);
             }
         }
        ItemTotal.textContent += count;
        taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
        Total.textContent += ((tax*count) + count).toFixed(2);
      }

        btn.addEventListener('click',Calculate);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">

</head>
<body>

<h2 class="first-heading">Assignment 1</h2>
<div class="row">
  <div class="column">
      <div id="checkBoxes">
            <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
            <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
            <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
            <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
            <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
            <button id="btn">Calculate</button>
        </div>
  </div>
  <div class="column" >

        <div id="Sums">
                <p id="ItemTotal"> Item Total: </p>
                <p id="Tax"> Tax: </p>
                <p id="TotalWithTax">Total with Tax: </p>
        </div>
  </div>
</div>
<script src="java.js"></script>

</body>
</html></code>```

答:
You can add count = 0; on the first line of function Calculate() { .... } so it will gives you a new total every time your list changes.

To update the field and keep the content intact.

const taxValue = tax * count;
total = taxValue + count;

ItemTotal.innerText = "Item Total:" + count;
taxFeild.innerText = "Tax:" + (parseFloat(taxValue).toFixed(2));
Total.innerText = "Total with Tax:" + (parseFloat(total).toFixed(2));
```

Body:
How will I clear the total after the first calculation?
I want it to reset if I add a new item after the first calculation. Right now it's adding it to the previous one.
For example, for the first calculation (item1 + item2) = total
if I add another item, it becomes (item1 + item 2) + (item1 + item2 + item3) = total

What I want is for it to reset and calculate the new total with the new item added.

 var count = 0;
    var tax = 0.05;
    var taxFeild = document.getElementById("Tax");
    var checkBoxes = document.getElementById("checkBoxes");
    var checks=document.querySelectorAll('.items');
    var ItemTotal=document.getElementById('ItemTotal');
    var Total=document.getElementById('TotalWithTax');
    var btn = document.getElementById("btn");

function Calculate()
      {

       for(var i =0 ;i< checks.length;i++)
         {
           if(checks[i].checked)
             {
               count+=parseFloat(checks[i].value);
             }
         }
        ItemTotal.textContent += count;
        taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
        Total.textContent += ((tax*count) + count).toFixed(2);
      }

        btn.addEventListener('click',Calculate);

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">

Assignment 1

            <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)

            <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)

            <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)

            <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)

            <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)

            <button id="btn">Calculate</button>

 Item Total:

 Tax:

Total with Tax:


问:
React Navigation how to hide tabbar from inside stack navigation
I have the following stack navigation and screens:

```<code>export const HomeStack = createStackNavigator({
    Home: HomeScreen,
    Categories: CategoriesScreen,
    Products: ProductsScreen,
    ProductDetails: ProductDetailsScreen,
})
</code>```

I want to hide tabs only in ProductDetailsScreen:

```<code>export const hideTabBarComponents = [
    'ProductDetails',
]

export const MainTabs = createBottomTabNavigator(
    {
        Home: HomeStack,
        Favorite: FavoriteScreen,
        Account: AccountScreen,
        Help: HelpScreen,
        Events: EventsScreen
    },
    {
        navigationOptions: ({ navigation }) => ({

            tabBarIcon: ({ focused, tintColor }) => {
                ...
            },
            tabBarLabel: ({ focused, tintColor }) => {
                ...
            },

            tabBarVisible: ! hideTabBarComponents.includes(navigation.state.routeName)

        }),
    }
);
</code>```

The problem is that can't pass any options to Tab navigation from Stack Navigation

Not all of the stack screens only one of them

答:
For React Navigation 5, you can do this inside of the stack component:

```<code>props.navigation.dangerouslyGetParent().setOptions({
  tabBarVisible: false
});
</code>```

https://reactnavigation.org/docs/en/navigation-prop.html#setoptions---update-screen-options-from-the-component

Be careful with using this though, you'll want to reset the tabBarVisible to true once unmounting the component.

For example, with React hooks inside the Stack component:

```<code>    useEffect(() => {
      const parent = props.navigation.dangerouslyGetParent();
      parent.setOptions({
        tabBarVisible: false
      });
      return () =>
        parent.setOptions({
          tabBarVisible: true
        });
    }, []);
</code>```

Or you can reset the tabBarVisible in the Stack.Screen component with the back button press like this:

```<code>    const StackNav = (props) => (
      <Stack.Screen
        name='name'
        component={Name}
        options={{
          headerTitle: 'Name',
          headerLeft: () => (
            <Text
              onPress={() =>
                props.navigation.setOptions({
                tabBarVisible: true
                })
              }
            >
              on back
            </Text>
          )
        }}
      />
    }
</code>```

(The second approach works better.)

Body:
I have the following stack navigation and screens:

export const HomeStack = createStackNavigator({
    Home: HomeScreen,
    Categories: CategoriesScreen,
    Products: ProductsScreen,
    ProductDetails: ProductDetailsScreen,
})

I want to hide tabs only in ProductDetailsScreen:

export const hideTabBarComponents = [
    'ProductDetails',
]

export const MainTabs = createBottomTabNavigator(
    {
        Home: HomeStack,
        Favorite: FavoriteScreen,
        Account: AccountScreen,
        Help: HelpScreen,
        Events: EventsScreen
    },
    {
        navigationOptions: ({ navigation }) => ({

            tabBarIcon: ({ focused, tintColor }) => {
                ...
            },
            tabBarLabel: ({ focused, tintColor }) => {
                ...
            },

            tabBarVisible: ! hideTabBarComponents.includes(navigation.state.routeName)

        }),
    }
);

The problem is that can't pass any options to Tab navigation from Stack Navigation

Not all of the stack screens only one of them

Body:
For React Navigation 5, you can do this inside of the stack component:

props.navigation.dangerouslyGetParent().setOptions({
  tabBarVisible: false
});

https://reactnavigation.org/docs/en/navigation-prop.html#setoptions---update-screen-options-from-the-component

Be careful with using this though, you'll want to reset the tabBarVisible to true once unmounting the component.

For example, with React hooks inside the Stack component:

    useEffect(() => {
      const parent = props.navigation.dangerouslyGetParent();
      parent.setOptions({
        tabBarVisible: false
      });
      return () =>
        parent.setOptions({
          tabBarVisible: true
        });
    }, []);

Or you can reset the tabBarVisible in the Stack.Screen component with the back button press like this:

    const StackNav = (props) => (
      <Stack.Screen
        name='name'
        component={Name}
        options={{
          headerTitle: 'Name',
          headerLeft: () => (
            <Text
              onPress={() =>
                props.navigation.setOptions({
                tabBarVisible: true
                })
              }
            >
              on back
            </Text>
          )
        }}
      />
    }

(The second approach works better.)


问:
Elements of a Structure Not Saving
I've been trying to do a leaderboard program for school, but I've noticed that the program overwrites the first player when trying to add new ones.

Am I doing something wrong?

The code accepts the players just fine, but opposed to adding new players to the leader board it just overwrites the first one completely.

```<code>#include <stdio.h>
int number,i,key,newscore,a;
struct playerdata
{
  char fname[50],lname[50];
  int id,score;
}playerstats[5];

void welcome()
{

    printf("\nWelcome to the leaderboard, challenger!");
    printf("\nPlease select an option:");
    printf("\n1-Add 5 players at a time\n2-Display all stats\n3-Update score\n4-Show player ranking\n5-Add 1 player");
    printf("\n\n");
    scanf("%d",&number);
    switch(number)
    {
        case 1:
        fillplayer();
        break;

        case 2:
        displaystats();
        break;

        case 3:
        updatescore();
        break;

        case 4:
        playerranking();
        break;

        case 5:
        addplayer();
        break;

        default:
        printf("\nThis option is invalid");
    }
}

void fillplayer()                                    //read player info//
{

    for(int i=0;i<5;i++)
    {
        printf("\nPlease enter your first name.");
        scanf("%s", &playerstats[i].fname);
        printf("\nPlease enter your last name.");
        scanf("%s", &playerstats[i].lname);
        printf("Please enter your player ID (Any random 4 digit number)");
        scanf("%d",&playerstats[i].id);
        printf("\n Please enter your score");
        scanf("%d",&playerstats[i].score);
    }

}

void displaystats()                              //Output player info//
{
    printf("\nFirstName\tLast Name\tID\tScore\t");
    for(int i=0;i<5;i++)
    {
        printf("\n%s\t\t%s\t\t%d\t\t%d",playerstats[i].fname,playerstats[i].lname,playerstats[i].id,playerstats[i].score);
    }
}

void addplayer()                                    //read one player's info//
{

        printf("\nPlease enter your first name.");
        scanf("%s", &playerstats[i].fname);
        printf("\nPlease enter your last name.");
        scanf("%s", &playerstats[i].lname);
        printf("Please enter your player ID (Any random 4 digit number)");
        scanf("%d",&playerstats[i].id);
        printf("\n Please enter your score");
        scanf("%d",&playerstats[i].score);

}

int searchplayer(void)
{
   printf("\nEnter your player ID");
   scanf("%d", &key);
   {
       if (playerstats[i].id=key)
       {
           return a;
       }
       else
       {
           return  -1;
       }
   }
}

void updatescore()
{
    a=searchplayer();
    if (playerstats[i].id==key)
    {
       printf ("\nYour ID is%d", playerstats[i].id);
       printf("\nEnter your new high score");
       scanf("%d",&newscore);
       if (newscore>playerstats[i].score)
       {
           playerstats[i].score=newscore;
           printf("Score successfully changed to %d", newscore);
       }
       else
       {
            printf("\nThis score is less than your current highscore, the high score shall not be changed");
       }
    }
    else
    {
        printf("\nInvalid ID");
    }
}

void playerranking()
{
    printf("\n not done");
}

int main()
{
    for(int i=0;i<999;i++)
    {
      welcome();
    }
    return 0;
}
</code>```

答:
You have a local loop counter i inside the function main() and some other function.

You have a (not explicitly initialised) global variable i which is used inside other functions.

They are not the same.
You never change the global i, which is e.g. used in the relevant function addplayer().

To solve I recommend to:

define to yourself the meaning and use of the global variable

name it accordingly

introduce some way of changing it, maybe more options in the menu

use it as parameter to called functions

also use it in the function which adds 5 players at once (or that will always overwrite the same first five), i.e. use the sum of global "current" and local loop counter

quite hard, but probably what you want: use the global via pointer parameter in functions which are supposed to change it; e.g. especially the add5 function

consider all the globals; generally try to avoid globals, they got you into the trouble you are currently experiencing

Title: Elements of a Structure Not Saving

Body:
I've been trying to do a leaderboard program for school, but I've noticed that the program overwrites the first player when trying to add new ones.

Am I doing something wrong?

The code accepts the players just fine, but opposed to adding new players to the leader board it just overwrites the first one completely.

#include <stdio.h>
int number,i,key,newscore,a;
struct playerdata
{
  char fname[50],lname[50];
  int id,score;
}playerstats[5];

void welcome()
{

    printf("\nWelcome to the leaderboard, challenger!");
    printf("\nPlease select an option:");
    printf("\n1-Add 5 players at a time\n2-Display all stats\n3-Update score\n4-Show player ranking\n5-Add 1 player");
    printf("\n\n");
    scanf("%d",&number);
    switch(number)
    {
        case 1:
        fillplayer();
        break;

        case 2:
        displaystats();
        break;

        case 3:
        updatescore();
        break;

        case 4:
        playerranking();
        break;

        case 5:
        addplayer();
        break;

        default:
        printf("\nThis option is invalid");
    }
}

void fillplayer()                                    //read player info//
{

    for(int i=0;i<5;i++)
    {
        printf("\nPlease enter your first name.");
        scanf("%s", &playerstats[i].fname);
        printf("\nPlease enter your last name.");
        scanf("%s", &playerstats[i].lname);
        printf("Please enter your player ID (Any random 4 digit number)");
        scanf("%d",&playerstats[i].id);
        printf("\n Please enter your score");
        scanf("%d",&playerstats[i].score);
    }

}

void displaystats()                              //Output player info//
{
    printf("\nFirstName\tLast Name\tID\tScore\t");
    for(int i=0;i<5;i++)
    {
        printf("\n%s\t\t%s\t\t%d\t\t%d",playerstats[i].fname,playerstats[i].lname,playerstats[i].id,playerstats[i].score);
    }
}

void addplayer()                                    //read one player's info//
{

        printf("\nPlease enter your first name.");
        scanf("%s", &playerstats[i].fname);
        printf("\nPlease enter your last name.");
        scanf("%s", &playerstats[i].lname);
        printf("Please enter your player ID (Any random 4 digit number)");
        scanf("%d",&playerstats[i].id);
        printf("\n Please enter your score");
        scanf("%d",&playerstats[i].score);

}

int searchplayer(void)
{
   printf("\nEnter your player ID");
   scanf("%d", &key);
   {
       if (playerstats[i].id=key)
       {
           return a;
       }
       else
       {
           return  -1;
       }
   }
}

void updatescore()
{
    a=searchplayer();
    if (playerstats[i].id==key)
    {
       printf ("\nYour ID is%d", playerstats[i].id);
       printf("\nEnter your new high score");
       scanf("%d",&newscore);
       if (newscore>playerstats[i].score)
       {
           playerstats[i].score=newscore;
           printf("Score successfully changed to %d", newscore);
       }
       else
       {
            printf("\nThis score is less than your current highscore, the high score shall not be changed");
       }
    }
    else
    {
        printf("\nInvalid ID");
    }
}

void playerranking()
{
    printf("\n not done");
}

int main()
{
    for(int i=0;i<999;i++)
    {
      welcome();
    }
    return 0;
}


问:
Open inbound calls redirects to another Twilio client when hang up
I have two available Twilio <client> to receive inbound calls on my website (after caller enters a code) using JS Quickstart and Twilio client PHP library, these calls are recorded and registered on my database.

I've noticed when one <client> hangs up an open inbound call , this call goes to the website of the other <client> I have have 2 registers on my database instead of one.

This is an example:

```<code><?php

//...
//Validating connection status
//$estd is the connection status I get via AJAX

if($estd=="open"){
    $call = $twilio->calls($callsid)->update(array("status" => "completed"));
    $calla = $twilio->calls($callsid)->fetch();
    $parentCall = $calla->parentCallSid; //parent call
    $calld = $twilio->calls($parentCall)->update(array("status" => "completed"));
} else if($estd=="pending"){
    $call = $twilio->calls($callsid)->update(array("status" => "completed"));
    $calla = $twilio->calls($callsid)->fetch();
    $parentCall = $calla->parentCallSid; //parent call
    $calld = $twilio->calls($parentCall)->update(array("twiml" => '<Response><Dial timeout="20" record="record-from-answer" recordingStatusCallback="https://mywebsite.com/record.php" recordingStatusCallbackEvent="in-progress completed absent"><Client><Identity>the_other_client</Identity><Parameter name="numdoc" value="user_code"/></Client></Dial></Response>'));
}

?>
</code>```

How can I fix it?

I'd like your help.

答:
I believe this could be occurring because a single incoming voice call will trigger both of your $estd if statements.

According to Twilio documentation (https://www.twilio.com/docs/voice/client/javascript/connection#status), an incoming call will first have the status pending, and then the status open. If your statuscallbackURL is set for when the status changes, you may be calling your record-keeping code more than once. Depending on how you have your SQL you may be inserting new records each time.

The way to prevent the double record is to save the resource SID for the call in your database and insert on duplicate key or update to prevent creating new records.

Alternatively, if the code snippet you are displaying is from record.php, when you make your outbound call using Twiml, you use a callbackURL to call record.php -- at which time you may be creating a new record in your database (as this call will have it's own unique SID). If you want to attach it to the current record, then you will need to create a different callbackURL for those outbound dials made from this script.

(But it is difficult from the details you have provided to know what code is being called when).

Body:
I have two available Twilio <client> to receive inbound calls on my website (after caller enters a code) using JS Quickstart and Twilio client PHP library, these calls are recorded and registered on my database.

I've noticed when one <client> hangs up an open inbound call , this call goes to the website of the other <client> I have have 2 registers on my database instead of one.

This is an example:

<?php

//...
//Validating connection status
//$estd is the connection status I get via AJAX

if($estd=="open"){
    $call = $twilio->calls($callsid)->update(array("status" => "completed"));
    $calla = $twilio->calls($callsid)->fetch();
    $parentCall = $calla->parentCallSid; //parent call
    $calld = $twilio->calls($parentCall)->update(array("status" => "completed"));
} else if($estd=="pending"){
    $call = $twilio->calls($callsid)->update(array("status" => "completed"));
    $calla = $twilio->calls($callsid)->fetch();
    $parentCall = $calla->parentCallSid; //parent call
    $calld = $twilio->calls($parentCall)->update(array("twiml" => '<Response><Dial timeout="20" record="record-from-answer" recordingStatusCallback="https://mywebsite.com/record.php" recordingStatusCallbackEvent="in-progress completed absent"><Client><Identity>the_other_client</Identity><Parameter name="numdoc" value="user_code"/></Client></Dial></Response>'));
}

?>

How can I fix it?

I'd like your help.


问:
‘ld: warning: directory not found for option’
When I'm building my Xcode 4 apps I'm getting this warning:

```<code>ld: warning: directory not found for option '-L/Users/frenck/Downloads/apz/../../../Downloads/Google Analytics SDK/Library'
ld: warning: directory not found for option '-L/Users/frenck/Downloads/apz/../Google Analytics SDK/Library'
</code>```

But I do not have Google Analytics in my app, I deleted all of it how can I remove the error?
And archiving an app gives me the error:

```<code>clang: error: no such file or directory: 'armv6'
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1
</code>```

I've tried so many things but I'm still getting this error when I'm trying to make an .IPA file

答: If the typical solution doesn't resolve the issue, what fixed it for me was ensuring that all iOS versions in the xcode project (e.g. IPHONEOS_DEPLOYMENT_TARGET) / deployment targets, podfiles (if applicable), etc. are set to the same version number. </p>

Body:
When I'm building my Xcode 4 apps I'm getting this warning:

ld: warning: directory not found for option '-L/Users/frenck/Downloads/apz/../../../Downloads/Google Analytics SDK/Library'
ld: warning: directory not found for option '-L/Users/frenck/Downloads/apz/../Google Analytics SDK/Library'

But I do not have Google Analytics in my app, I deleted all of it how can I remove the error?
And archiving an app gives me the error:

clang: error: no such file or directory: 'armv6'
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

I've tried so many things but I'm still getting this error when I'm trying to make an .IPA file


问:
How can I implement onActivityResult and onNewIntent on FlutterActivity
I would like to implement onActivityResult and onNewIntent on my Android native side of flutter app.

For example, I would like to be able to run "startActivityForResult", and open my app using a deep link.

My main activity is flutter, but I have some work I need to do on the native part.

Is there a way to accomplish this without writing an external plugin?

```<code>package com.test.flutter_app

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}
</code>```

As I understand from the documentation, I need to use PluginRegistry.Registrar addActivityResultListener. But who is my Registrar? how can I get it/use it?
Code examples would be much appreciated.

答:
I use this way.

Create Channel

```<code>MethodChannel nativeChannel = new MethodChannel(MainApplication.flutterActivity.getFlutterView(), CHANNEL_NATIVE);
nativeChannel.setMethodCallHandler(new MethodCallHandler() {
    @Override
    public void onMethodCall(@NotNull MethodCall methodCall, @NotNull Result result) {
        if (methodCall.method == METHOD_SHOW_NATIVEVIEW) {
            Intent intent = new Intent(MainApplication.instance().getApplicationContext(), [YourActivityClass]);
            intent.putExtra(ARG_VIEW_NAME, [YourActivityClassName]);
            MainFlutterActivity.instance().startActivityForResult(intent, RESULT_ACTIVITY);
        }
    }
});
public void closeNativeView(String viewName, HashMap<String, Object> params) {
    HashMap<String, Object> arg = new HashMap<>();
    arg.put(ARG_VIEW_NAME, viewName);
    arg.put(ARG_PARAMS, params);
    nativeChannel.invokeMethod(METHOD_CLOSE_NATIVEVIEW, arg, null);
}
</code>```

Override FlutterActivity

```<code>public class MainFlutterActivity extends FlutterActivity {
  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_ACTIVITY) {
      String viewName = "";
      HashMap<String, Object> params = new HashMap<String, Object>();

      if (data != null) {
        viewName = data.getStringExtra(ARG_VIEW_NAME);
        params = (HashMap<String, Object>) data.getSerializableExtra(ARG_PARAMS);
      }

      closeNativeView(viewName, params);
    }
  }
}
</code>```

Body:
I would like to implement onActivityResult and onNewIntent on my Android native side of flutter app.

For example, I would like to be able to run "startActivityForResult", and open my app using a deep link.

My main activity is flutter, but I have some work I need to do on the native part.

Is there a way to accomplish this without writing an external plugin?

package com.test.flutter_app

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}

As I understand from the documentation, I need to use PluginRegistry.Registrar addActivityResultListener. But who is my Registrar? how can I get it/use it?
Code examples would be much appreciated.

Body:
I use this way.

Create Channel

MethodChannel nativeChannel = new MethodChannel(MainApplication.flutterActivity.getFlutterView(), CHANNEL_NATIVE);
nativeChannel.setMethodCallHandler(new MethodCallHandler() {
    @Override
    public void onMethodCall(@NotNull MethodCall methodCall, @NotNull Result result) {
        if (methodCall.method == METHOD_SHOW_NATIVEVIEW) {
            Intent intent = new Intent(MainApplication.instance().getApplicationContext(), [YourActivityClass]);
            intent.putExtra(ARG_VIEW_NAME, [YourActivityClassName]);
            MainFlutterActivity.instance().startActivityForResult(intent, RESULT_ACTIVITY);
        }
    }
});
public void closeNativeView(String viewName, HashMap<String, Object> params) {
    HashMap<String, Object> arg = new HashMap<>();
    arg.put(ARG_VIEW_NAME, viewName);
    arg.put(ARG_PARAMS, params);
    nativeChannel.invokeMethod(METHOD_CLOSE_NATIVEVIEW, arg, null);
}

Override FlutterActivity

public class MainFlutterActivity extends FlutterActivity {
  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_ACTIVITY) {
      String viewName = "";
      HashMap<String, Object> params = new HashMap<String, Object>();

      if (data != null) {
        viewName = data.getStringExtra(ARG_VIEW_NAME);
        params = (HashMap<String, Object>) data.getSerializableExtra(ARG_PARAMS);
      }

      closeNativeView(viewName, params);
    }
  }
}


问:
Loss of data type when converting numpy.ndarry.tolist?
So I have an ndarray similar to this example:

```<code>dates = ['3/1/2020','4/15/2020','7/21/2020']
darray = np.asarray([dateutil.parser.parse(d) for d in dates], dtype='datetime64[ns]')

>>> array(['2020-03-01T00:00:00.000000000', '2020-04-15T00:00:00.000000000',
   '2020-07-21T00:00:00.000000000'], dtype='datetime64[ns]')

darray.tolist()

>>> [1583020800000000000, 1586908800000000000, 1595289600000000000]
</code>```

So I'm assuming it's converting to number of nanoseconds since the POSIX origin (1970-01-01). Is there a way to avoid this loss of data type?

答:
Is this what you're looking for?

>>> list(darray)
[numpy.datetime64('2020-03-01T00:00:00.000000000'),
 numpy.datetime64('2020-04-15T00:00:00.000000000'),
 numpy.datetime64('2020-07-21T00:00:00.000000000')]
```

The difference is that np.ndarray.tolist() converts values to Python types, whereas list(...) leaves the objects as they are. Internally of course they both contain 64-bit integers either way. If you want to convert to Python datetime objects, have a look at this question. Unfortunately it's not as convenient as it could be.

Body:
So I have an ndarray similar to this example:

dates = ['3/1/2020','4/15/2020','7/21/2020']
darray = np.asarray([dateutil.parser.parse(d) for d in dates], dtype='datetime64[ns]')

>>> array(['2020-03-01T00:00:00.000000000', '2020-04-15T00:00:00.000000000',
   '2020-07-21T00:00:00.000000000'], dtype='datetime64[ns]')

darray.tolist()

>>> [1583020800000000000, 1586908800000000000, 1595289600000000000]

So I'm assuming it's converting to number of nanoseconds since the POSIX origin (1970-01-01). Is there a way to avoid this loss of data type?

Body:
Is this what you're looking for?

>>> list(darray)
[numpy.datetime64('2020-03-01T00:00:00.000000000'),
 numpy.datetime64('2020-04-15T00:00:00.000000000'),
 numpy.datetime64('2020-07-21T00:00:00.000000000')]

The difference is that np.ndarray.tolist() converts values to Python types, whereas list(...) leaves the objects as they are. Internally of course they both contain 64-bit integers either way. If you want to convert to Python datetime objects, have a look at this question. Unfortunately it's not as convenient as it could be.


问:
Should I return an array or a collection from a function?
What's the preferred container type when returning multiple objects of the same type from a function?

Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?

Thanks!

答:
There are big advantages to favouring IEnumerable over anything else, as this gives you the greatest implementation flexibility and allows you to use yield return or Linq operators for lazy implementation.

If the caller wants a List<T> instead they can simply call ToList() on whatever you returned, and the overall performance will be roughly the same as if you had created and returned a new List<T> from your method.

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Earwicker


问:
Is html-webpack-plugin hijacking my express server?
I've been working through the tutorials at https://webpack.js.org/guides/output-management/ and they've solidified my understanding of how webpack typically bundles your whole frontend into a script that is run by a barebones HTML page like this:

```<code><html>
<head>
    <title>Output Management</title>
</head>
<body>
    <script src="./app.bundle.js"></script>
</body>
</html>
</code>```

This file is in a src directory, which sits in the project root.

I've modified the tutorials slightly by serving that HTML page from an Express server, which looks like this:

```<code>const express = require("express");
var path = require("path");

const server = express();
server.use(express.static(path.join(__dirname, "../dist")));
server.use(express.urlencoded({ extended: true }));

var indexPath = path.join(__dirname, "../src/index.html");

//create a server object:
server
    .get("/", function(req, res) {
        res.status(200)
        res.sendFile(indexPath);
        //res.send('<h1>I am not the webpack script!</h1>')
    })

module.exports = server
</code>```

So far everything makes sense. This server serves my index.html, which runs the webpack script, and that script causes the HTML page to show some text, images, and CSS. If I uncomment the res.send line, the server serves a one-line website instead.

However, the linked tutorial recommends trying HTML-webpack plugin, and when that comes in I get confused. I understand that the plugin creates an index.html file in the same directory as the bundled scripts (in my case /dist) that incorporates any and all scripts created by webpack. Sure, makes sense. But nothing is explicitly serving that HTML file. However,  if I add the plugin to my webpack config:

```<code>    entry: {
        app: "./src/index.js",
        print: "./src/print.js"
    },
+   plugins: [
+     new HtmlWebpackPlugin({
+       title: 'Output Management',
+     }),
+   ],
    output: {
        filename: "[name].bundle.js",
        path: path.resolve(__dirname, "dist")
    },
</code>```

then navigate to localhost:3000 in the browser, it displays the /dist/index.html file, NOT the /src/index.html file. Nothing I do to modify the server.js file changes what is displayed in the browser, but if I stop that server from being listened to I see nothing, so apparently webpack-html-plugin is not creating a server of its own.

So seemingly what is happening is that webpack-html-plugin is not just dynamically creating an HTML file to run bundled scripts, it is also changing the behavior of my server in a way that I am not explicitly instructing it to and seemingly cannot modify.

TLDR: Specifically, something in webpack-html-plugin is causing the root route of my express server to serve /dist/index.html, not /src/index.html as I am explicitly instructing it to. Why?

The repo is at https://github.com/CliffRobinson/webpack-tutorial-sandbox and you can (probably) have a look at codesandbox here to see if you can replicate this odd behavior.

答: What is happening is that you are serving all the files inside the dist directory as static files where your index.html is generated by html-webpack-plugin. I'm not sure how paths are handled in express but it seems that static files take precedence over any route defined that is why dist/index.html is overriding / path.

Body:
I've been working through the tutorials at https://webpack.js.org/guides/output-management/ and they've solidified my understanding of how webpack typically bundles your whole frontend into a script that is run by a barebones HTML page like this:

    <title>Output Management</title>

This file is in a src directory, which sits in the project root.

I've modified the tutorials slightly by serving that HTML page from an Express server, which looks like this:

const express = require("express");
var path = require("path");

const server = express();
server.use(express.static(path.join(__dirname, "../dist")));
server.use(express.urlencoded({ extended: true }));

var indexPath = path.join(__dirname, "../src/index.html");

//create a server object:
server
    .get("/", function(req, res) {
        res.status(200)
        res.sendFile(indexPath);
        //res.send('
I am not the webpack script!
')
    })

module.exports = server

So far everything makes sense. This server serves my index.html, which runs the webpack script, and that script causes the HTML page to show some text, images, and CSS. If I uncomment the res.send line, the server serves a one-line website instead.

However, the linked tutorial recommends trying HTML-webpack plugin, and when that comes in I get confused. I understand that the plugin creates an index.html file in the same directory as the bundled scripts (in my case /dist) that incorporates any and all scripts created by webpack. Sure, makes sense. But nothing is explicitly serving that HTML file. However,  if I add the plugin to my webpack config:

    entry: {
        app: "./src/index.js",
        print: "./src/print.js"
    },
+   plugins: [
+     new HtmlWebpackPlugin({
+       title: 'Output Management',
+     }),
+   ],
    output: {
        filename: "[name].bundle.js",
        path: path.resolve(__dirname, "dist")
    },

then navigate to localhost:3000 in the browser, it displays the /dist/index.html file, NOT the /src/index.html file. Nothing I do to modify the server.js file changes what is displayed in the browser, but if I stop that server from being listened to I see nothing, so apparently webpack-html-plugin is not creating a server of its own.

So seemingly what is happening is that webpack-html-plugin is not just dynamically creating an HTML file to run bundled scripts, it is also changing the behavior of my server in a way that I am not explicitly instructing it to and seemingly cannot modify.

TLDR: Specifically, something in webpack-html-plugin is causing the root route of my express server to serve /dist/index.html, not /src/index.html as I am explicitly instructing it to. Why?

The repo is at https://github.com/CliffRobinson/webpack-tutorial-sandbox and you can (probably) have a look at codesandbox here to see if you can replicate this odd behavior.


问:
OOP inheritance, how to get variable of parent type in python?
i have this code so far:

```<code>class vehicle:
    def __init__(self, numWheels, listWeightOfItem):
        self.numWheels = numWheels
        self.listWeightOfItem = listWeightOfItem

class car(vehicle):
    def __init__(self, numWheels, listWeightOfItem, listWeightPeople):
        vehicle.__init__(self, numWheels, listOfWeightItem)
        self.listWeightPeople = listWeightPeople
</code>```

Car is going to inherit from vehicle.
Car is supposed to have a trailer of type vehicle and I do not know how to put this into code. I thought about creating a class variable but I do not think that it makes sense, and how do i make sure the trailer is of type vehicle and not car?

答:
Car is going to inherit from vehicle. Car is supposed to have a trailer of type vehicle and I do not know how to put this into code. I thought about creating a class variable but I do not think that it makes sense, and how do i make sure the trailer is of type vehicle and not car?

Why a class variable and not an instance variable?

how do i make sure the trailer is of type vehicle and not car?

Why would there be any risk related to that?

If I understand the situation correctly, you can do something like this:

class Vehicle:
    def __init__(self, num_wheels: int, list_weight_item: float) -> None:
        self.num_wheels = num_wheels
        self.list_weight_item = list_weight_item

    def __repr__(self) -> str:
        return f"Vehicle(num_wheels={self.num_wheels}, " \
               f"list_weight_item={self.list_weight_item})"

class Trailer(Vehicle):

    def __init__(self, num_wheels: int, list_weight_item: float, cargo_type: str) -> None:
        super().__init__(num_wheels, list_weight_item)
        self.cargo_type = cargo_type

    def __repr__(self) -> str:
        return f"Trailer(num_wheels={self.num_wheels}, " \
               f"list_weight_item={self.list_weight_item}, " \
               f"cargo_type={self.cargo_type})"

class Car(Vehicle):
    def __init__(self, num_wheels: int, list_weight_item: float, list_weight_people: float,
                 trailer: Trailer = None) -> None:
        super().__init__(num_wheels, list_weight_item)
        self.list_weight_people = list_weight_people
        self.trailer = trailer

    def __repr__(self) -> str:
        return f"Car(num_wheels={self.num_wheels}, " \
               f"list_weight_item={self.list_weight_item}, " \
               f"list_weight_people={self.list_weight_people}, " \
               f"trailer={self.trailer})"

t_1 = Vehicle(2, 100)
t_2 = Trailer(num_wheels=2, list_weight_item=1000, cargo_type='car')
t_3 = Car(num_wheels=4, list_weight_item=2000, list_weight_people=200, trailer=t_2)
t_4 = Car(num_wheels=4, list_weight_item=2500, list_weight_people=300)

print(t_1, t_2, t_3, t_4, sep='\n')
```

Body:
i have this code so far:

class vehicle:
    def __init__(self, numWheels, listWeightOfItem):
        self.numWheels = numWheels
        self.listWeightOfItem = listWeightOfItem

class car(vehicle):
    def __init__(self, numWheels, listWeightOfItem, listWeightPeople):
        vehicle.__init__(self, numWheels, listOfWeightItem)
        self.listWeightPeople = listWeightPeople

Car is going to inherit from vehicle.
Car is supposed to have a trailer of type vehicle and I do not know how to put this into code. I thought about creating a class variable but I do not think that it makes sense, and how do i make sure the trailer is of type vehicle and not car?


问:
Azure monitor for containers v/s Application insights
We are designing an application which will be hosted on AKS(Azure kubernetes service). The application will consist of a set of services written in asp .net core running in docker containers. I want to monitor the services as well as the containers/nodes and have the observability across the cluster. Azure monitor for containers seems to be a good solution for monitoring containers, nodes and the cluster as a whole however I want the advanced monitoring capabilities of the application insights for the asp .net core services for example application maps, live metrics streams, transaction tracing and such features. Moreover, I don't want to have overlapping solutions. Is the Azure monitor for containers able to provide all or most of these application insights features or do I have to have both solutions in order to get proper cluster monitoring and also the advanced application monitoring?</p>

答: In this (https://learn.microsoft.com/en-us/azure/azure-monitor/insights/container-insights-overview) guide, you can find all the features of AKS monitoring. If these covers all your use cases then you don't need to install any other tool. If not, then you cover only those features which are missing.</p>


问:
Pyinstaller win32ctypes.pywin32.pywintypes.error: (1920, 'LoadLibraryExW', 'System cannot access the file')
I'm trying to use the pyinstaller to pack my python file in to .exe, but I keep getting this error message.

```<code>win32ctypes.pywin32.pywintypes.error: (1920, 'LoadLibraryExW', 'System can not access the file')
</code>```

I've tried running the cmd as administrator but it's still not working.

My operating system is Windows 10

答: I had the same problem. Just move your python file in your C:\Users\batman\AppData\Local\Programs\Python\Python38-32\Scripts folder where you can also find pyinstaller.exe and run the windows command prompt there and try again!

Body:
I'm trying to use the pyinstaller to pack my python file in to .exe, but I keep getting this error message.

win32ctypes.pywin32.pywintypes.error: (1920, 'LoadLibraryExW', 'System can not access the file')

I've tried running the cmd as administrator but it's still not working.

My operating system is Windows 10


问:
How do I keep track of time before executing any function?
I have this service which calls Notification() function every second. What this function does is it checks the time difference between lastupdated and DateTime.UtcNow and check if the Countdiff is greater than 1

If the above conditions is true then it checks if the AppGuid is already in the DB if it's not it inserts it and calls DoAction() function which sends a notification. Everything works fine till here.

The problem starts when the AppGuid is already in DB.

What I need is if AppGuid is already in DB then send notification every 15 Min, here I'm struggling with keeping track last time I send notification, I tried to compare last timestamp when it got updated and tried to compare the difference but it keeps sending notifications resulting spamming the pipeline.

I tried to keep elasped time with stopwatch class but the problem it waits for 15 min when app starts initially to send anything.

How do I send notification only once every 15 min?

```<code>public class DataGetService : DelegatingHandler, IHostedService
{
    private Timer _timer;
    Stopwatch stopwatch = new Stopwatch();

    public Task StartAsync(CancellationToken cancellationToken)
    {
        stopwatch.Start();
        _timer = new Timer(Heartbeat, null, 1000, 1000);
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        //Timer does not have a stop.
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    public void Heartbeat(object state)
    {
        _ = Notifications(TimeSpan.FromMinutes(15));
    }

    public async Task Notifications(TimeSpan period)
    {
        // Result array have: LastUpdated, CountDiff, AppGuid, AppName, Timestamp
        foreach (var d in result)
        {
            var x = _DBcontext.TestEvents.FirstOrDefault(o => o.AppGuid == (Guid)d.AppGuid);

            if (DateTime.UtcNow - d.LastUpdated <= TimeSpan.FromMinutes(30) && d.CountDiff > 1)
            {
                if (x == null)
                {
                    DoAction();
                    _DBcontext.TestEvents.Add(new TestEvents
                    {
                        AppGuid = (Guid)d.AppGuid,
                        AppName = d.AppName,
                        Timestamp = DateTime.UtcNow
                    });
                }
                else
                {   //This is useful if app have crashed or was not able to update in db, it will update the current timestamp.
                    if (DateTime.UtcNow - x.Timestamp >= TimeSpan.FromMinutes(30))
                    {
                        x.Timestamp = DateTime.UtcNow;
                    }
                    else
                    {
                        if (stopwatch.Elapsed <= period)
                            return;

                        DoAction();
                        x.Timestamp = DateTime.UtcNow;
                    }
                }
            }
        }

        await _DBcontext.SaveChangesAsync();

        stopwatch.Restart();
    }
}
</code>```

答:
For future answer seekers:

I have added futureTime variable which adds 15 min to the Timestamp from DB.

The interesting thing was when I compare with if(DateTime.UtcNow == futureTime) the condition never became true, reason what I have understood is I call this function every second during the execution somehow system was skipping the time resulting false condition.

To overcome this I took the difference (DateTime.UtcNow - futureTime) and also consider the tolerance of seconds.

```<code>if (DateTime.UtcNow - d.LastUpdated <= TimeSpan.FromMinutes(30) && d.CountDiff > 1)
{
    if (x == null)
    {
        DoAction();
        _DBcontext.TestEvents.Add(new TestEvents
        {
            AppGuid = (Guid)item.AppGuid,
            AppName = item.AppName,
            Timestamp = DateTime.UtcNow
        });
    }
    //This is useful if app have crashed or was not able to update in db, it will update the current timestamp.
    else if (DateTime.UtcNow - x.Timestamp >= TimeSpan.FromMinutes(30))
    {
        x.Timestamp = DateTime.UtcNow;
    }
    else
    {
        //This will set the notification date in future
        DateTime dbtimestamp = x.Timestamp;
        DateTime futureTime = dbtimestamp.AddMinutes(15);

        if (((DateTime.UtcNow - futureTime) - TimeSpan.FromSeconds(1)).Duration() < TimeSpan.FromSeconds(1.0))
        {
            DoAction();
            x.Timestamp = DateTime.UtcNow;
        }
    }
}
</code>```

Body:
I have this service which calls Notification() function every second. What this function does is it checks the time difference between lastupdated and DateTime.UtcNow and check if the Countdiff is greater than 1

If the above conditions is true then it checks if the AppGuid is already in the DB if it's not it inserts it and calls DoAction() function which sends a notification. Everything works fine till here.

The problem starts when the AppGuid is already in DB.

What I need is if AppGuid is already in DB then send notification every 15 Min, here I'm struggling with keeping track last time I send notification, I tried to compare last timestamp when it got updated and tried to compare the difference but it keeps sending notifications resulting spamming the pipeline.

I tried to keep elasped time with stopwatch class but the problem it waits for 15 min when app starts initially to send anything.

How do I send notification only once every 15 min?

public class DataGetService : DelegatingHandler, IHostedService
{
    private Timer _timer;
    Stopwatch stopwatch = new Stopwatch();

    public Task StartAsync(CancellationToken cancellationToken)
    {
        stopwatch.Start();
        _timer = new Timer(Heartbeat, null, 1000, 1000);
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        //Timer does not have a stop.
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    public void Heartbeat(object state)
    {
        _ = Notifications(TimeSpan.FromMinutes(15));
    }

    public async Task Notifications(TimeSpan period)
    {
        // Result array have: LastUpdated, CountDiff, AppGuid, AppName, Timestamp
        foreach (var d in result)
        {
            var x = _DBcontext.TestEvents.FirstOrDefault(o => o.AppGuid == (Guid)d.AppGuid);

            if (DateTime.UtcNow - d.LastUpdated <= TimeSpan.FromMinutes(30) && d.CountDiff > 1)
            {
                if (x == null)
                {
                    DoAction();
                    _DBcontext.TestEvents.Add(new TestEvents
                    {
                        AppGuid = (Guid)d.AppGuid,
                        AppName = d.AppName,
                        Timestamp = DateTime.UtcNow
                    });
                }
                else
                {   //This is useful if app have crashed or was not able to update in db, it will update the current timestamp.
                    if (DateTime.UtcNow - x.Timestamp >= TimeSpan.FromMinutes(30))
                    {
                        x.Timestamp = DateTime.UtcNow;
                    }
                    else
                    {
                        if (stopwatch.Elapsed <= period)
                            return;

                        DoAction();
                        x.Timestamp = DateTime.UtcNow;
                    }
                }
            }
        }

        await _DBcontext.SaveChangesAsync();

        stopwatch.Restart();
    }
}

Body:
For future answer seekers:

I have added futureTime variable which adds 15 min to the Timestamp from DB.

The interesting thing was when I compare with if(DateTime.UtcNow == futureTime) the condition never became true, reason what I have understood is I call this function every second during the execution somehow system was skipping the time resulting false condition.

To overcome this I took the difference (DateTime.UtcNow - futureTime) and also consider the tolerance of seconds.

if (DateTime.UtcNow - d.LastUpdated <= TimeSpan.FromMinutes(30) && d.CountDiff > 1)
{
    if (x == null)
    {
        DoAction();
        _DBcontext.TestEvents.Add(new TestEvents
        {
            AppGuid = (Guid)item.AppGuid,
            AppName = item.AppName,
            Timestamp = DateTime.UtcNow
        });
    }
    //This is useful if app have crashed or was not able to update in db, it will update the current timestamp.
    else if (DateTime.UtcNow - x.Timestamp >= TimeSpan.FromMinutes(30))
    {
        x.Timestamp = DateTime.UtcNow;
    }
    else
    {
        //This will set the notification date in future
        DateTime dbtimestamp = x.Timestamp;
        DateTime futureTime = dbtimestamp.AddMinutes(15);

        if (((DateTime.UtcNow - futureTime) - TimeSpan.FromSeconds(1)).Duration() < TimeSpan.FromSeconds(1.0))
        {
            DoAction();
            x.Timestamp = DateTime.UtcNow;
        }
    }
}


问:
Separating Docker files and application source files to optimize production environment
I have a bunch of (Ruby) scripts stored on a server. Up until now, my team has used them by opening an accessor app that launches a list of the script names, and they select the script they want to run in that instance on the files in their working folder. The scripts are run directly from the server, so updates made to the script files are automatically reflected when a user runs the script.

The scripts require a fair amount of specific dependencies, so I'm trying to move to a Docker-based workflow to eliminate the problems we encounter with incongruent computer environments. I've been able to successfully build an image with our script library and run an instance of it on my computer.

However, all of the documentation and tutorials include the application source files when building an image, so that all the files are copied over by the Dockerfile. From my understanding, this means that any time the code in the application files needs to be updated, all the users will need to rebuild the image before trying to run anything. I would very rarely ever need to make changes to the environment settings/dependencies, but the app code is changed relatively frequently, so it seems like having every user rebuild an image every single time a line of app code is changed would actually slow down everyone's workflow considerably.

My question is this: Is it not possible to have Docker simply create the environment that a user must have to run the applications, but have the applications themselves still run directly off the server where they were originally stored? And does a new container need to be created every single time a user wants to run any one of the scripts? (The users are not tech-savvy.)

答:
Generally you'd do this by using a Docker image instead of the checked-out tree of scripts.  You can use a Docker registry to store a built copy of the image somewhere on the network; Docker Hub works for this, most large public-cloud providers have some version of this (AWS ECR, Google GCR, Azure ACR, ...), or you can run your own.  The workflow for using this would generally look like

# Get any updates to the "latest" version of the image
# (can be run infrequently)
docker pull ourorg/scripts

# Actually run the script, injecting config files and credentials
docker run --rm \
  -v $PWD/config:/config \
  -v $HOME/.ssh:/config/.ssh \
  ourorg/scripts \
  some_script.rb

# Nothing in this example actually requires a local copy of the scripts
```

<p>I'm envisioning a directory that has kind of a mix of scripts and support files and not a lot of organization to it.  Still, you could write a simple Dockerfile that looks like</p>

<pre class="lang-sh prettyprint-override"><code>FROM ruby:2.7
WORKDIR /opt/scripts

# As of Bundler 2.1, there is no compatibility between Bundler
# versions; this must match exactly what is in Gemfile.lock
RUN gem install bundler -v 2.1.4

# Copy the scripts in and do basic installation
COPY Gemfile Gemfile.lock .
RUN bundle install
COPY . .
ENV PATH /opt/scripts:$PATH

# Prefix all commands with...
ENTRYPOINT ["bundle", "exec"]

# The default command to run is...
CMD ["ls"]
</code>```

On the back end you'd need a continous integration service (Jenkins is popular if a little unwieldy; there are a large selection of cloud-hosted ones) that can rebuild the Docker image whenever there's a commit to the source repository.  You can generally rig this up so that it happens automatically whenever anybody pushes anything.

This process makes more sense of most people are just using the set of scripts and few of them are developing them.  It's also a little bit difficult to discover what the scripts are (you might be able to docker run --rm ourorg/scripts ls though).

Is it not possible to have Docker simply create the environment that a user must have to run the applications, but have the applications themselves still run directly off the server where they were originally stored?

This always strikes me as an ineffective use of Docker.  You have all of the fiddly steps of your current workflow that require everyone to run a git pull or equivalent routinely, but you also have to inject the host source tree into the container.  If there are OS incompatibilities in, for example, native gems in the vendor tree, you have to work around that.

# You still need to do this periodically
git pull

# And you also need to
sudo docker run \
  --rm \
  -v $PWD:/app \
  -v $HOME/config:/config \
  -v $HOME/.ssh:/config/.ssh \
  -w /app \
  ruby:2.7 \
  bundle exec ./some_script.rb
```

Some of these details (especially the config file and credentials) you'd have to deal with even if you did build an image; some others of the details you could improve by building an image.  Inside the image you need to correct the ownership and permissions on the ssh keys and replace the $PWD/vendor tree with something the container can run, without modifying the mounted host directories.

Body:
Generally you'd do this by using a Docker image instead of the checked-out tree of scripts.  You can use a Docker registry to store a built copy of the image somewhere on the network; Docker Hub works for this, most large public-cloud providers have some version of this (AWS ECR, Google GCR, Azure ACR, ...), or you can run your own.  The workflow for using this would generally look like

# Get any updates to the "latest" version of the image
# (can be run infrequently)
docker pull ourorg/scripts

# Actually run the script, injecting config files and credentials
docker run --rm \
  -v $PWD/config:/config \
  -v $HOME/.ssh:/config/.ssh \
  ourorg/scripts \
  some_script.rb

# Nothing in this example actually requires a local copy of the scripts

I'm envisioning a directory that has kind of a mix of scripts and support files and not a lot of organization to it.  Still, you could write a simple Dockerfile that looks like

FROM ruby:2.7
WORKDIR /opt/scripts

# As of Bundler 2.1, there is no compatibility between Bundler
# versions; this must match exactly what is in Gemfile.lock
RUN gem install bundler -v 2.1.4

# Copy the scripts in and do basic installation
COPY Gemfile Gemfile.lock .
RUN bundle install
COPY . .
ENV PATH /opt/scripts:$PATH

# Prefix all commands with...
ENTRYPOINT ["bundle", "exec"]

# The default command to run is...
CMD ["ls"]

On the back end you'd need a continous integration service (Jenkins is popular if a little unwieldy; there are a large selection of cloud-hosted ones) that can rebuild the Docker image whenever there's a commit to the source repository.  You can generally rig this up so that it happens automatically whenever anybody pushes anything.

This process makes more sense of most people are just using the set of scripts and few of them are developing them.  It's also a little bit difficult to discover what the scripts are (you might be able to docker run --rm ourorg/scripts ls though).

Is it not possible to have Docker simply create the environment that a user must have to run the applications, but have the applications themselves still run directly off the server where they were originally stored?

This always strikes me as an ineffective use of Docker.  You have all of the fiddly steps of your current workflow that require everyone to run a git pull or equivalent routinely, but you also have to inject the host source tree into the container.  If there are OS incompatibilities in, for example, native gems in the vendor tree, you have to work around that.

# You still need to do this periodically
git pull

# And you also need to
sudo docker run \
  --rm \
  -v $PWD:/app \
  -v $HOME/config:/config \
  -v $HOME/.ssh:/config/.ssh \
  -w /app \
  ruby:2.7 \
  bundle exec ./some_script.rb

Some of these details (especially the config file and credentials) you'd have to deal with even if you did build an image; some others of the details you could improve by building an image.  Inside the image you need to correct the ownership and permissions on the ssh keys and replace the $PWD/vendor tree with something the container can run, without modifying the mounted host directories.


问:
Vue.js this.$refs empty due to v-if
I have a simple Vue component that displays an address, but converts into a form to edit the address if the user clicks a button.  The address field is an autocomplete using Google Maps API.  Because the field is hidden (actually nonexistent) half the time, I have to re-instantiate the autocomplete each time the field is shown.

<template>

<input ref="autocomplete" v-model="address">

      <button @click="save">Save</button>

{{ address }}

      <button @click="edit">Edit</button>

</template>

答:
Maybe a solution would be to use $nextTick which will wait for your DOM to rerender.

So your code would look like :

```<code>edit() {
  this.editing = true;
  this.$nextTick(() => { this.initAutocomplete(); });
},
</code>```

Moreover if you try to use your this.initAutocomplete(); during mounting it cannot work since the $refs.autocomplete is not existing yet but I'm not sure you need it since your v-model is already empty.

Title: Vue.js this.$refs empty due to v-if

Body:
Maybe a solution would be to use $nextTick which will wait for your DOM to rerender.

So your code would look like :

edit() {
  this.editing = true;
  this.$nextTick(() => { this.initAutocomplete(); });
},

Moreover if you try to use your this.initAutocomplete(); during mounting it cannot work since the $refs.autocomplete is not existing yet but I'm not sure you need it since your v-model is already empty.


问:
How to make animation in ARkit by changing position per second
I what to make animation in ARkit to a SCNnode by changing its positions, kind of like a render loop. Means to change the location 60 time per second, how can I do that?</p>

答:
If you just want to change your node's position 60 times a second, then you could just implement the renderer 'updateAtTime' function for the 'ARSCNViewDelegate'.
That function should be called at around 60 times a second.

A dumb version might be

```<code>extension ViewController: ARSCNViewDelegate, ARSessionDelegate {
    func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
        yourNode.simdWorldPosition.z -= 0.01
    }

</code>```

That would move the previously defined yourNode 1 cm in the -Z direction 60 times a second. You could write this with an iteration tracker to loop whatever position actions you want.

You could also do an actual animation with something like

```<code>    let startingZ = node.simdWorldPosition.z
    let animation = CABasicAnimation(keyPath: "simdWorldPosition.z")
    animation.fromValue = startingZ
    animation.toValue = startingZ - 2.0
    animation.duration = 1
    animation.autoreverses = true
    animation.repeatCount = .infinity
    yourNode.addAnimation(animation, forKey: "backAndForth")
</code>```

Or you could use SCNActions as shown here: Adding animation to 3D models in ARKit

Body:
If you just want to change your node's position 60 times a second, then you could just implement the renderer 'updateAtTime' function for the 'ARSCNViewDelegate'.
That function should be called at around 60 times a second.

A dumb version might be

extension ViewController: ARSCNViewDelegate, ARSessionDelegate {
    func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
        yourNode.simdWorldPosition.z -= 0.01
    }

That would move the previously defined yourNode 1 cm in the -Z direction 60 times a second. You could write this with an iteration tracker to loop whatever position actions you want.

You could also do an actual animation with something like

    let startingZ = node.simdWorldPosition.z
    let animation = CABasicAnimation(keyPath: "simdWorldPosition.z")
    animation.fromValue = startingZ
    animation.toValue = startingZ - 2.0
    animation.duration = 1
    animation.autoreverses = true
    animation.repeatCount = .infinity
    yourNode.addAnimation(animation, forKey: "backAndForth")

Or you could use SCNActions as shown here: Adding animation to 3D models in ARKit


答:
I think it's because your "refs" is plural

```<code><input refs="autocomplete" v-model="address">
</code>```

It should be:

```<code><input ref="autocomplete" v-model="address">
</code>```

Title: Vue.js this.$refs empty due to v-if

Body:
I have a simple Vue component that displays an address, but converts into a form to edit the address if the user clicks a button.  The address field is an autocomplete using Google Maps API.  Because the field is hidden (actually nonexistent) half the time, I have to re-instantiate the autocomplete each time the field is shown.

<template>

<input ref="autocomplete" v-model="address">

      <button @click="save">Save</button>

{{ address }}

      <button @click="edit">Edit</button>

</template>

Body:
I think it's because your "refs" is plural

<input refs="autocomplete" v-model="address">

It should be:

<input ref="autocomplete" v-model="address">


问:
align an element to the bottom of window
I am trying to use jQuery to calculate the window height then apply that value to a DIV (the container div) finally i want the jQuery to align an element to the bottom of the page.</p>

```<code><div id="wrapper">
    <div id="element-align">Here is the element i wish to align to the bottom</div>
</div>
</code>```

答:
Further to my question on your OP, this can be done in CSS:

```<code>#element-align {
    position: fixed;
    bottom: 0;
}
</code>```

If needs be you can also add left/right to the element, but the fixed positioning will mean that the element will always appear in the same place relative to the browser chrome, regardless of the scroll position of the page.

Body:
I am trying to use jQuery to calculate the window height then apply that value to a DIV (the container div) finally i want the jQuery to align an element to the bottom of the page.

Here is the element i wish to align to the bottom

Body:
Further to my question on your OP, this can be done in CSS:

#element-align {
    position: fixed;
    bottom: 0;
}

If needs be you can also add left/right to the element, but the fixed positioning will mean that the element will always appear in the same place relative to the browser chrome, regardless of the scroll position of the page.


问:
How do I use NetworkLink refreshMode in a KML/KMZ file that only contains folders of placemarks?
I have a bunch of Placemarks organized into folders, and then compressed into a KMZ file. I use Google Maps JavaScript API to display the KMZ file as a map overlay, but about once a week the overlay disappears. I believe this is due to caching expiration. I've read up a bit on NetworkLink and refreshMode (https://developers.google.com/kml/documentation/kmlreference#Link) but I'm stumped on how to implement this for my specific situation.

When I unzip the KMZ file, the only file inside is doc.kml, which looks something like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
    <name>My Document</name>
<StyleMap> A BUNCH OF STYLES, not sure why all of these exist </StyleMap>
<Folder>
        <name>My Folder</name>
        <open>1</open>
        <Folder>
            <name>My Subfolder</name>
            <Placemark>
                <description><![CDATA[<br><br><br>
    <table border="1" padding="0">
      <tr><td>cableid</td><td>1</td></tr>
      <tr><td>spanid</td><td>1076</td></tr>]]></description>
                <styleUrl>#m_ylw-pushpin</styleUrl>
                <LineString>
                    <extrude>1</extrude>
                    <tessellate>1</tessellate>
                    <coordinates>
                        -79.86184,40.349647,0 -79.861864,40.350147,0 -79.860741,40.350056,0
                    </coordinates>
                </LineString>
            </Placemark>
            <Placemark>
               ... etc
            </Placemark>
    </Folder>
</Folder>
</Document>
</kml>
</code>```

It does contain multiple Documents and nested Folders. Not sure if that matters.

Do I need to upload doc.kml to the server on its own, and then create a separate KML file with a NetworkLink that references doc.kml? Won't I lose the benefits of KMZ compression? Any other ideas?

答:
If you are starting out with creating your own KML and displaying it in Google Maps JavaScript APi, you can refer to this documentation.

The documentation also states that publicly hosting the KML file on the internet is a requirement for all applications that load KML into a KMLLayer, so that Google's servers can find and retrieve the content to display it on the map. It is only possible to display KML files if they are hosted at a publicly accessible URL that does not require authentication to access.

If you require access to private files, fine-grained control over caches, or send the browser viewport to a geospatial data server as a query parameter, it is recommended to use the  data layers instead of KmlLayer. This will direct your users' browsers to directly request resources from your web server.

You can also refer to this documentation of Google Maps Platform which discusses the performance and caching considerations and recommended tips for best performance.

Body:
I have a bunch of Placemarks organized into folders, and then compressed into a KMZ file. I use Google Maps JavaScript API to display the KMZ file as a map overlay, but about once a week the overlay disappears. I believe this is due to caching expiration. I've read up a bit on NetworkLink and refreshMode (https://developers.google.com/kml/documentation/kmlreference#Link) but I'm stumped on how to implement this for my specific situation.

When I unzip the KMZ file, the only file inside is doc.kml, which looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
    <name>My Document</name>

<Folder>
        <name>My Folder</name>
        <open>1</open>
        <Folder>
            <name>My Subfolder</name>
            <Placemark>
                <description><![CDATA[

cableid	1

spanid	1076
]]></description>

                <LineString>
                    <extrude>1</extrude>
                    <tessellate>1</tessellate>
                    <coordinates>
                        -79.86184,40.349647,0 -79.861864,40.350147,0 -79.860741,40.350056,0
                    </coordinates>
                </LineString>
            </Placemark>
            <Placemark>
               ... etc
            </Placemark>
    </Folder>
</Folder>
</Document>
</kml>

It does contain multiple Documents and nested Folders. Not sure if that matters.

Do I need to upload doc.kml to the server on its own, and then create a separate KML file with a NetworkLink that references doc.kml? Won't I lose the benefits of KMZ compression? Any other ideas?