问:
Using a ArrayAdapter won't work with fragment
I am trying to get an ArrayList from an activity and then display it inside a fragment  in a custom adapter. The problem it's that I cannot setAdapter to do so. The error it says the context it's wrong, when I created the Adapter.

Creare_istoricAdapter class:

```<code>public class Creare_istoricAdapter extends ArrayAdapter<Creare_istoric> {
    private static final String TAG = "Creareistoric_adapter";
    private Context mContext;
    int mResource;

    public Creare_istoricAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Creare_istoric> objects) {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        String id_alerta = getItem(position).getId_alerta();
        String tip_problema = getItem(position).getTip_problema();
        String data_ora= getItem(position).getData_ora();
        String stare_problema = getItem(position).getStare_problema();
        String descriere = getItem(position).getDescriere();
        Creare_istoric istoric = new Creare_istoric(id_alerta, tip_problema, data_ora, stare_problema, descriere);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);
        TextView text_tip_alerta_istoric = convertView.findViewById(R.id.text_tip_alerta_istoric);
        TextView text_ora_alerta_istoric = convertView.findViewById(R.id.text_ora_alerta_istoric);
        TextView text_stare_alerta_istoric = convertView.findViewById(R.id.text_stare_alerta_istoric);
        text_tip_alerta_istoric.setText(tip_problema);
        text_ora_alerta_istoric.setText(data_ora);
        text_stare_alerta_istoric.setText(stare_problema);
        return convertView;
    }
}
</code>```

The fragment class:

```<code>public class Fragment_alerte_trimise extends Fragment {
    public Fragment_alerte_trimise(){}
    ListView list_view_alerte_trimise;
    ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
        Bundle bundle_trimise;
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        Creare_istoricAdapter adapter = new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise);
        list_view_alerte_trimise.setAdapter(adapter);
    }

}
</code>```

The problems it's in new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise) , about the context, and is also greyed out, saying it's redundant.

EDIT:

I have changed the code following the answers below, but now when I open the activity that uses the fragment, it does not show the list at all. It's only an blank screen.

The fragment code:

```<code>public class Fragment_alerte_trimise extends Fragment {
   public Fragment_alerte_trimise(){}
   private ListView list_view_alerte_trimise;
   ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

   @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
}

   @Override
     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle_trimise = getArguments();
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        list_view_alerte_trimise.setAdapter(new Creare_istoricAdapter(getContext(), R.layout.istoric_alerte_adapter, alerteTrimise));
}
</code>```

}

The way I created the Parceable:

```<code>Bundle bundle_trimise = new Bundle();
bundle_trimise.putParcelableArrayList("alerte_trimise", alerteTrimise);
Fragment_alerte_trimise fg = new Fragment_alerte_trimise();
fg.setArguments(bundle_trimise);
</code>```

I have the ListView created in the layout that's inflated by the onCreateView, but when I use getView().findViewById it says that it may produce 'NullPointerException', and so does the getContext(), which says it might be null

答: Please try to use getContext() instead of this.

Body:
I am trying to get an ArrayList from an activity and then display it inside a fragment  in a custom adapter. The problem it's that I cannot setAdapter to do so. The error it says the context it's wrong, when I created the Adapter.

Creare_istoricAdapter class:

public class Creare_istoricAdapter extends ArrayAdapter<Creare_istoric> {
    private static final String TAG = "Creareistoric_adapter";
    private Context mContext;
    int mResource;

    public Creare_istoricAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Creare_istoric> objects) {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        String id_alerta = getItem(position).getId_alerta();
        String tip_problema = getItem(position).getTip_problema();
        String data_ora= getItem(position).getData_ora();
        String stare_problema = getItem(position).getStare_problema();
        String descriere = getItem(position).getDescriere();
        Creare_istoric istoric = new Creare_istoric(id_alerta, tip_problema, data_ora, stare_problema, descriere);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);
        TextView text_tip_alerta_istoric = convertView.findViewById(R.id.text_tip_alerta_istoric);
        TextView text_ora_alerta_istoric = convertView.findViewById(R.id.text_ora_alerta_istoric);
        TextView text_stare_alerta_istoric = convertView.findViewById(R.id.text_stare_alerta_istoric);
        text_tip_alerta_istoric.setText(tip_problema);
        text_ora_alerta_istoric.setText(data_ora);
        text_stare_alerta_istoric.setText(stare_problema);
        return convertView;
    }
}

The fragment class:

public class Fragment_alerte_trimise extends Fragment {
    public Fragment_alerte_trimise(){}
    ListView list_view_alerte_trimise;
    ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
        Bundle bundle_trimise;
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        Creare_istoricAdapter adapter = new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise);
        list_view_alerte_trimise.setAdapter(adapter);
    }

}

The problems it's in new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise) , about the context, and is also greyed out, saying it's redundant.

EDIT:

I have changed the code following the answers below, but now when I open the activity that uses the fragment, it does not show the list at all. It's only an blank screen.

The fragment code:

public class Fragment_alerte_trimise extends Fragment {
   public Fragment_alerte_trimise(){}
   private ListView list_view_alerte_trimise;
   ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

   @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
}

   @Override
     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle_trimise = getArguments();
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        list_view_alerte_trimise.setAdapter(new Creare_istoricAdapter(getContext(), R.layout.istoric_alerte_adapter, alerteTrimise));
}

}

The way I created the Parceable:

Bundle bundle_trimise = new Bundle();
bundle_trimise.putParcelableArrayList("alerte_trimise", alerteTrimise);
Fragment_alerte_trimise fg = new Fragment_alerte_trimise();
fg.setArguments(bundle_trimise);

I have the ListView created in the layout that's inflated by the onCreateView, but when I use getView().findViewById it says that it may produce 'NullPointerException', and so does the getContext(), which says it might be null


来源: stackexchange

问:
long text in a fixed size scrolable container flutter
hello world hope you're well
looking to have a container with a fixed size witch have in it a Text() mean long text more than the size of the container
Thank you for your help

in flutter

答:
Found the solution thanks to Stonik

Try to add scrollDirection (horizontal)

```<code>SingleChildScrollView(
scrollDirection: Axis.horizontal,
  child: Container(
      height: 200,
      child: Text(
          "Long text here which is longer than the container height"))),
</code>```

Default is vertical

or if you want to have with your height then you have to change the order (SingleChildScrollView inside Container)

```<code>Container(
    height: 200,
    child: SingleChildScrollView(
        child: Text(
            "Long text here which is longer than the container height"))),
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Found the solution thanks to Stonik

Try to add scrollDirection (horizontal)

SingleChildScrollView(
scrollDirection: Axis.horizontal,
  child: Container(
      height: 200,
      child: Text(
          "Long text here which is longer than the container height"))),

Default is vertical

or if you want to have with your height then you have to change the order (SingleChildScrollView inside Container)

Container(
    height: 200,
    child: SingleChildScrollView(
        child: Text(
            "Long text here which is longer than the container height"))),


问:
How to delete reversed value on Oracle Database by using Query?
Lets say i have some data on Oracle database like what i mentioned above .

TABLE

```<code>       COLUMN1 | COLUMN2 | Quantity

        100    |  2000   |     1
       2000    |  100    |     5
       3000    |  100    |     2
</code>```

As you can see column1 and column2 is reversed data . What is the efficient way to clean this data from oracleDb . I am not concerned about which one might delete . My main purpose is if table includes reverse data  one of them should be deleted . It is enough for me .

答:
The simplest way of doing it is using EXISTS as shown in the following example:

Oracle Data setup:

```<code>SQL> CREATE TABLE TBL (COL1, COL2, QUANTITY)
  2  AS SELECT * FROM
  3  (
  4  SELECT 100, 2000, 1 FROM DUAL UNION ALL
  5  SELECT 2000, 100, 5 FROM DUAL UNION ALL
  6  SELECT 3000, 100, 2 FROM DUAL
  7  );

Table created.
</code>```

Current data:

```<code>SQL> SELECT * FROM TBL;

      COL1       COL2   QUANTITY
---------- ---------- ----------
       100       2000          1
      2000        100          5
      3000        100          2
</code>```

Query to delete the duplicate:

```<code>SQL> DELETE FROM TBL T
  2  WHERE EXISTS (
  3          SELECT 1
  4          FROM TBL TIN
  5          WHERE T.COL1 = TIN.COL2
  6              AND T.COL2 = TIN.COL1
  7              AND T.ROWID > TIN.ROWID
  8      );

1 row deleted.
</code>```

Current view of the data:

```<code>SQL> SELECT * FROM TBL;

      COL1       COL2   QUANTITY
---------- ---------- ----------
       100       2000          1
      3000        100          2
</code>```

Cheers!!

Body:
Lets say i have some data on Oracle database like what i mentioned above .

TABLE

       COLUMN1 | COLUMN2 | Quantity

        100    |  2000   |     1
       2000    |  100    |     5
       3000    |  100    |     2

As you can see column1 and column2 is reversed data . What is the efficient way to clean this data from oracleDb . I am not concerned about which one might delete . My main purpose is if table includes reverse data  one of them should be deleted . It is enough for me .

Body:
The simplest way of doing it is using EXISTS as shown in the following example:

Oracle Data setup:

SQL> CREATE TABLE TBL (COL1, COL2, QUANTITY)
  2  AS SELECT * FROM
  3  (
  4  SELECT 100, 2000, 1 FROM DUAL UNION ALL
  5  SELECT 2000, 100, 5 FROM DUAL UNION ALL
  6  SELECT 3000, 100, 2 FROM DUAL
  7  );

Table created.

Current data:

SQL> SELECT * FROM TBL;

      COL1       COL2   QUANTITY
---------- ---------- ----------
       100       2000          1
      2000        100          5
      3000        100          2

Query to delete the duplicate:

SQL> DELETE FROM TBL T
  2  WHERE EXISTS (
  3          SELECT 1
  4          FROM TBL TIN
  5          WHERE T.COL1 = TIN.COL2
  6              AND T.COL2 = TIN.COL1
  7              AND T.ROWID > TIN.ROWID
  8      );

1 row deleted.

Current view of the data:

SQL> SELECT * FROM TBL;

      COL1       COL2   QUANTITY
---------- ---------- ----------
       100       2000          1
      3000        100          2

Cheers!!


问:
JavaScript Promise return Pending but i need only the value
can you help me with this code snippet? In this part, I make a ajax request to my c# controller only to validate a email and get the boolean value, but in the process, a promise returns status pending make a problem because i really need only the value inside the promise, here my code:

```<code>let Email = input;
let valida = ValidaEmail(Email);
console.log(valida);
</code>```

The Function

```<code>async function ValidaEmail(email) {
    let promise = new Promise(resolve => {
        var string = JSON.stringify(email);
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/Home/EmailisValid", true);
        xhttp.setRequestHeader("Content-type", "application/json");
        xhttp.onreadystatechange = () => {
            if (xhttp.readyState === 4 && xhttp.status === 200)
                resolve(xhttp.response);
        };
        xhttp.send(string);
    });
    let retorno = await promise;
    console.log(retorno);
}
</code>```

The Output:

答:
In the first you have to return result of promise from ValideEmail.

```<code>async function ValidaEmail(email) {
    let promise = new Promise(resolve => {
        var string = JSON.stringify(email);
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/Home/EmailisValid", true);
        xhttp.setRequestHeader("Content-type", "application/json");
        xhttp.onreadystatechange = () => {
            if (xhttp.readyState === 4 && xhttp.status === 200)
                resolve(xhttp.response);
        };
        xhttp.send(string);
    });
    let retorno = await promise;
    console.log(retorno);
    //////
    return retorno;
    //////
}
</code>```

When you use ValidateEmail function you have to use await or .then();

```<code>let Email = input;
///
let valida = await ValidaEmail(Email);
console.log(valida);
// or
ValidaEmail(Email).then((valida) => {
   console.log(valida);
})

</code>```

Body:
can you help me with this code snippet? In this part, I make a ajax request to my c# controller only to validate a email and get the boolean value, but in the process, a promise returns status pending make a problem because i really need only the value inside the promise, here my code:

let Email = input;
let valida = ValidaEmail(Email);
console.log(valida);

The Function

async function ValidaEmail(email) {
    let promise = new Promise(resolve => {
        var string = JSON.stringify(email);
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/Home/EmailisValid", true);
        xhttp.setRequestHeader("Content-type", "application/json");
        xhttp.onreadystatechange = () => {
            if (xhttp.readyState === 4 && xhttp.status === 200)
                resolve(xhttp.response);
        };
        xhttp.send(string);
    });
    let retorno = await promise;
    console.log(retorno);
}

The Output:

Body:
In the first you have to return result of promise from ValideEmail.

async function ValidaEmail(email) {
    let promise = new Promise(resolve => {
        var string = JSON.stringify(email);
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/Home/EmailisValid", true);
        xhttp.setRequestHeader("Content-type", "application/json");
        xhttp.onreadystatechange = () => {
            if (xhttp.readyState === 4 && xhttp.status === 200)
                resolve(xhttp.response);
        };
        xhttp.send(string);
    });
    let retorno = await promise;
    console.log(retorno);
    //////
    return retorno;
    //////
}

When you use ValidateEmail function you have to use await or .then();

let Email = input;
///
let valida = await ValidaEmail(Email);
console.log(valida);
// or
ValidaEmail(Email).then((valida) => {
   console.log(valida);
})


问:
How to scroll up through Instagram direct messages using Selenium and Python with Chrome Device Toolbar
I'm trying to automate the scrolling on Instagram's Direct to be able to get to the beginning of an Instagram chat. Also I think that is not possible to select the scroll bar using xpath, so maybe is necessary to use an automatic key-pressing loop with the "home" key or "page up". But honestly I dont really know how to do this. Ps: If you keep the "home" key pressed you only will be able to scroll up a few pages before the scrolling just stops, so you need to release the key after a couple of seconds to keep scrolling up. So maybe this is not the best way to do what I'm looking for.
I hope somebody can help me, thank you very much!

Source Code:

```<code>    from selenium import webdriver
    from time import sleep
    from secrets import username, pw

    from selenium.webdriver.chrome.options import Options

    mobile_emulation = {

        "deviceMetrics": { "width": 360, "height": 640, "pixelRatio": 3.0 },

        "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19" }

    chrome_options = Options()

    chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)

    class MsgBot:
def __init__(self):
    self.driver = webdriver.Chrome(chrome_options = chrome_options)

    self.driver.get("https://instagram.com")
    sleep(2)
    self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/div[2]/button').click()
    sleep(5)
    login_input = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/form/div[4]/div/label/input')
    login_input.send_keys(username)
    pw_input = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/form/div[5]/div/label/input')
    pw_input.send_keys(pw)
    login_btn = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/form/div[7]/button').click()
    sleep(4)
    self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/button').click()
    sleep(4)
    self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div[3]/button[2]').click()
    sleep(2)
    self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav[1]/div/div/header/div/div[2]/a/div').click()
    sleep(4)
    self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div[3]/button[2]').click()
    sleep(4)
    self.driver.find_element_by_xpath('//*[@id="react-root"]/section/div[2]/div/div/div[2]/div/div[2]/a').click()
    sleep(3)
    #scroll should begin
</code>```

MsgBot()

答:
For scrolling to the element you can use:

```<code>from selenium.webdriver.common.action_chains import ActionChains

actions = ActionChains(driver)
element = driver.find_element_by_id("id")
actions.move_to_element(element).perform()
</code>```

or

```<code>driver.execute_script("arguments[0].scrollIntoView();", element)
</code>```

to scroll to element using JavaScript code

Body:
I'm trying to automate the scrolling on Instagram's Direct to be able to get to the beginning of an Instagram chat. Also I think that is not possible to select the scroll bar using xpath, so maybe is necessary to use an automatic key-pressing loop with the "home" key or "page up". But honestly I dont really know how to do this. Ps: If you keep the "home" key pressed you only will be able to scroll up a few pages before the scrolling just stops, so you need to release the key after a couple of seconds to keep scrolling up. So maybe this is not the best way to do what I'm looking for.
I hope somebody can help me, thank you very much!

Source Code:

    from selenium import webdriver
    from time import sleep
    from secrets import username, pw

    from selenium.webdriver.chrome.options import Options

    mobile_emulation = {

        "deviceMetrics": { "width": 360, "height": 640, "pixelRatio": 3.0 },

        "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19" }

    chrome_options = Options()

    chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)

    class MsgBot:
def __init__(self):
    self.driver = webdriver.Chrome(chrome_options = chrome_options)

    self.driver.get("https://instagram.com")
    sleep(2)
    self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/div[2]/button').click()
    sleep(5)
    login_input = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/form/div[4]/div/label/input')
    login_input.send_keys(username)
    pw_input = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/form/div[5]/div/label/input')
    pw_input.send_keys(pw)
    login_btn = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/form/div[7]/button').click()
    sleep(4)
    self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/button').click()
    sleep(4)
    self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div[3]/button[2]').click()
    sleep(2)
    self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav[1]/div/div/header/div/div[2]/a/div').click()
    sleep(4)
    self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div[3]/button[2]').click()
    sleep(4)
    self.driver.find_element_by_xpath('//*[@id="react-root"]/section/div[2]/div/div/div[2]/div/div[2]/a').click()
    sleep(3)
    #scroll should begin

MsgBot()

Body:
For scrolling to the element you can use:

from selenium.webdriver.common.action_chains import ActionChains

actions = ActionChains(driver)
element = driver.find_element_by_id("id")
actions.move_to_element(element).perform()

or

driver.execute_script("arguments[0].scrollIntoView();", element)

to scroll to element using JavaScript code


问:
works in ie9 and ff4 - not in ie7 or ie 8?
I wrote this script awhile back and have modified it to use css sprites to cut down on images.  Everything works perfect in ie9 and ff4, however, I noticed it will not show in ie7/ie8... It must be a css or js problem, but I certainly cannot see anything that would be preventing the older ie's from displaying the code...

I have included the entire contents below in a 'test' page which includes everything... if someone can point me out to why this is not working in ie7 or ie8 I would be very grateful!

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<style type="text/css">
#social16 {height:16px;font-size:13px; color:#0066ff; font-weight:bold;}
#sb16 {margin: 0px; padding:0px; height:16px; display: inline;line-height:16px;}
#sb16 li {list-style-type:none;float:left;padding:0 5px 0 0;}
#sb16 li a {background:url(social.png);background-repeat:no-repeat;display: block;height: 16px;width:16px;}
#sb16 li a.item0 {background-position:0px 0px;}
#sb16 li a.item1 {background-position:-16px 0px;}
#sb16 li a.item2 {background-position:-32px 0px;}
#sb16 li a.item3 {background-position:-48px 0px;}
#sb16 li a.item4 {background-position:-64px 0px;}
#sb16 li a.item5 {background-position:-80px 0px;}
#sb16 li a.item6 {background-position:-96px 0px;}
</style>
</head>
<body>
<div id="social16"></div>
<script type="text/javascript">
(function(){

var sites = [
        ['Send to Facebook', 'http://www.facebook.com/sharer.php?u={url}&t={title}'],
        ['Tweet This', 'http://twitter.com/share?text={title}&url={url}'],
        ['Send to StumbleUpon', 'http://www.stumbleupon.com/submit?url={url}&title={title}'],
        ['Digg This', 'http://digg.com/submit?phase=2&url={url}&title={title}'],
        ['Send to GoogleBuzz', 'http://www.google.com/buzz/post?message={title}&url={url}'],
        ['Send to Reddit', 'http://reddit.com/submit?url={url}&title={title}'],
        ['Email to Friends', 'mailto:?subject={title}&body={url}'],
    ];

var url = encodeURIComponent(location.href),
    url = url.replace( "#", "" ),
    title = encodeURIComponent(document.title),
    html = '<ul id="sb16"><li>Share this ... </li>';

for (var i = 0, len = sites.length; i < len; i++) {
    var site = sites[i],
    link = site[1].replace('{url}', url).replace('{title}', title);

    html += '<li><a class="item' + i + '" href="#" title="' + site[0] + '" onclick="window.open(\'' + link + '\')"></a></li>';
}

html += '</ul>';

document.getElementById("social16").innerHTML=(html);

})();
</script>
</body>
</html>
</code>```

答:
```<code>var sites = [
        ...
        ['Email to Friends', 'mailto:?subject={title}&body={url}'],
    ];
</code>```

Your last element has a trailing ,. Remove it.

Further Reading.

ContentLicense: CC BY-SA 3.0

Body:
I wrote this script awhile back and have modified it to use css sprites to cut down on images.  Everything works perfect in ie9 and ff4, however, I noticed it will not show in ie7/ie8... It must be a css or js problem, but I certainly cannot see anything that would be preventing the older ie's from displaying the code...

I have included the entire contents below in a 'test' page which includes everything... if someone can point me out to why this is not working in ie7 or ie8 I would be very grateful!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Body:
var sites = [
        ...
        ['Email to Friends', 'mailto:?subject={title}&amp;body={url}'],
    ];

Your last element has a trailing ,. Remove it.

Further Reading.


问:
Change default TextFormField's icon color from grey to anything but show primary color on selection
I want to change default colour of icon of TextFormField, which will also get changes on selection. There are few way to change colour but non of them works for me.

1. Set icon color

When changing icon colour directly as below the icon colour will not change when selected, below is the code of the same and screenshot which shows red colour when field is selected or not selected.

```<code>     TextFormField(
        maxLength: 15,
        decoration: InputDecoration(
          labelText: "USER NAME",
          prefixIcon: IconTheme(data: IconThemeData(
            color: Colors.redAccent
          ), child: Icon(Icons.email,))
        ),
        onSaved: (username) => _username = username,
      ),
</code>```

2. Leave it default

This will show grey colour when field is not selected and primary colour when field is selected. Below is the screenshot of the same. Here i want to change the colour of icon from grey to red and want to show primary colour on selection.

NOTE:- It will be good if we can do this using theme

答:
The code below  will generate the FocusNodes you need to manage the focus of your TextFormFields and do a setState when the focus changes from one field to another. We are just creating a list of focus nodes, listening to changes on each of them and assigning them to a field:

```<code>List<FocusNode> _focusNodes = [
  FocusNode(),
  FocusNode(),
  FocusNode(),
  FocusNode(),
];

@override
void initState() {
  _focusNodes.forEach((node){
    node.addListener(() {
      setState(() {});
    });
  });
  super.initState();
}

@override
Widget build(BuildContext context) {
  return Column(
    children: <Widget>[
      TextFormField(
        focusNode: _focusNodes[0],
        decoration: InputDecoration(
          prefixIcon: Icon(Icons.email,
            color: _focusNodes[0].hasFocus ? Theme.of(context).accentColor : Colors.grey,
          ),
        ),
      ),
      TextFormField(
        focusNode: _focusNodes[1],
        decoration: InputDecoration(
          prefixIcon: Icon(Icons.email,
            color: _focusNodes[1].hasFocus ? Theme.of(context).accentColor : Colors.grey,
          ),
        ),
      ),
      TextFormField(
        focusNode: _focusNodes[2],
        decoration: InputDecoration(
          prefixIcon: Icon(Icons.email,
            color: _focusNodes[2].hasFocus ? Theme.of(context).accentColor : Colors.grey,
          ),
        ),
      ),
    ],
  );
}
</code>```

Body:
I want to change default colour of icon of TextFormField, which will also get changes on selection. There are few way to change colour but non of them works for me.

1. Set icon color

When changing icon colour directly as below the icon colour will not change when selected, below is the code of the same and screenshot which shows red colour when field is selected or not selected.

     TextFormField(
        maxLength: 15,
        decoration: InputDecoration(
          labelText: "USER NAME",
          prefixIcon: IconTheme(data: IconThemeData(
            color: Colors.redAccent
          ), child: Icon(Icons.email,))
        ),
        onSaved: (username) => _username = username,
      ),

2. Leave it default

This will show grey colour when field is not selected and primary colour when field is selected. Below is the screenshot of the same. Here i want to change the colour of icon from grey to red and want to show primary colour on selection.

NOTE:- It will be good if we can do this using theme

Body:
The code below  will generate the FocusNodes you need to manage the focus of your TextFormFields and do a setState when the focus changes from one field to another. We are just creating a list of focus nodes, listening to changes on each of them and assigning them to a field:

List<FocusNode> _focusNodes = [
  FocusNode(),
  FocusNode(),
  FocusNode(),
  FocusNode(),
];

@override
void initState() {
  _focusNodes.forEach((node){
    node.addListener(() {
      setState(() {});
    });
  });
  super.initState();
}

@override
Widget build(BuildContext context) {
  return Column(
    children: <Widget>[
      TextFormField(
        focusNode: _focusNodes[0],
        decoration: InputDecoration(
          prefixIcon: Icon(Icons.email,
            color: _focusNodes[0].hasFocus ? Theme.of(context).accentColor : Colors.grey,
          ),
        ),
      ),
      TextFormField(
        focusNode: _focusNodes[1],
        decoration: InputDecoration(
          prefixIcon: Icon(Icons.email,
            color: _focusNodes[1].hasFocus ? Theme.of(context).accentColor : Colors.grey,
          ),
        ),
      ),
      TextFormField(
        focusNode: _focusNodes[2],
        decoration: InputDecoration(
          prefixIcon: Icon(Icons.email,
            color: _focusNodes[2].hasFocus ? Theme.of(context).accentColor : Colors.grey,
          ),
        ),
      ),
    ],
  );
}


问:
How do I generate array values in Vue.js and show them?
I only just started learning vue, trying to practice

export default {
    name:'FrontPage',
    data: function(){
        return {
            player: [
                { 'ap': ngen() },
                { 'df': ngen() },
                { 'iq': ngen() },
            ]
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
    <div>
        <h2> {{ player.ap }} </h2>
        <h2> {{ player.df }} </h2>
        <h2> {{ player.iq }} </h2>
    </div>
</template></code>```

答:
Basing on what you want to get as results, I think it's not necessary to have the player array in your data object.

Just define your random method and call it in your template.

<template>

 {{ ngen() }}

 {{ ngen() }}

 {{ ngen() }}

</template>
```

or just do a call of the JavaScript random function directly

Body:
I only just started learning vue, trying to practice

export default {
    name:'FrontPage',
    data: function(){
        return {
            player: [
                { 'ap': ngen() },
                { 'df': ngen() },
                { 'iq': ngen() },
            ]
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}

<template>

 {{ player.ap }}

 {{ player.df }}

 {{ player.iq }}

</template>

Body:
Basing on what you want to get as results, I think it's not necessary to have the player array in your data object.

Just define your random method and call it in your template.

<template>
    <div>
        <h2> {{ ngen() }} </h2>
        <h2> {{ ngen() }} </h2>
        <h2> {{ ngen() }} </h2>
    </div>
</template>

or just do a call of the JavaScript random function directly


问:
Overloading a function using templates
I am trying to define a function using templates and I want the typename to be either int or anEnum (a specific enum I had defined). I have tried the following but I have failed:

```<code>template <int | anEnum T> // or <int T, anEnum T> or <int, anEnum T>
bool isFunction(const T &aVariable){}
</code>```

What I am trying to do is to use templates, instead of defining two overloaded functions.
I'd prefer the function to be called as the following, without the programmer having to consider the type

```<code>isFunction(aVariable) // and not isFunction<int> (aVariable) nor isFunction<anEnum> (aVariable)
</code>```

Basically, I want this function to be templated for int and aNum types. I have searched for this, but could not find the answer. What may I be missing? Thank you,

答:
There are a couple of ways to accomplish this. All involve using the type_traits header. You can static assert on the types in question in the body of the function, for instance.

Or, if you need to consider this function among other overloads, a SFINAE technique can be employed.

```<code>template<typename T>
auto isFunction(const T &aVariable)
  -> std::enable_if_t<std::is_same<T, int>::value || std::is_same<T,anEnum>::value, bool> {
}
</code>```

This will remove the function from an overload set before it's called if the types don't match. But if you don't need this behavior, a static assertion does allow for a more programmer friendly error message.

Title: Overloading a function using templates

Body:
I am trying to define a function using templates and I want the typename to be either int or anEnum (a specific enum I had defined). I have tried the following but I have failed:

template <int | anEnum T> // or <int T, anEnum T> or <int, anEnum T>
bool isFunction(const T &aVariable){}

What I am trying to do is to use templates, instead of defining two overloaded functions.
I'd prefer the function to be called as the following, without the programmer having to consider the type

isFunction(aVariable) // and not isFunction<int> (aVariable) nor isFunction<anEnum> (aVariable)

Basically, I want this function to be templated for int and aNum types. I have searched for this, but could not find the answer. What may I be missing? Thank you,

Body:
There are a couple of ways to accomplish this. All involve using the type_traits header. You can static assert on the types in question in the body of the function, for instance.

Or, if you need to consider this function among other overloads, a SFINAE technique can be employed.

template<typename T>
auto isFunction(const T &aVariable)
  -> std::enable_if_t<std::is_same<T, int>::value || std::is_same<T,anEnum>::value, bool> {
}

This will remove the function from an overload set before it's called if the types don't match. But if you don't need this behavior, a static assertion does allow for a more programmer friendly error message.


问:
Multi language speech translation
Can Azure cognitive services  assist to translate multi languages (e.g. japanese,chinese and spanish) in 1 audio clips to English in text form.
Is the multi translation for a single file is possible?</p>

答:
Video Indexer (VI) supports multi language identification and transcription (public preview) for cases where speakers do not overlap.
if the translator was recorded on a separate channel, VI supports split channel conversations detection and transcription where speech overlap is supported.

Once the multi-language transcription is in place, the customer can translate it to multiple different languages.

Title: Multi language speech translation


问:
How to write Perl modified content into a file in Python scripts?
My research data is not a normal file. The column number of each row may be different. I want to convert the "dat" file into "*.csv" file using Perl because it can run efficiently (I have poor experience in Python). Below is the script I ran. It works fine in Linux, but it does not output the context in Python scripts.

```<code>new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
perl -p -e 's/\\t\s+|\s+/,/g' $new_dat_file |perl -p -e 's/,FRAM/\\nFRAM/g' >  $new_csv_file
</code>```

Above codes work in Linux. I improved them in Python scripts. If I use below command

```<code>import os
new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g'
os.system(cmd)
</code>```

I can see the output correctly. However, if I modify cmd values like below to save the output into a csv file, but I got an empty file.

```<code>cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g' > " + new_csv_file
</code>```

How can I fix this issue? If I cannot do so, any other alternative way available? Any further suggestion would be highly appreciated.

BTW: partial data listed below

```<code>FRAM_#            0            0(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.008
FRAM_#          100           25(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.955
FRAM_#          200           50(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.993
FRAM_#          300           75(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.973
FRAM_#          400          100(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.988
FRAM_#          500          125(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.033
FRAM_#          600          150(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.032
FRAM_#          700          175(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.986
FRAM_#          800          200(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.061
FRAM_#          900          225(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.078
FRAM_#         1000          250(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.922
FRAM_#         1100          275(fs)  CN= 2 PRMRYTGT     14689      H      17402      O  1.257     15449      O  1.430
FRAM_#       303200        75800(fs)  CN= 0 PRMRYTGT_BD     14689      H
FRAM_#       921200       230300(fs)  CN= 1 PRMRYTGT_BD     14689      H        8375      O  1.062
FRAM_#      1078700       269675(fs)  CN= 1 PRMRYTGT_BD     14689      H       12971      O  1.507
FRAM_#     18203400      4550850(fs)  CN= 1 PRMRYTGT_BD     14689      H       16172      O  1.507
</code>```

I hope to get output like below:

```<code>FRAM_#,0,0(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.008
FRAM_#,100,25(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.955
FRAM_#,200,50(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.993
FRAM_#,300,75(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.973
FRAM_#,400,100(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.988
FRAM_#,500,125(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.033
FRAM_#,600,150(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.032
FRAM_#,700,175(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.986
FRAM_#,800,200(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.061
FRAM_#,900,225(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.078
FRAM_#,1000,250(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.922
FRAM_#,1100,275(fs),CN=,2,PRMRYTGT,14689,H,17402,O,1.257,15449,O,1.430
</code>```

Body:
My research data is not a normal file. The column number of each row may be different. I want to convert the "dat" file into "*.csv" file using Perl because it can run efficiently (I have poor experience in Python). Below is the script I ran. It works fine in Linux, but it does not output the context in Python scripts.

new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
perl -p -e 's/\\t\s+|\s+/,/g' $new_dat_file |perl -p -e 's/,FRAM/\\nFRAM/g' >  $new_csv_file

Above codes work in Linux. I improved them in Python scripts. If I use below command

import os
new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g'
os.system(cmd)

I can see the output correctly. However, if I modify cmd values like below to save the output into a csv file, but I got an empty file.

cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g' > " + new_csv_file

How can I fix this issue? If I cannot do so, any other alternative way available? Any further suggestion would be highly appreciated.

BTW: partial data listed below

FRAM_#            0            0(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.008
FRAM_#          100           25(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.955
FRAM_#          200           50(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.993
FRAM_#          300           75(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.973
FRAM_#          400          100(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.988
FRAM_#          500          125(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.033
FRAM_#          600          150(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.032
FRAM_#          700          175(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.986
FRAM_#          800          200(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.061
FRAM_#          900          225(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.078
FRAM_#         1000          250(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.922
FRAM_#         1100          275(fs)  CN= 2 PRMRYTGT     14689      H      17402      O  1.257     15449      O  1.430
FRAM_#       303200        75800(fs)  CN= 0 PRMRYTGT_BD     14689      H
FRAM_#       921200       230300(fs)  CN= 1 PRMRYTGT_BD     14689      H        8375      O  1.062
FRAM_#      1078700       269675(fs)  CN= 1 PRMRYTGT_BD     14689      H       12971      O  1.507
FRAM_#     18203400      4550850(fs)  CN= 1 PRMRYTGT_BD     14689      H       16172      O  1.507

I hope to get output like below:

FRAM_#,0,0(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.008
FRAM_#,100,25(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.955
FRAM_#,200,50(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.993
FRAM_#,300,75(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.973
FRAM_#,400,100(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.988
FRAM_#,500,125(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.033
FRAM_#,600,150(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.032
FRAM_#,700,175(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.986
FRAM_#,800,200(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.061
FRAM_#,900,225(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.078
FRAM_#,1000,250(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.922
FRAM_#,1100,275(fs),CN=,2,PRMRYTGT,14689,H,17402,O,1.257,15449,O,1.430

Body:
This task is very simple - replace all sequential spaces [ +] to comma [,] -- done.

use strict;
use warnings;
use feature 'say';

my $infile  = shift || die 'Provide input file';
my $outfile = shift || die 'Provide output file';

my $fh;     # filehandle

open $fh, '<', $infile
    or die "Couldn't open $infile";

my @data = <$fh>;

close $fh;

open $fh, '>', $outfile
    or die "Couldn't open $outfile";

for (@data) {
    chomp;
    s/ +/,/g;
    say $fh $_;
}

close $fh;

Output

FRAM_#,0,0(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.008
FRAM_#,100,25(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.955
FRAM_#,200,50(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.993
FRAM_#,300,75(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.973
FRAM_#,400,100(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.988
FRAM_#,500,125(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.033
FRAM_#,600,150(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.032
FRAM_#,700,175(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.986
FRAM_#,800,200(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.061
FRAM_#,900,225(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.078
FRAM_#,1000,250(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.922
FRAM_#,1100,275(fs),CN=,2,PRMRYTGT,14689,H,17402,O,1.257,15449,O,1.430
FRAM_#,303200,75800(fs),CN=,0,PRMRYTGT_BD,14689,H
FRAM_#,921200,230300(fs),CN=,1,PRMRYTGT_BD,14689,H,8375,O,1.062
FRAM_#,1078700,269675(fs),CN=,1,PRMRYTGT_BD,14689,H,12971,O,1.507
FRAM_#,18203400,4550850(fs),CN=,1,PRMRYTGT_BD,14689,H,16172,O,1.507


问:
Redirecting after form submission with user input in the URL
I need to have a form that when filled out will create a variable and then goto a url with that variable in the url.

Something like this (but that works) :)

```<code><form action="?????" method="?????">

Number: <input type="text" name="url1" value=""><br>

<input type="submit" name="submit" value="Goto URL">
</form>
</code>```

When the submit is pressed I need it to goto http://somewhere.com?url=VALUEHERE

Any ideas?

答:
```<code><form>
Number: <input type="text" name="url1" id="url1" value=""><br>
<input type="submit" name="submit" value="Goto URL" onclick="redirect()">
</form>

<script>
function redirect()
{
  window.location='http://somewhere.com?url=' + document.getElementByID('url1').value;
}
</script>
</code>```

Body:
I need to have a form that when filled out will create a variable and then goto a url with that variable in the url.

Something like this (but that works) :)

<form action="?????" method="?????">

Number: <input type="text" name="url1" value="">

<input type="submit" name="submit" value="Goto URL">
</form>

When the submit is pressed I need it to goto http://somewhere.com?url=VALUEHERE

Any ideas?


问:
Visual Studio 2019 - Unable to debug Azure functions - (Desktop CLR (.NETFramework) versus Managed (CoreCLR)' debugger
I have installed the  Visual Studio 2019 community version 16.4.4 on a brand new laptop

OS:- Windows 10 Home Single Language

The following are the .NET Core SDKS installed in my laptop

The command dotnet --info  gave me the following details

I  created a Azure function with V3 template

The project settings are given below

When I  try to debug , i get the following error

A fatal error has occurred and debugging needs to be terminated. The debugger was configured to use the Desktop CLR (.NETFramework) Managed debugger, but the target process loaded the CoreCLR (.Net Core) runtime. To debug this project, configure it to use the 'Managed (CoreCLR)' debugger."

Tried several options  like the one mentioned in the link below

https://social.msdn.microsoft.com/Forums/en-US/59f880f7-ed60-4842-bc55-a9400971c58b/problem-debugging-net-core?forum=vsdebug

答:
I still have this issue after reinstalling my VS2019, downloading the latest sdk and downloading the core tools multiple times. Seems like the only way for now is to run without using the debugger (Ctrl + F5). Sometimes I downgrade the function to v2.1 for this only happens on v3 functions.

Edit: I got this fixed when I updated my VS to 16.5.1


问:
Swift Array - Check if an index exists
In Swift, is there any way to check if an index exists in an array without a fatal error being thrown?

I was hoping I could do something like this:

```<code>let arr: [String] = ["foo", "bar"]
let str: String? = arr[1]
if let str2 = arr[2] as String? {
    // this wouldn't run
    println(str2)
} else {
    // this would be run
}
</code>```

But I get

fatal error: Array index out of range

答:
```<code>extension Array {
    func isValidIndex(_ index : Int) -> Bool {
        return index < self.count
    }
}
</code>```

```<code>let array = ["a","b","c","d"]

func testArrayIndex(_ index : Int) {

    guard array.isValidIndex(index) else {
        print("Handle array index Out of bounds here")
        return
    }

}
</code>```

It's work for me to handle indexOutOfBounds.

Title: Swift Array - Check if an index exists

Body:
In Swift, is there any way to check if an index exists in an array without a fatal error being thrown?

I was hoping I could do something like this:

let arr: [String] = ["foo", "bar"]
let str: String? = arr[1]
if let str2 = arr[2] as String? {
    // this wouldn't run
    println(str2)
} else {
    // this would be run
}

But I get

fatal error: Array index out of range

Body:
extension Array {
    func isValidIndex(_ index : Int) -> Bool {
        return index < self.count
    }
}

let array = ["a","b","c","d"]

func testArrayIndex(_ index : Int) {

    guard array.isValidIndex(index) else {
        print("Handle array index Out of bounds here")
        return
    }

}

It's work for me to handle indexOutOfBounds.


问:
SwiftUI NavigationBar height
How to get current NavigationBar height? In UIKit we could get

```<code>navigationController?.navigationBar.frame.height
</code>```

but can't find anything for SwiftUI...

答:
Based on this post (thanks to Asperi): https://stackoverflow.com/a/59972635/12299030

```<code>struct NavBarAccessor: UIViewControllerRepresentable {
    var callback: (UINavigationBar) -> Void
    private let proxyController = ViewController()

    func makeUIViewController(context: UIViewControllerRepresentableContext<NavBarAccessor>) ->
                              UIViewController {
        proxyController.callback = callback
        return proxyController
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavBarAccessor>) {
    }

    typealias UIViewControllerType = UIViewController

    private class ViewController: UIViewController {
        var callback: (UINavigationBar) -> Void = { _ in }

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            if let navBar = self.navigationController {
                self.callback(navBar.navigationBar)
            }
        }
    }
}
</code>```

And then we can call this from any View:

```<code>.background(NavBarAccessor { navBar in
      print(">> NavBar height: \(navBar.bounds.height)")
                // !! use as needed, in calculations, @State, etc.
 })
</code>```

Title: SwiftUI NavigationBar height

Body:
How to get current NavigationBar height? In UIKit we could get

navigationController?.navigationBar.frame.height

but can't find anything for SwiftUI...

Body:
Based on this post (thanks to Asperi): https://stackoverflow.com/a/59972635/12299030

struct NavBarAccessor: UIViewControllerRepresentable {
    var callback: (UINavigationBar) -> Void
    private let proxyController = ViewController()

    func makeUIViewController(context: UIViewControllerRepresentableContext<NavBarAccessor>) ->
                              UIViewController {
        proxyController.callback = callback
        return proxyController
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavBarAccessor>) {
    }

    typealias UIViewControllerType = UIViewController

    private class ViewController: UIViewController {
        var callback: (UINavigationBar) -> Void = { _ in }

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            if let navBar = self.navigationController {
                self.callback(navBar.navigationBar)
            }
        }
    }
}

And then we can call this from any View:

.background(NavBarAccessor { navBar in
      print(">> NavBar height: \(navBar.bounds.height)")
                // !! use as needed, in calculations, @State, etc.
 })


问:
Jquery - Accessing input element within a class by its index
I need some pointer here. I am trying to set the value of multiple input text within a class by its index value. The extra validate class is just for inline form validation and I think it is not the problem.

I was able to access multiple check boxes within a class using the same method but I can't figure this one out. Can someone please give me a hint as to what I did wrong? Thank you.

Script

```<code>//--(4) Load Delivery Cost Input Box
var tmpstr = $('#editDeliveryCost').html();
if (tmpstr != ""){
   var tmparray = tmpstr.split(',');
   for (i = 0; i < tmparray.length; ++i) {
      $('.typeDeliveryCost:eq('+(tmparray[i]-1)+')').val(tmparray[i]);
   }
</code>```

HTML

```<code><input type="text" name='cost[]' id='inp01' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp02' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp03' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp04' class="validate[required,custom[price]] typeDeliveryCost" />
</code>```

答:
Shouldnt

```<code>$('.typeDeliveryCost:eq('+(tmparray[i]-1)+')').val(tmparray[i]);
</code>```

be

```<code>$('.typeDeliveryCost:eq(' + i + ')').val(tmparray[i]);
</code>```

:eq(index) takes a zero-based index (eq-selector)

Body:
I need some pointer here. I am trying to set the value of multiple input text within a class by its index value. The extra validate class is just for inline form validation and I think it is not the problem.

I was able to access multiple check boxes within a class using the same method but I can't figure this one out. Can someone please give me a hint as to what I did wrong? Thank you.

Script

//--(4) Load Delivery Cost Input Box
var tmpstr = $('#editDeliveryCost').html();
if (tmpstr != ""){
   var tmparray = tmpstr.split(',');
   for (i = 0; i < tmparray.length; ++i) {
      $('.typeDeliveryCost:eq('+(tmparray[i]-1)+')').val(tmparray[i]);
   }

HTML

<input type="text" name='cost[]' id='inp01' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp02' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp03' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp04' class="validate[required,custom[price]] typeDeliveryCost" />

Body:
Shouldnt

$('.typeDeliveryCost:eq('+(tmparray[i]-1)+')').val(tmparray[i]);

be

$('.typeDeliveryCost:eq(' + i + ')').val(tmparray[i]);

:eq(index) takes a zero-based index (eq-selector)


问:
Finding a min() value on each row using an arrayformula() within Google Sheets
I'm kind of in a pickle with a sheet I've been working on, I was looking for some clarification. For some reason my old account is gone that Ive for years :(, I apologize.

I'm trying get a min value for each row I've added data in. There is 2 columns where I need to convert the data first, and then find the lowest value for for all 3 columns for each row.

I've tried multiple things and only entering the formula I've created for each row works perfectly.
For Instance:

=MIN( IF(E124 > 0, E124*$E$6), IF(F124 > 0, F124*$F$6), IF(G124 > 0, G124) )

I've tried to use other examples, however, I am not familiar with QUERY. Trying to do simple calculations (adding) within the formula is confusing. Example I've tried using:

```<code>=QUERY(TRANSPOSE(QUERY(TRANSPOSE(A1:C),
 "select "&REGEXREPLACE(JOIN( , ARRAYFORMULA(IF(LEN(A1:A&B1:B&C1:C),
 "min(Col"&ROW(A1:A)-ROW(A1)+1&"),", ""))), ".\z", "")&"")),
 "select Col2")
</code>```

That has multiple problems when adding it. I want to ignore empty cells and text like headers. It will not write over text, and does not execute (gives me an error about overwriting values).

I've tried writing an =arrayformula but does not like calculating the min value. It does do the calculations for the rows.

```<code>=ArrayFormula(IF(ISBLANK({E8:E;F8:8;G8:8}), "", added my formula here))
</code>```

Down below was something I've worked on for hours, I believe the problem is selecting the ranges inside the MIN function that is causing the problems

```<code>=arrayformula(IF(LEN(E8:G)<>0, MIN( IF(E8:E > 0, E8:E*$E$6), IF(F8:F > 0, F8:F*$F$6), IF(G8:G > 0, G124) ),)
</code>```

If there's a way to do this, I'd really appreciate some help

LINK: a viewable version of a sample I made as my actual sheet is over 500 lines long.
https://docs.google.com/spreadsheets/d/133LJHY3s45ZyxWq0PWew1KikbyNE4MTt-wOeWHBrZY0/edit?usp=sharing

答:
In cell O3 give this a try

```<code>=ArrayFormula(TO_DOLLARS(index(transpose(query(transpose(E3:G18*{M5, N5, 1}),"select "&join("),","max(Col"&row(indirect("A3:A18"))-2)&")")),,2)))
</code>```

and see if that delivers the expected output?

In case, you'll have more then one value in the columns E:G you could try

```<code>=ArrayFormula(TO_DOLLARS(index(transpose(query(transpose(if(ISNUMBER(E3:G18), E3:G18, 99^99)*{M5, N5, 1}),"select "&join("),","min(Col"&row(indirect("A3:A18"))-2)&")")),,2)))
</code>```

Body:
I'm kind of in a pickle with a sheet I've been working on, I was looking for some clarification. For some reason my old account is gone that Ive for years :(, I apologize.

I'm trying get a min value for each row I've added data in. There is 2 columns where I need to convert the data first, and then find the lowest value for for all 3 columns for each row.

I've tried multiple things and only entering the formula I've created for each row works perfectly.
For Instance:

=MIN( IF(E124 > 0, E124*$E$6), IF(F124 > 0, F124*$F$6), IF(G124 > 0, G124) )

I've tried to use other examples, however, I am not familiar with QUERY. Trying to do simple calculations (adding) within the formula is confusing. Example I've tried using:

=QUERY(TRANSPOSE(QUERY(TRANSPOSE(A1:C),
 "select "&REGEXREPLACE(JOIN( , ARRAYFORMULA(IF(LEN(A1:A&B1:B&C1:C),
 "min(Col"&ROW(A1:A)-ROW(A1)+1&"),", ""))), ".\z", "")&"")),
 "select Col2")

That has multiple problems when adding it. I want to ignore empty cells and text like headers. It will not write over text, and does not execute (gives me an error about overwriting values).

I've tried writing an =arrayformula but does not like calculating the min value. It does do the calculations for the rows.

=ArrayFormula(IF(ISBLANK({E8:E;F8:8;G8:8}), "", added my formula here))

Down below was something I've worked on for hours, I believe the problem is selecting the ranges inside the MIN function that is causing the problems

=arrayformula(IF(LEN(E8:G)<>0, MIN( IF(E8:E > 0, E8:E*$E$6), IF(F8:F > 0, F8:F*$F$6), IF(G8:G > 0, G124) ),)

If there's a way to do this, I'd really appreciate some help

LINK: a viewable version of a sample I made as my actual sheet is over 500 lines long.
https://docs.google.com/spreadsheets/d/133LJHY3s45ZyxWq0PWew1KikbyNE4MTt-wOeWHBrZY0/edit?usp=sharing

Body:
In cell O3 give this a try

=ArrayFormula(TO_DOLLARS(index(transpose(query(transpose(E3:G18*{M5, N5, 1}),"select "&join("),","max(Col"&row(indirect("A3:A18"))-2)&")")),,2)))

and see if that delivers the expected output?

In case, you'll have more then one value in the columns E:G you could try

=ArrayFormula(TO_DOLLARS(index(transpose(query(transpose(if(ISNUMBER(E3:G18), E3:G18, 99^99)*{M5, N5, 1}),"select "&join("),","min(Col"&row(indirect("A3:A18"))-2)&")")),,2)))


问:
Using a ArrayAdapter won't work with fragment
I am trying to get an ArrayList from an activity and then display it inside a fragment  in a custom adapter. The problem it's that I cannot setAdapter to do so. The error it says the context it's wrong, when I created the Adapter.

Creare_istoricAdapter class:

```<code>public class Creare_istoricAdapter extends ArrayAdapter<Creare_istoric> {
    private static final String TAG = "Creareistoric_adapter";
    private Context mContext;
    int mResource;

    public Creare_istoricAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Creare_istoric> objects) {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        String id_alerta = getItem(position).getId_alerta();
        String tip_problema = getItem(position).getTip_problema();
        String data_ora= getItem(position).getData_ora();
        String stare_problema = getItem(position).getStare_problema();
        String descriere = getItem(position).getDescriere();
        Creare_istoric istoric = new Creare_istoric(id_alerta, tip_problema, data_ora, stare_problema, descriere);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);
        TextView text_tip_alerta_istoric = convertView.findViewById(R.id.text_tip_alerta_istoric);
        TextView text_ora_alerta_istoric = convertView.findViewById(R.id.text_ora_alerta_istoric);
        TextView text_stare_alerta_istoric = convertView.findViewById(R.id.text_stare_alerta_istoric);
        text_tip_alerta_istoric.setText(tip_problema);
        text_ora_alerta_istoric.setText(data_ora);
        text_stare_alerta_istoric.setText(stare_problema);
        return convertView;
    }
}
</code>```

The fragment class:

```<code>public class Fragment_alerte_trimise extends Fragment {
    public Fragment_alerte_trimise(){}
    ListView list_view_alerte_trimise;
    ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
        Bundle bundle_trimise;
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        Creare_istoricAdapter adapter = new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise);
        list_view_alerte_trimise.setAdapter(adapter);
    }

}
</code>```

The problems it's in new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise) , about the context, and is also greyed out, saying it's redundant.

EDIT:

I have changed the code following the answers below, but now when I open the activity that uses the fragment, it does not show the list at all. It's only an blank screen.

The fragment code:

```<code>public class Fragment_alerte_trimise extends Fragment {
   public Fragment_alerte_trimise(){}
   private ListView list_view_alerte_trimise;
   ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

   @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
}

   @Override
     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle_trimise = getArguments();
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        list_view_alerte_trimise.setAdapter(new Creare_istoricAdapter(getContext(), R.layout.istoric_alerte_adapter, alerteTrimise));
}
</code>```

}

The way I created the Parceable:

```<code>Bundle bundle_trimise = new Bundle();
bundle_trimise.putParcelableArrayList("alerte_trimise", alerteTrimise);
Fragment_alerte_trimise fg = new Fragment_alerte_trimise();
fg.setArguments(bundle_trimise);
</code>```

I have the ListView created in the layout that's inflated by the onCreateView, but when I use getView().findViewById it says that it may produce 'NullPointerException', and so does the getContext(), which says it might be null

答:
You have to use activity context instead of fragment context this. Instead of using getContext() or getActivity() you should initialize the context on onAttach to avoid NullPointerException. Check below:

```<code>private Context activityContext;

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    activityContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    activityContext = null;
}
</code>```

Beside this, you have to return the view inside onCreateView at the very end. Check below:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    ....

    // use alerte_trimise instead of getView()
    list_view_alerte_trimise = alerte_trimise.findViewById(R.id.list_view_alerte_trimise);

    //use activityContext instead of this
    Creare_istoricAdapter adapter = new Creare_istoricAdapter(activityContext, R.layout.istoric_alerte_adapter, alerteTrimise);

    ....

    return alerte_trimise;
}
</code>```

In your code, you try to use Bundle after call return. That's why rest of your code is unreachable.

Body:
I am trying to get an ArrayList from an activity and then display it inside a fragment  in a custom adapter. The problem it's that I cannot setAdapter to do so. The error it says the context it's wrong, when I created the Adapter.

Creare_istoricAdapter class:

public class Creare_istoricAdapter extends ArrayAdapter<Creare_istoric> {
    private static final String TAG = "Creareistoric_adapter";
    private Context mContext;
    int mResource;

    public Creare_istoricAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Creare_istoric> objects) {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        String id_alerta = getItem(position).getId_alerta();
        String tip_problema = getItem(position).getTip_problema();
        String data_ora= getItem(position).getData_ora();
        String stare_problema = getItem(position).getStare_problema();
        String descriere = getItem(position).getDescriere();
        Creare_istoric istoric = new Creare_istoric(id_alerta, tip_problema, data_ora, stare_problema, descriere);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);
        TextView text_tip_alerta_istoric = convertView.findViewById(R.id.text_tip_alerta_istoric);
        TextView text_ora_alerta_istoric = convertView.findViewById(R.id.text_ora_alerta_istoric);
        TextView text_stare_alerta_istoric = convertView.findViewById(R.id.text_stare_alerta_istoric);
        text_tip_alerta_istoric.setText(tip_problema);
        text_ora_alerta_istoric.setText(data_ora);
        text_stare_alerta_istoric.setText(stare_problema);
        return convertView;
    }
}

The fragment class:

public class Fragment_alerte_trimise extends Fragment {
    public Fragment_alerte_trimise(){}
    ListView list_view_alerte_trimise;
    ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
        Bundle bundle_trimise;
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        Creare_istoricAdapter adapter = new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise);
        list_view_alerte_trimise.setAdapter(adapter);
    }

}

The problems it's in new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise) , about the context, and is also greyed out, saying it's redundant.

EDIT:

I have changed the code following the answers below, but now when I open the activity that uses the fragment, it does not show the list at all. It's only an blank screen.

The fragment code:

public class Fragment_alerte_trimise extends Fragment {
   public Fragment_alerte_trimise(){}
   private ListView list_view_alerte_trimise;
   ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

   @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
}

   @Override
     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle_trimise = getArguments();
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        list_view_alerte_trimise.setAdapter(new Creare_istoricAdapter(getContext(), R.layout.istoric_alerte_adapter, alerteTrimise));
}

}

The way I created the Parceable:

Bundle bundle_trimise = new Bundle();
bundle_trimise.putParcelableArrayList("alerte_trimise", alerteTrimise);
Fragment_alerte_trimise fg = new Fragment_alerte_trimise();
fg.setArguments(bundle_trimise);

I have the ListView created in the layout that's inflated by the onCreateView, but when I use getView().findViewById it says that it may produce 'NullPointerException', and so does the getContext(), which says it might be null

Body:
You have to use activity context instead of fragment context this. Instead of using getContext() or getActivity() you should initialize the context on onAttach to avoid NullPointerException. Check below:

private Context activityContext;

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    activityContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    activityContext = null;
}

Beside this, you have to return the view inside onCreateView at the very end. Check below:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    ....

    // use alerte_trimise instead of getView()
    list_view_alerte_trimise = alerte_trimise.findViewById(R.id.list_view_alerte_trimise);

    //use activityContext instead of this
    Creare_istoricAdapter adapter = new Creare_istoricAdapter(activityContext, R.layout.istoric_alerte_adapter, alerteTrimise);

    ....

    return alerte_trimise;
}

In your code, you try to use Bundle after call return. That's why rest of your code is unreachable.


问:
Mongodb querie get peaks of timeseries
I have a mongodb with some sensor data in it. Each time the sensor is triggered the value increases by 1. Sometimes the sensor is being reset. Now I want to sum up the value of the sensor data to get the total value of a timeseries.

My data looks like this:

```<code>{
    value: 10
    timestamp: 1577836800
}, {
    value: 12
    timestamp: 1577836810
}, {
    value: 17 <== PEAK
    timestamp: 1577836820
}, {
    value: 2
    timestamp: 1577836830
}, {
    value: 7
    timestamp: 1577836840
}, {
    value: 10 <== PEAK
    timestamp: 1577836850
},{
    value: 1
    timestamp: 1577836860
}
</code>```

My goal is to get all the values of the peaks (17 + 10), within a min and max timestamp, and sum them up (This could also be done manually afterwards). That would mean I have to sort them by timestamp and compare a value with the previous one to check which one is higher. I am new to mongo and don't know where to start. Any help is welcome!

答:
I have mentioned in the comment regarding the usage of an edge device which makes it possible to assign the value to the proper period. Use the nodeJS service to figure out and which document it has to update because it make querying the collection much easier and faster.

You could use this format per document:

```<code>{
    "period" : {
        "start" : 1577836800,
        "end" : 1577836820
    },
    "values": [
        {
            "value": 10
            "timestamp": 1577836800
        },
        {
            "value": 12
            "timestamp": 1577836810
        },
        {
            "value": 17
            "timestamp": 1577836820
        }
    ]
}
</code>```

As an example when the sensor provides the service with a new value. In this case the value 2, get the last document and compare this with the last value within values.

if the new value is less then the previous value, create a new document with the following information and of course don't forget to update the previous document with filling out the "periode.end" with the last value's timestamp.

```<code>{
    "period" : {
        "start" : 1577836830,
        "end" : null
    },
    "values": [
        {
            "value": 2
            "timestamp": 1577836830
        }
    ]
}
</code>```

UPDATE

I wrote this JavaScript script to migrate from one collection, process the data into a new format based on the requirements and insert those into the new collection.

```<code>function createSensorObject(start, value){
    var doc = new Object();

    doc.period = new Object();
    doc.period["start"] = start;
    doc.period["end"] = null;

    doc.values = new Array();

    var valueObject = new Object();
    valueObject["value"] = value;
    valueObject["timestamp"] = start;

    doc.values.push(valueObject);
    return doc;
}

function pushNewValueIntoSensorObject(doc, value, timestamp){
    doc["period"]["end"] = timestamp;

    var valueObject = new Object();
    valueObject["value"] = value;
    valueObject["timestamp"] = timestamp;

    doc["values"].push(valueObject);
}

function closePeriodInSensorObject(doc) {
    doc["period"]["end"] = doc["period"]["start"];
}

// New collection cursor to insert new values.
var sensorNewCursor = db.sensor_new;

// Using the aggregate pipeline to sort and using toArray to iterate through.
var sensorDocuments = db.sensor.aggregate([ { $sort: { "timestamp" : 1}}]).toArray();

// Temp array to store the new sensor objects.
var sensorObjectArray = new Array();

for(var i = 0; i < sensorDocuments.length; i++) {
    // Working with the current document.
    var currentDocument = sensorDocuments[i];
    var value = currentDocument["value"];
    var timestamp = currentDocument["timestamp"];

    // Initially creating a new document.
    if(i === 0) {
        var sensorObject = createSensorObject(timestamp, value);

        // If there is only one document then we need to close the document.
        if(i === (sensorDocuments.Length - 1)) {
            closePeriodInSensorObject(sensorObject);
        }

        // Push into temp array.
        sensorObjectArray.push(sensorObject);
    }
    else{
        // Get the previous value.
        var previousValue = sensorDocuments[i - 1]["value"];

        // Get the latest sensor object from the temp array.
        var sensorObject = sensorObjectArray[sensorObjectArray.length - 1];

        // When the new value is larger or equal to the previous value.
        if(value >= previousValue) {
            // Push the new value into the latest sensor object.
            pushNewValueIntoSensorObject(sensorObject, value, timestamp);
        }
        else {
            // Create new sensor object.
            var sensorObject = createSensorObject(timestamp, value);
            sensorObjectArray.push(sensorObject);
        }
    }
}

print(`Inserting ${sensorObjectArray.length} objects into the db.sensor_new collection.`);

// Insert the whole array into the new collection
sensorNewCursor.insert(sensorObjectArray);
</code>```

You can use the load function to call this js file from the mongoshell.
https://docs.mongodb.com/manual/reference/method/load/

Take a look at the two screenshots.

Finally! The query

You must use the aggregation pipeline to get the sum of the max value per periode.

First we need to unwind the values then $group with the $max to find our max value and then group again but without an $_id field to $sum the values.

```<code>db.collection.aggregate([
    {
        $unwind: "$values"
    },
    {
        $group: {
            "_id": "$_id",
            "value": {
                $max: "$values.value"
            }
        }
    },
    {
        $group: {
            "_id": null,
            "total": {
                $sum: "$value"
            }
        }
    }
])
</code>```

The result of this query would be 28

```<code>[
    {
        "_id": null,
        "total": 28
    }
]
</code>```

MongoPlayground according to the new document structure:
https://mongoplayground.net/p/WblN5QzPoeB

I really hope that this is working on your end, if it doesn't please comment. :)

Title: Mongodb querie get peaks of timeseries

Body:
I have a mongodb with some sensor data in it. Each time the sensor is triggered the value increases by 1. Sometimes the sensor is being reset. Now I want to sum up the value of the sensor data to get the total value of a timeseries.

My data looks like this:

{
    value: 10
    timestamp: 1577836800
}, {
    value: 12
    timestamp: 1577836810
}, {
    value: 17 <== PEAK
    timestamp: 1577836820
}, {
    value: 2
    timestamp: 1577836830
}, {
    value: 7
    timestamp: 1577836840
}, {
    value: 10 <== PEAK
    timestamp: 1577836850
},{
    value: 1
    timestamp: 1577836860
}

My goal is to get all the values of the peaks (17 + 10), within a min and max timestamp, and sum them up (This could also be done manually afterwards). That would mean I have to sort them by timestamp and compare a value with the previous one to check which one is higher. I am new to mongo and don't know where to start. Any help is welcome!

Body:
I have mentioned in the comment regarding the usage of an edge device which makes it possible to assign the value to the proper period. Use the nodeJS service to figure out and which document it has to update because it make querying the collection much easier and faster.

You could use this format per document:

{
    "period" : {
        "start" : 1577836800,
        "end" : 1577836820
    },
    "values": [
        {
            "value": 10
            "timestamp": 1577836800
        },
        {
            "value": 12
            "timestamp": 1577836810
        },
        {
            "value": 17
            "timestamp": 1577836820
        }
    ]
}

As an example when the sensor provides the service with a new value. In this case the value 2, get the last document and compare this with the last value within values.

if the new value is less then the previous value, create a new document with the following information and of course don't forget to update the previous document with filling out the "periode.end" with the last value's timestamp.

{
    "period" : {
        "start" : 1577836830,
        "end" : null
    },
    "values": [
        {
            "value": 2
            "timestamp": 1577836830
        }
    ]
}

UPDATE

I wrote this JavaScript script to migrate from one collection, process the data into a new format based on the requirements and insert those into the new collection.

function createSensorObject(start, value){
    var doc = new Object();

    doc.period = new Object();
    doc.period["start"] = start;
    doc.period["end"] = null;

    doc.values = new Array();

    var valueObject = new Object();
    valueObject["value"] = value;
    valueObject["timestamp"] = start;

    doc.values.push(valueObject);
    return doc;
}

function pushNewValueIntoSensorObject(doc, value, timestamp){
    doc["period"]["end"] = timestamp;

    var valueObject = new Object();
    valueObject["value"] = value;
    valueObject["timestamp"] = timestamp;

    doc["values"].push(valueObject);
}

function closePeriodInSensorObject(doc) {
    doc["period"]["end"] = doc["period"]["start"];
}

// New collection cursor to insert new values.
var sensorNewCursor = db.sensor_new;

// Using the aggregate pipeline to sort and using toArray to iterate through.
var sensorDocuments = db.sensor.aggregate([ { $sort: { "timestamp" : 1}}]).toArray();

// Temp array to store the new sensor objects.
var sensorObjectArray = new Array();

for(var i = 0; i < sensorDocuments.length; i++) {
    // Working with the current document.
    var currentDocument = sensorDocuments[i];
    var value = currentDocument["value"];
    var timestamp = currentDocument["timestamp"];

    // Initially creating a new document.
    if(i === 0) {
        var sensorObject = createSensorObject(timestamp, value);

        // If there is only one document then we need to close the document.
        if(i === (sensorDocuments.Length - 1)) {
            closePeriodInSensorObject(sensorObject);
        }

        // Push into temp array.
        sensorObjectArray.push(sensorObject);
    }
    else{
        // Get the previous value.
        var previousValue = sensorDocuments[i - 1]["value"];

        // Get the latest sensor object from the temp array.
        var sensorObject = sensorObjectArray[sensorObjectArray.length - 1];

        // When the new value is larger or equal to the previous value.
        if(value >= previousValue) {
            // Push the new value into the latest sensor object.
            pushNewValueIntoSensorObject(sensorObject, value, timestamp);
        }
        else {
            // Create new sensor object.
            var sensorObject = createSensorObject(timestamp, value);
            sensorObjectArray.push(sensorObject);
        }
    }
}

print(`Inserting ${sensorObjectArray.length} objects into the db.sensor_new collection.`);

// Insert the whole array into the new collection
sensorNewCursor.insert(sensorObjectArray);

You can use the load function to call this js file from the mongoshell.
https://docs.mongodb.com/manual/reference/method/load/

Take a look at the two screenshots.

Finally! The query

You must use the aggregation pipeline to get the sum of the max value per periode.

First we need to unwind the values then $group with the $max to find our max value and then group again but without an $_id field to $sum the values.

db.collection.aggregate([
    {
        $unwind: "$values"
    },
    {
        $group: {
            "_id": "$_id",
            "value": {
                $max: "$values.value"
            }
        }
    },
    {
        $group: {
            "_id": null,
            "total": {
                $sum: "$value"
            }
        }
    }
])

The result of this query would be 28

[
    {
        "_id": null,
        "total": 28
    }
]

MongoPlayground according to the new document structure:
https://mongoplayground.net/p/WblN5QzPoeB

I really hope that this is working on your end, if it doesn't please comment. :)


问:
GatsbyJs - make ImageSharp from multiple images referenced in csv
Using gatsby-transformer-csv and gatsby-transformer-sharp

given a CSV file with one cell that has multiple images (with a local path) referenced, how can I get them to be processed by imageSharp?

```<code>id,slug,images
615,prime-click-solid-2,./images/products/PC-019-S1.png, ./images/products/PC-019-S-1.png

</code>```

答:
For this to work, I think you'd have to do a lot of manual work here.

First, since values are separated by comma, you should group the images together:

```<code>id,slug,images
                         v                        v
615,prime-click-solid-2, "./img-1.png, ./img-2.png"
</code>```

Then you can use createSchemaCustomization hook in gatsby-node to...

intercept the images field

extracts the paths from the original value, ./img-1.png, ./img-2.png

create a correct absolute path for each of your image

query those images in Gatsby's database

return the images

I have a bit of downtime, so I ended up creating a small example.

Directory structure:

```<code><root>
  |--content
  |     |
  |     |--images
  |     |     |--img-1.png
  |     |     `--img-2.png
  |     |
  |     `--data.csv
  |
  `--gatsby-node.js

</code>```

data.csv content

```<code>id,images
hello,"./images/287.jpg, ./images/288.jpg"
</code>```

Custom gatsby hook

// gatsby-node.js

const path = require('path')

exports.createSchemaCustomization = ({ actions, schema }) => {
  const { createTypes } = actions

  const types = schema.buildObjectType({
    name: 'DataCsv', // Gatsby create name based on your csv file name. Yours will be different — you can find your CSV type name in localhost:8000/___graphql
    interfaces: ['Node'],
    extensions: {
      infer: true,
    },
    fields: {
      images: {
        type: '[File]', // important. We're saying DataCsv.images will return an array of File, instead of a string as inferred by default.
        resolve: async (src, args, context, info) => {
          const { fieldName } = info
          const paths = src[fieldName]
          const imagePaths = paths.split(',').map(str => str.trim())

          const absolutePaths = imagePaths.map(imagePath => {
            return path.join(__dirname, 'content', imagePath)
          })

          const fileNodes = await context.nodeModel.runQuery({
            type: 'File',
            query: {
              filter: {
                absolutePath: {
                  in: absolutePaths
                }
              }
            }
          })

          return fileNodes
        }
      }
    }
  })

  createTypes(types)
}
```
<p>Then, you can query the images:</p>
```  query Images {
    dataCsv {
      images {
        childImageSharp {
          original {
            src
          }
        }
      }
    }
  }
```

You can see the example & adapt as needed here:
https://github.com/d4rekanguok/gatsby-csv-multi-images-example

Resources

You can learn more about this hook in the official docs, but it's a bit dry.

I've also written a tutorial on the topic here.

Hope it's helpful!

Edit Gatsby has since made runQuery asynchronous (Jul 2020), the answer has been updated to reflect this.

Body:
Using gatsby-transformer-csv and gatsby-transformer-sharp

given a CSV file with one cell that has multiple images (with a local path) referenced, how can I get them to be processed by imageSharp?

id,slug,images
615,prime-click-solid-2,./images/products/PC-019-S1.png, ./images/products/PC-019-S-1.png

Body:
For this to work, I think you'd have to do a lot of manual work here.

First, since values are separated by comma, you should group the images together:

id,slug,images
                         v                        v
615,prime-click-solid-2, "./img-1.png, ./img-2.png"

Then you can use createSchemaCustomization hook in gatsby-node to...

intercept the images field

extracts the paths from the original value, ./img-1.png, ./img-2.png

create a correct absolute path for each of your image

query those images in Gatsby's database

return the images

I have a bit of downtime, so I ended up creating a small example.

Directory structure:

<root>
  |--content
  |     |
  |     |--images
  |     |     |--img-1.png
  |     |     `--img-2.png
  |     |
  |     `--data.csv
  |
  `--gatsby-node.js

data.csv content

id,images
hello,"./images/287.jpg, ./images/288.jpg"

Custom gatsby hook

// gatsby-node.js

const path = require('path')

exports.createSchemaCustomization = ({ actions, schema }) => {
  const { createTypes } = actions

  const types = schema.buildObjectType({
    name: 'DataCsv', // Gatsby create name based on your csv file name. Yours will be different — you can find your CSV type name in localhost:8000/___graphql
    interfaces: ['Node'],
    extensions: {
      infer: true,
    },
    fields: {
      images: {
        type: '[File]', // important. We're saying DataCsv.images will return an array of File, instead of a string as inferred by default.
        resolve: async (src, args, context, info) => {
          const { fieldName } = info
          const paths = src[fieldName]
          const imagePaths = paths.split(',').map(str => str.trim())

          const absolutePaths = imagePaths.map(imagePath => {
            return path.join(__dirname, 'content', imagePath)
          })

          const fileNodes = await context.nodeModel.runQuery({
            type: 'File',
            query: {
              filter: {
                absolutePath: {
                  in: absolutePaths
                }
              }
            }
          })

          return fileNodes
        }
      }
    }
  })

  createTypes(types)
}

Then, you can query the images:

  query Images {
    dataCsv {
      images {
        childImageSharp {
          original {
            src
          }
        }
      }
    }
  }

You can see the example & adapt as needed here:
https://github.com/d4rekanguok/gatsby-csv-multi-images-example

Resources

You can learn more about this hook in the official docs, but it's a bit dry.

I've also written a tutorial on the topic here.

Hope it's helpful!

Edit Gatsby has since made runQuery asynchronous (Jul 2020), the answer has been updated to reflect this.


问:
Get names of the params passed to a C# method
```<code>void MyMethod(string something, params object[] parameters)
    {
      foreach (object parameter in parameters)
      {
        // Get the name of each passed parameter
      }
    }
</code>```

For example, if I call the method in the following way, I want to get the names "myFirstParam" and "anotherParam".

```<code>string myFirstParam = "some kind of text";
string anotherParam = 42;
MyMethod("test", myFirstParam, anotherParam);
</code>```

Perhaps reflection is the answer? Perhaps it's just not possible? I am aware of the existance of this question, but that solution won't work here.

(Please do not respond with "This is not a good idea". That is not my question.)

答: In addition to SLaks's answer - variable names are not available at run-time at all. The variables are represented by stack slots and are addressed by an index. Thus you can't get this information even for the example you provided, not to mention all these examples SLaks provided. Reflection is no help here. Nothing is.</p>

Body:
void MyMethod(string something, params object[] parameters)
    {
      foreach (object parameter in parameters)
      {
        // Get the name of each passed parameter
      }
    }

For example, if I call the method in the following way, I want to get the names "myFirstParam" and "anotherParam".

string myFirstParam = "some kind of text";
string anotherParam = 42;
MyMethod("test", myFirstParam, anotherParam);

Perhaps reflection is the answer? Perhaps it's just not possible? I am aware of the existance of this question, but that solution won't work here.

(Please do not respond with "This is not a good idea". That is not my question.)