问:
React Hook select multiple items with icons
I am trying to implement a popover with many items where a user can multi select them. When a user clicks a item, a font-awesome icon is shown to the right.

A user is able to select multiple items and an icon is shown on the right to show it has been checked. This icon toggles when clicking. My problem is my event handler is tied to all the items and whenever I click one, all gets checked.

I am new to hook and react.  I am also trying to assign the Id of the selected item in an array. It won't append.

```<code>const SettingsComponent = (props) => {
const urlStofTyper = stofTyperUrl;
const stofTyper = [];
const [isPopoverOpen, setPopoverOpen] = useState(false);

const [isItemChecked, setItemChecked] = useState(false);

const [error, setError] = useState(null);
const [loading, setLoading] = useState(null);
const [stoftype, setStoftyper] = useState({ DataList: [] });

const toggle = () => setPopoverOpen(!isPopoverOpen);

const sectionClicked = (e) => {
setItemChecked(!isItemChecked);
let secId = e.target.parentNode.getAttribute("data-section");
if (!isItemChecked) {
    stofTyper.push(secId);
   } else {
    stofTyper.filter((sec) => sec == secId);
  }
};

useEffect(() => {
fetchStoftyper({ setError, setLoading, setStoftyper });
}, []);

const fetchStoftyper = async ({ setError, setLoading, setStoftyper }) => {
try {
    setLoading(true);
    const response = await Axios(urlStofTyper);
    const allStofs = response.data;
    setLoading(false);
    setStoftyper(allStofs);
  } catch (error) {
    setLoading(false);
    setError(error);
  }
};

return (
<React.Fragment>
  <div className='list-header-icons__fontawesome-icon' id='PopoverClick'>
    <FontAwesomeIcon icon={faCog} />
  </div>
  <Popover
    isOpen={isPopoverOpen}
    placement='bottom'
    toggle={toggle}
    target='PopoverClick'>
    <PopoverHeader>formatter</PopoverHeader>
    <div className='popover-body'>
      <ul className='individual-col--my-dropdown-menu-settings'>
        {stoftype.DataList.map((item) => (
          <li key={item.Id} className='section-items'>
            <a
              onClick={sectionClicked}
              className='dropdown-item'

              data-section={item.Sections[0].SectionId}
              data-format={
                item.Formats.length > 0
                  ? item.Formats[0].FormatId
                  : ""
              }
              aria-selected='false'>
              <span className='formatter-name'>
                {item.Name}
              </span>
              {isItemChecked && (
                <span className='formatter-check-icon'>
                  <FontAwesomeIcon icon={faCheck} size='lg' />
                </span>
              )}
            </a>
          </li>
        ))}
      </ul>
    </div>
  </Popover>
</React.Fragment>
);
</code>```

答:
Finally, I have a solution for my own question. Even though, I did not need above solution but I though it would be a good practice to try solve it. Popover is not relevant as that was used only as a wrapper. The below solution can still be placed in a Popover.

CodeSandBox link: Demo here using Class component, I will try to re-write this using hooks as soon as possible.

This solution dependency is Bootstrap 4 and Fontawesome.

```<code>import React, { Component } from "react";
import Cars from "./DataSeed";

class DropDownWithSelect extends Component {
  constructor(props) {
    super(props);

    this.toggleDropdown = this.toggleDropdown.bind(this);

    this.state = {
      isDropDownOpen: false,
      idsOfItemClicked: []
    };
  }

  toggleDropdown = evt => {
    this.setState({
      isDropDownOpen: !this.state.isDropDownOpen
    });
  };

  toggleItemClicked = id => {
    this.setState(state => {
      const idsOfItemClicked = state.idsOfItemClicked.includes(id)
        ? state.idsOfItemClicked.filter(x => x !== id)
        : [...state.idsOfItemClicked, id];

      return {
        idsOfItemClicked
      };
    });
  };

  render() {
    return (
      <div className="dropdown">
        <button
          onClick={this.toggleDropdown}
          className="btn btn-secondary dropdown-toggle"
          type="button"
          id="dropdownMenuButton"
          data-toggle="dropdown"
          aria-haspopup="true"
          aria-expanded="false"
        >
          Dropdown button
        </button>
        {this.state.isDropDownOpen && (
          <div
            className="dropdown-menu show"
            aria-labelledby="dropdownMenuButton"
          >
            {Cars.map(x => {
              return (
                <div
                  key={x.id}
                  onClick={() => this.toggleItemClicked(x.id)}
                  className="dropdown-item d-inline-flex justify-content-between"
                >
                  <span className="d-flex"> {x.name} </span>
                  <span className="d-flex align-self-center">
                    {this.state.idsOfItemClicked.includes(x.id) && (
                      <i className="fa fa-times" aria-hidden="true" />
                    )}
                  </span>
                </div>
              );
            })}
          </div>
        )}
      </div>
    );
  }
}
export default DropDownWithSelect;
</code>```

Data i.e., ./DataSeed

```<code>    const cars = [
  {
    id: 1,
    name: "BMW",
    cost: 450000
  },
  {
    id: 2,
    name: "Audi",
    cost: 430000
  },
  {
    id: 3,
    name: "Mercedes",
    cost: 430000
  }
];

export default cars;
</code>```

Body:
I am trying to implement a popover with many items where a user can multi select them. When a user clicks a item, a font-awesome icon is shown to the right.

A user is able to select multiple items and an icon is shown on the right to show it has been checked. This icon toggles when clicking. My problem is my event handler is tied to all the items and whenever I click one, all gets checked.

I am new to hook and react.  I am also trying to assign the Id of the selected item in an array. It won't append.

const SettingsComponent = (props) => {
const urlStofTyper = stofTyperUrl;
const stofTyper = [];
const [isPopoverOpen, setPopoverOpen] = useState(false);

const [isItemChecked, setItemChecked] = useState(false);

const [error, setError] = useState(null);
const [loading, setLoading] = useState(null);
const [stoftype, setStoftyper] = useState({ DataList: [] });

const toggle = () => setPopoverOpen(!isPopoverOpen);

const sectionClicked = (e) => {
setItemChecked(!isItemChecked);
let secId = e.target.parentNode.getAttribute("data-section");
if (!isItemChecked) {
    stofTyper.push(secId);
   } else {
    stofTyper.filter((sec) => sec == secId);
  }
};

useEffect(() => {
fetchStoftyper({ setError, setLoading, setStoftyper });
}, []);

const fetchStoftyper = async ({ setError, setLoading, setStoftyper }) => {
try {
    setLoading(true);
    const response = await Axios(urlStofTyper);
    const allStofs = response.data;
    setLoading(false);
    setStoftyper(allStofs);
  } catch (error) {
    setLoading(false);
    setError(error);
  }
};

return (
<React.Fragment>

    <FontAwesomeIcon icon={faCog} />

  <Popover
    isOpen={isPopoverOpen}
    placement='bottom'
    toggle={toggle}
    target='PopoverClick'>
    <PopoverHeader>formatter</PopoverHeader>

        {stoftype.DataList.map((item) => (

             0
                  ? item.Formats[0].FormatId
                  : ""
              }
              aria-selected='false'>

                {item.Name}

              {isItemChecked && (

                  <FontAwesomeIcon icon={faCheck} size='lg' />

              )}

        ))}

  </Popover>
</React.Fragment>
);

Body:
Finally, I have a solution for my own question. Even though, I did not need above solution but I though it would be a good practice to try solve it. Popover is not relevant as that was used only as a wrapper. The below solution can still be placed in a Popover.

CodeSandBox link: Demo here using Class component, I will try to re-write this using hooks as soon as possible.

This solution dependency is Bootstrap 4 and Fontawesome.

import React, { Component } from "react";
import Cars from "./DataSeed";

class DropDownWithSelect extends Component {
  constructor(props) {
    super(props);

    this.toggleDropdown = this.toggleDropdown.bind(this);

    this.state = {
      isDropDownOpen: false,
      idsOfItemClicked: []
    };
  }

  toggleDropdown = evt => {
    this.setState({
      isDropDownOpen: !this.state.isDropDownOpen
    });
  };

  toggleItemClicked = id => {
    this.setState(state => {
      const idsOfItemClicked = state.idsOfItemClicked.includes(id)
        ? state.idsOfItemClicked.filter(x => x !== id)
        : [...state.idsOfItemClicked, id];

      return {
        idsOfItemClicked
      };
    });
  };

  render() {
    return (
      <div className="dropdown">
        <button
          onClick={this.toggleDropdown}
          className="btn btn-secondary dropdown-toggle"
          type="button"
          id="dropdownMenuButton"
          data-toggle="dropdown"
          aria-haspopup="true"
          aria-expanded="false"
        >
          Dropdown button
        </button>
        {this.state.isDropDownOpen && (
          <div
            className="dropdown-menu show"
            aria-labelledby="dropdownMenuButton"
          >
            {Cars.map(x => {
              return (
                <div
                  key={x.id}
                  onClick={() => this.toggleItemClicked(x.id)}
                  className="dropdown-item d-inline-flex justify-content-between"
                >
                  <span className="d-flex"> {x.name} </span>
                  <span className="d-flex align-self-center">
                    {this.state.idsOfItemClicked.includes(x.id) && (
                      <i className="fa fa-times" aria-hidden="true" />
                    )}
                  </span>
                </div>
              );
            })}
          </div>
        )}
      </div>
    );
  }
}
export default DropDownWithSelect;

Data i.e., ./DataSeed

    const cars = [
  {
    id: 1,
    name: "BMW",
    cost: 450000
  },
  {
    id: 2,
    name: "Audi",
    cost: 430000
  },
  {
    id: 3,
    name: "Mercedes",
    cost: 430000
  }
];

export default cars;


来源: stackexchange

问:
Is There an adb/shell command to list the items on the android's notification bar?
Can someone tell me if there is a way to get the complete list of items currently being displayed in the notification bar?  I'm trying to write an interface that will trigger notifications to my PC based on the particular app giving the notification.

My only hits for something similar using the adb cli tool is Receiving push notifications using adb shell command which appears to be trying to get the notification from a particular app.

Other references that I am finding are related to actual android programming and sending your own notifications to the bar.

For the sake of formatting, I'm repeating my comment to fRoStBiT who provided the resource in his answer.  The following cli provides the specific item:

```<code>$ adb shell dumpsys notification | egrep NotificationRecord | awk -F\| '{print $2}'
</code>```

答:
On Android >= 6 for get notification extras use this command

adb shell dumpsys notification --noredact
```

<p>the full notifications text you can see at the <code>extras</code> section:</p>

```
      extras={
          android.title=String (Bring The Rain)
          android.reduced.images=Boolean (true)
          android.subText=null
          android.template=String (android.app.Notification$MediaStyle)
          toSingleLine=Boolean (false)
          android.text=String (Upon A Burning Body)
          android.appInfo=ApplicationInfo (ApplicationInfo{c8165e6 org.telegram.messenger})
          android.showWhen=Boolean (false)
          android.largeIcon=Icon (Icon(typ=BITMAP size=100x100))
          android.mediaSession=Token (android.media.session.MediaSession$Token@608a746)
          gameDndOn=Boolean (false)
          android.compactActions=int[] (3)
            [0] 0
            [1] 1
            [2] 2
      }
```

ContentLicense: CC BY-SA 3.0

Body:
Can someone tell me if there is a way to get the complete list of items currently being displayed in the notification bar?  I'm trying to write an interface that will trigger notifications to my PC based on the particular app giving the notification.

My only hits for something similar using the adb cli tool is Receiving push notifications using adb shell command which appears to be trying to get the notification from a particular app.

Other references that I am finding are related to actual android programming and sending your own notifications to the bar.

For the sake of formatting, I'm repeating my comment to fRoStBiT who provided the resource in his answer.  The following cli provides the specific item:

$ adb shell dumpsys notification | egrep NotificationRecord | awk -F\| '{print $2}'

Body:
On Android >= 6 for get notification extras use this command

adb shell dumpsys notification --noredact

the full notifications text you can see at the extras section:

      extras={
          android.title=String (Bring The Rain)
          android.reduced.images=Boolean (true)
          android.subText=null
          android.template=String (android.app.Notification$MediaStyle)
          toSingleLine=Boolean (false)
          android.text=String (Upon A Burning Body)
          android.appInfo=ApplicationInfo (ApplicationInfo{c8165e6 org.telegram.messenger})
          android.showWhen=Boolean (false)
          android.largeIcon=Icon (Icon(typ=BITMAP size=100x100))
          android.mediaSession=Token (android.media.session.MediaSession$Token@608a746)
          gameDndOn=Boolean (false)
          android.compactActions=int[] (3)
            [0] 0
            [1] 1
            [2] 2
      }

ContentLicense: CC BY-SA 4.0


问:
Why are browser requests not going through my proxy server?
I tried writing a simple proxy in node.js today with a basic HTTP server, I realized in Firefox when I reload the proxy, I can see a request.  However, when I load any page, it doesn't seem to be going through my proxy.  I can curl the server, and it works fine. But why is the browser not using my proxy?

The code just looks like:

```<code>var http = require('http');

var listener = function(request, response) {
  console.log('hi');

  response.write("200");
  response.end();
};

var server = http.createServer(listener);
server.listen(8000, undefined, function() {
  console.log('Server has started on 8000');
});
</code>```

I'm just looking for something that changes the header of the request, though a reverse proxy would also be cool.

Edit: This is how I'm pointing my browser to my proxy. In Firefox, preferences -> advanced -> Network -> Settings

I tried to setting the HTTP Proxy under "Manual proxy configuration" to 127.0.0.1:8000 - that seems to do something, cuz all my pages fail to load, but I don't see any activity on my proxy server.

I also tried to just put 127.0.0.1:8000 under "Automatic proxy configuration URL" which sends a request when I just configure it, but nothing is proxied afterwards. I'm wonder what kind of response the "automatic" configuration is looking for...

答:
The code you have written isn't a proxy server? It's just an HTTPd responder, which is why your curl script 'works' but firefox doesn't

Taking an example already online, http://catonmat.net/http-proxy-in-nodejs, you will see that as well as setting up the HTTPd in node, you have the dispatch HTTP calls to the server being proxied and drain that output back into the response to your browser.

Body:
I tried writing a simple proxy in node.js today with a basic HTTP server, I realized in Firefox when I reload the proxy, I can see a request.  However, when I load any page, it doesn't seem to be going through my proxy.  I can curl the server, and it works fine. But why is the browser not using my proxy?

The code just looks like:

var http = require('http');

var listener = function(request, response) {
  console.log('hi');

  response.write("200");
  response.end();
};

var server = http.createServer(listener);
server.listen(8000, undefined, function() {
  console.log('Server has started on 8000');
});

I'm just looking for something that changes the header of the request, though a reverse proxy would also be cool.

Edit: This is how I'm pointing my browser to my proxy. In Firefox, preferences -> advanced -> Network -> Settings

I tried to setting the HTTP Proxy under "Manual proxy configuration" to 127.0.0.1:8000 - that seems to do something, cuz all my pages fail to load, but I don't see any activity on my proxy server.

I also tried to just put 127.0.0.1:8000 under "Automatic proxy configuration URL" which sends a request when I just configure it, but nothing is proxied afterwards. I'm wonder what kind of response the "automatic" configuration is looking for...


问:
Print Python output into two columns
Trying to replicate a basic column command in a Python program to print a list of States to the user via the command line:

```<code>us_states_list_with_population = [
("Alabama" , "AL" , 4903185),
("Montana" , "MT" , 1068778),
("Alaska" , "AK" , 731545),
...

]

for state_name , state_abbreviation , num_counties in us_states_list_with_population:
    print(state_name + " (" + state_abbreviation + ")")
</code>```

Is there an easy way to split the output into two or three columns to make this shorter and more readable?

Desired output would be something like:

```<code>Alabama (AL)        Alaska (AK)
Montana (MT)        California (CA)
...
</code>```

Versus:

```<code>Alabama (AL)
Alaska (AK)
Montana (MT)
California (CA)
...
</code>```

答:
You could separate them by tabs, rather than spaces.

```<code>for state_name , state_abbreviation , num_counties in us_states_list_with_population:
    print(state_name + "\t(" + state_abbreviation + ")")
</code>```

The \t there will get translated into a tab when printed.

Title: Print Python output into two columns

Body:
Trying to replicate a basic column command in a Python program to print a list of States to the user via the command line:

us_states_list_with_population = [
("Alabama" , "AL" , 4903185),
("Montana" , "MT" , 1068778),
("Alaska" , "AK" , 731545),
...

]

for state_name , state_abbreviation , num_counties in us_states_list_with_population:
    print(state_name + " (" + state_abbreviation + ")")

Is there an easy way to split the output into two or three columns to make this shorter and more readable?

Desired output would be something like:

Alabama (AL)        Alaska (AK)
Montana (MT)        California (CA)
...

Versus:

Alabama (AL)
Alaska (AK)
Montana (MT)
California (CA)
...

Body:
You could separate them by tabs, rather than spaces.

for state_name , state_abbreviation , num_counties in us_states_list_with_population:
    print(state_name + "\t(" + state_abbreviation + ")")

The \t there will get translated into a tab when printed.


问:
How to calculate exact average using arrays in Java
Regardless of what I try, the program outputs the average as the integer "4" when the average should be "4.78". I have tried changing the integers to doubles, but to no avail.

The rest of the program works as intended, though. It is supposed to print how many times each value in the text files appears by putting an asterisk next to it and it is supposed to indicate when a number is larger than the average by having a ">" appear next to it in the output.

```<code>import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {

    public static void main(String args[]) throws IOException {

        int i = 0, count = 0, sum = 0;

        Scanner file = new Scanner(new File("input3.txt"));

        int[] frequency = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        int[] arr = new int[50];

        int current_num;

        while (file.hasNext()) {

            current_num = file.nextInt();

            sum += current_num;

            arr[i++] = current_num;

            count++;

            frequency[current_num]++;

        }

        int average = sum / count;

        for(i=0; i<arr.length; i++){
            if(arr[i] > average){
                System.out.print(arr[i] + " > " );
            }
            else{
                System.out.print(arr[i] + " ");
            }

            if(i%5==4){
                System.out.println();
                }
            }

        System.out.println("\n***** Frequency Graph *****\n");
        for(i=0; i<frequency.length; i++){
        System.out.print(i + " = ");
        for(int j=0; j<frequency[i]; j++){
        System.out.print("*");
        }
        System.out.println();
        }

        System.out.println("\nAverage of the numbers in the text file is : " + average);

        }

    }
</code>```

The numbers in the "input3.txt" file are:

```<code>5
8
8
1
5
0
6
6
5
3
4
0
6
8
5
4
9
5
8
0
4
7
4
2
0
9
8
3
5
5
5
7
5
7
1
4
4
0
7
4
8
4
2
4
9
8
8
2
3
4
</code>```

Any help would be appreciated!

答:
Since your are streaming integers from a file, you could just rely on IntStream::average as well, which returns a double.

```<code>    int[] intArray = Files.lines(Paths.get("/tmp/input3"))
            .map(String::trim)
            .mapToInt(Integer::parseInt)
            .toArray();
    double average = Arrays.stream(intArray).average()
            .orElse(0d);

    for (int i = 0; i < intArray.length; i++) {
        if (intArray[i] > average) {
            System.out.print(intArray[i] + " > ");
        } else {
            System.out.print(intArray[i] + " ");
        }

        if (i % 5 == 4) {
            System.out.println();
        }
    }

    Map<Integer, Integer> occurences = Arrays.stream(intArray)
            .boxed()
            .collect(Collectors.toMap(
                    i -> i,
                    i -> 1,
                    Integer::sum
            ));

    System.out.println("\n***** Frequency Graph *****\n");
    occurences.keySet().stream()
            .sorted()
            .forEach(k -> System.out.println(k + " = " + "*".repeat(occurences.get(k))));

    System.out.println("\nAverage of the numbers in the text file is : " + average);
</code>```

Body:
Regardless of what I try, the program outputs the average as the integer "4" when the average should be "4.78". I have tried changing the integers to doubles, but to no avail.

The rest of the program works as intended, though. It is supposed to print how many times each value in the text files appears by putting an asterisk next to it and it is supposed to indicate when a number is larger than the average by having a ">" appear next to it in the output.

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {

    public static void main(String args[]) throws IOException {

        int i = 0, count = 0, sum = 0;

        Scanner file = new Scanner(new File("input3.txt"));

        int[] frequency = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        int[] arr = new int[50];

        int current_num;

        while (file.hasNext()) {

            current_num = file.nextInt();

            sum += current_num;

            arr[i++] = current_num;

            count++;

            frequency[current_num]++;

        }

        int average = sum / count;

        for(i=0; i<arr.length; i++){
            if(arr[i] > average){
                System.out.print(arr[i] + " > " );
            }
            else{
                System.out.print(arr[i] + " ");
            }

            if(i%5==4){
                System.out.println();
                }
            }

        System.out.println("\n***** Frequency Graph *****\n");
        for(i=0; i<frequency.length; i++){
        System.out.print(i + " = ");
        for(int j=0; j<frequency[i]; j++){
        System.out.print("*");
        }
        System.out.println();
        }

        System.out.println("\nAverage of the numbers in the text file is : " + average);

        }

    }

The numbers in the "input3.txt" file are:

5
8
8
1
5
0
6
6
5
3
4
0
6
8
5
4
9
5
8
0
4
7
4
2
0
9
8
3
5
5
5
7
5
7
1
4
4
0
7
4
8
4
2
4
9
8
8
2
3
4

Any help would be appreciated!

Body:
Since your are streaming integers from a file, you could just rely on IntStream::average as well, which returns a double.

    int[] intArray = Files.lines(Paths.get("/tmp/input3"))
            .map(String::trim)
            .mapToInt(Integer::parseInt)
            .toArray();
    double average = Arrays.stream(intArray).average()
            .orElse(0d);

    for (int i = 0; i < intArray.length; i++) {
        if (intArray[i] > average) {
            System.out.print(intArray[i] + " > ");
        } else {
            System.out.print(intArray[i] + " ");
        }

        if (i % 5 == 4) {
            System.out.println();
        }
    }

    Map<Integer, Integer> occurences = Arrays.stream(intArray)
            .boxed()
            .collect(Collectors.toMap(
                    i -> i,
                    i -> 1,
                    Integer::sum
            ));

    System.out.println("\n***** Frequency Graph *****\n");
    occurences.keySet().stream()
            .sorted()
            .forEach(k -> System.out.println(k + " = " + "*".repeat(occurences.get(k))));

    System.out.println("\nAverage of the numbers in the text file is : " + average);


问:
Reading Bigtable data from the middle of a Dataflow pipeline
I have a pipeline that receive some data from pub sub, do some processing, and needs to process all data on Bigtable based on the result of that processing.

For example, I have a pub sub message like: {clientId: 10}, so I need to read from Bigtable all the data for clientId 10 (I know how to create the scan based on the clientId). The problem is that both reads that we have at the moment for Bigtable (BigtableIO and CloudBigtableIO) are based on the fact that pipeline starts with bigtable, so I can not (or could not find a way) to use them on the middle of the pipeline. How can I achieve this case?

Simple pseudo-like code:

```<code>Pipeline p = Pipeline.create(...)
p.apply(PubsubIO.readMessagesWithAttributes ...)
.apply( PubsubMessageToScans()) // I know how to do this
.apply( ReadBigTable()) // How to do this?
</code>```

答:
To complement @Billy's answer, you can also try using the BigtableDataClient class inside a ParDo transformation.
The data input will be the parameters contained in a PubsubMessage to configure the Scan object, then in the ParDo set the Scan parameters, make the connection to BigTable and obtain the filtered results.

This snippet maybe be useful:

    @ProcessElement
    public void processElement(@Element String element, OutputReceiver<String> out){

        String projectId = "<PROJECT_ID>";
        String instanceId = "<INSTANCE_ID>";
        String tableName = "<TABLENAME>";

        String[] scanParameters = element.split(",");

        try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)){

            Table table = connection.getTable(TableName.valueOf(tableName));

            Scan scan = new Scan();
            scan.withStartRow(Bytes.toBytes(scanParameters[0]));
            scan.withStopRow(Bytes.toBytes(scanParameters[1]));

            ResultScanner scanner = table.getScanner(scan);

            for (Result row : scanner) {
                System.out.println(row);
            }

            catch (Exception e){
                e.printStackTrace();
            }

            out.output("");
        }
```

I didn't test it directly with a PubsubMessage but, you can do another transform to adapt the message or directly get the PubsubMessage and set the Scan object.

Body:
I have a pipeline that receive some data from pub sub, do some processing, and needs to process all data on Bigtable based on the result of that processing.

For example, I have a pub sub message like: {clientId: 10}, so I need to read from Bigtable all the data for clientId 10 (I know how to create the scan based on the clientId). The problem is that both reads that we have at the moment for Bigtable (BigtableIO and CloudBigtableIO) are based on the fact that pipeline starts with bigtable, so I can not (or could not find a way) to use them on the middle of the pipeline. How can I achieve this case?

Simple pseudo-like code:

Pipeline p = Pipeline.create(...)
p.apply(PubsubIO.readMessagesWithAttributes ...)
.apply( PubsubMessageToScans()) // I know how to do this
.apply( ReadBigTable()) // How to do this?

Body:
To complement @Billy's answer, you can also try using the BigtableDataClient class inside a ParDo transformation.
The data input will be the parameters contained in a PubsubMessage to configure the Scan object, then in the ParDo set the Scan parameters, make the connection to BigTable and obtain the filtered results.

This snippet maybe be useful:

    @ProcessElement
    public void processElement(@Element String element, OutputReceiver<String> out){

        String projectId = "<PROJECT_ID>";
        String instanceId = "<INSTANCE_ID>";
        String tableName = "<TABLENAME>";

        String[] scanParameters = element.split(",");

        try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)){

            Table table = connection.getTable(TableName.valueOf(tableName));

            Scan scan = new Scan();
            scan.withStartRow(Bytes.toBytes(scanParameters[0]));
            scan.withStopRow(Bytes.toBytes(scanParameters[1]));

            ResultScanner scanner = table.getScanner(scan);

            for (Result row : scanner) {
                System.out.println(row);
            }

            catch (Exception e){
                e.printStackTrace();
            }

            out.output("");
        }

I didn't test it directly with a PubsubMessage but, you can do another transform to adapt the message or directly get the PubsubMessage and set the Scan object.


问:
XSLT 1.0 - How to combine sub-string/concat/translate value of select
I am trying to combine a sub-string, concat and translate so I can combine the string but capitalize the output but am having trouble.  I am using the below snippet of code:

```<code><xsl:value-of select="substring(concat(translate(E_Firstname, ',', E_Lastname, ' ', E_MiddleInitial, '                       '), 1, 24), $smallcase, $uppercase)"/>
</code>```

Can anyone tell me where I am going wrong here?

I am getting an error that the wrong number of arguments were built into the translate function.

答:
Try the following XSLT expression:

```<code><xsl:value-of select="substring(translate(concat(E_Firstname, ',', E_Lastname, ' ', E_MiddleInitial, '                       '), $smallcase, $uppercase),1,24)"/>
</code>```

It should fix your problem.

In a full example with the sample XML

```<code><?xml version='1.0' encoding='UTF-8'?>
<Data>
    <E_Firstname>Homer</E_Firstname>
    <E_Lastname>Simpson</E_Lastname>
    <E_MiddleInitial>J.</E_MiddleInitial>
</Data>
</code>```

and the sample XSLT-1.0 stylesheet

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />

  <xsl:template match="/Data">
    <xsl:value-of select="substring(translate(concat(E_Firstname, ',', E_Lastname, ' ', E_MiddleInitial, '                       '), $smallcase, $uppercase),1,24)"/>
  </xsl:template>

</xsl:stylesheet>
</code>```

the result will be

```<code><?xml version="1.0"?>
HOMER,SIMPSON J.
</code>```

Body:
I am trying to combine a sub-string, concat and translate so I can combine the string but capitalize the output but am having trouble.  I am using the below snippet of code:

<xsl:value-of select="substring(concat(translate(E_Firstname, ',', E_Lastname, ' ', E_MiddleInitial, '                       '), 1, 24), $smallcase, $uppercase)"/>

Can anyone tell me where I am going wrong here?

I am getting an error that the wrong number of arguments were built into the translate function.

Body:
Try the following XSLT expression:

<xsl:value-of select="substring(translate(concat(E_Firstname, ',', E_Lastname, ' ', E_MiddleInitial, '                       '), $smallcase, $uppercase),1,24)"/>

It should fix your problem.

In a full example with the sample XML

<?xml version='1.0' encoding='UTF-8'?>
<Data>
    <E_Firstname>Homer</E_Firstname>
    <E_Lastname>Simpson</E_Lastname>
    <E_MiddleInitial>J.</E_MiddleInitial>
</Data>

and the sample XSLT-1.0 stylesheet

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />

  <xsl:template match="/Data">
    <xsl:value-of select="substring(translate(concat(E_Firstname, ',', E_Lastname, ' ', E_MiddleInitial, '                       '), $smallcase, $uppercase),1,24)"/>
  </xsl:template>

</xsl:stylesheet>

the result will be

<?xml version="1.0"?>
HOMER,SIMPSON J.


问:
SharePoint 2010: Problem trying to install web part using power shell
I'm trying to deploy my first web part on 2010. I developed a web part using VS2008 and tested it on SP2007.

I copied the CAB to the 2010 server and tried to use the power shell to install it:

```<code>PS C:\Users\sa_portalt> Install-SPWebPartPack -LiteralPath "c:\transfer\webparts\redirectwebpart.cab" -Name "RedirectWebPart"
Install-SPWebPartPack : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:22
+ Install-SPWebPartPack <<<<  -LiteralPath "c:\transfer\webparts\redirectwebpart.cab" -Name "RedirectWebPart"
    + CategoryInfo          : InvalidArgument: (:) [Install-SPWebPartPack], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.SharePoint.PowerShell.SPCmdletInstallWebPartPack
</code>```

What am I doing wrong? Is this the right way to install web parts?

答:
This was the first article I found that provided the actual answer, however, in the Install-SPSolution, there is a typeo, the -Indentify parameter should be -Identity

Also, in most cases (if adding to the GAC) need to add the -GACDeployment to the Install-SPSolution.

So the line should look like:
Install-SPSolution -Identity BasicWebPart.wsp -WebApplication http://vsp -GACDeployment

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to deploy my first web part on 2010. I developed a web part using VS2008 and tested it on SP2007.

I copied the CAB to the 2010 server and tried to use the power shell to install it:

PS C:\Users\sa_portalt> Install-SPWebPartPack -LiteralPath "c:\transfer\webparts\redirectwebpart.cab" -Name "RedirectWebPart"
Install-SPWebPartPack : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:22
+ Install-SPWebPartPack <<<<  -LiteralPath "c:\transfer\webparts\redirectwebpart.cab" -Name "RedirectWebPart"
    + CategoryInfo          : InvalidArgument: (:) [Install-SPWebPartPack], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.SharePoint.PowerShell.SPCmdletInstallWebPartPack

What am I doing wrong? Is this the right way to install web parts?


问:
Blogger B:if for comments and b:loop tag for displaying commnets
i have a blog on blogger: Mobtakr
I wanted to display comments in posts using the blogger tag b:loop instead of this data code

```<code>  <data:post.commentHtml/>
</code>```

So i used this code cause i wanted to implement schema markup for comments :

```<code>  <ol id="top-ra" >
<b:loop values='data:post.comments' var='comment'>
  <li itemscope='itemscope' itemtype='https://schema.org/Comment'  class="comment" expr:id='data:comment.anchorName' >
<div class="comment-block">
<div class="comment-header">
<b:if cond='data:comment.authorUrl'>
<a expr:href='data:comment.authorUrl' itemprop='author' itemscope='itemscope' itemtype='https://schema.org/Person' rel='nofollow'>
<span itemprop="name">
<data:comment.author/>
  </span>
</a>
<b:else/>
<a expr:href='data:comment.authorUrl' itemprop='author' itemscope='itemscope' itemtype='https://schema.org/Person' rel='nofollow'>
<data:comment.author/></a>
</b:if>
<time expr:datetime="data:comment.timestamp" itemprop="dateCreated"  class="datetime secondary-text">
<data:comment.timestamp/>
  </time>
  </div>
<p  class='comment-body' expr:id='data:widget.instanceId + data:comment.cmtBodyIdPostfix' itemprop='text'>
<data:comment.body/>
</p>
    </div>
<div class="comment-replies" >
<ol >

<b:loop values='data:post.comments-replies' var='comment'>
/*
So i want to loop the replies here and add some custom styles to them */
</b:loop>
</ol>
    </div>
</li>
</b:loop>
</ol>
</code>```

the problem is i cant find a condition for comment replies or if the comment has replies then loop its replies with some style to make the replies different from the comment itself and margin the replies.

So, can anyone help me  ?

Is there a b:if tag with the condition cond="hasReplies" ?

答:
There is two versions of comments structure in Blogger, Comments and threadedComments.
The first one (which you are using) is customizable but unfortunately it does not support comment replies.

So if you want to use comment replies in your blog you should use the second one threadedComments, but it is not customizable, which means you can not edit HTML or add schema markup to it.

Body:
i have a blog on blogger: Mobtakr
I wanted to display comments in posts using the blogger tag b:loop instead of this data code

  <data:post.commentHtml/>

So i used this code cause i wanted to implement schema markup for comments :

<data:comment.author/>

<data:comment.author/>

<time expr:datetime="data:comment.timestamp" itemprop="dateCreated"  class="datetime secondary-text">
<data:comment.timestamp/>
  </time>

<data:comment.body/>

/*
So i want to loop the replies here and add some custom styles to them */

the problem is i cant find a condition for comment replies or if the comment has replies then loop its replies with some style to make the replies different from the comment itself and margin the replies.

So, can anyone help me  ?

Is there a b:if tag with the condition cond="hasReplies" ?


问:
Python dataclass from a nested dict
The standard library in 3.7 can recursively convert a dataclass into a dict (example from the docs):

```<code>from dataclasses import dataclass, asdict
from typing import List

@dataclass
class Point:
     x: int
     y: int

@dataclass
class C:
     mylist: List[Point]

p = Point(10, 20)
assert asdict(p) == {'x': 10, 'y': 20}

c = C([Point(0, 0), Point(10, 4)])
tmp = {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
assert asdict(c) == tmp
</code>```

I am looking for a way to turn a dict back into a dataclass when there is nesting. Something like C(**tmp) only works if the fields of the data class are simple types and not themselves dataclasses. I am familiar with jsonpickle, which however comes with a prominent security warning.

EDIT:

Answers have suggested the following libraries:

dacite

mashumaro (I used for a while, works well but I quickly ran into tricky corner cases)

pydantic (works very well, excellent documentation and fewer corner cases)

答:
I would like to suggest using the Composite Pattern to solve this,
the main advantage is that you could continue adding classes to this pattern
and have them behave the same way.

```<code>from dataclasses import dataclass
from typing import List

@dataclass
class CompositeDict:
    def as_dict(self):
        retval = dict()
        for key, value in self.__dict__.items():
            if key in self.__dataclass_fields__.keys():
                if type(value) is list:
                    retval[key] = [item.as_dict() for item in value]
                else:
                    retval[key] = value
        return retval

@dataclass
class Point(CompositeDict):
    x: int
    y: int

@dataclass
class C(CompositeDict):
    mylist: List[Point]

c = C([Point(0, 0), Point(10, 4)])
tmp = {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
assert c.as_dict() == tmp
</code>```

as a side note, you could employ a factory pattern within the CompositeDict class that would handle other cases like nested dicts, tuples and such, which would save much boilerplate.

Title: Python dataclass from a nested dict

Body:
The standard library in 3.7 can recursively convert a dataclass into a dict (example from the docs):

from dataclasses import dataclass, asdict
from typing import List

@dataclass
class Point:
     x: int
     y: int

@dataclass
class C:
     mylist: List[Point]

p = Point(10, 20)
assert asdict(p) == {'x': 10, 'y': 20}

c = C([Point(0, 0), Point(10, 4)])
tmp = {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
assert asdict(c) == tmp

I am looking for a way to turn a dict back into a dataclass when there is nesting. Something like C(**tmp) only works if the fields of the data class are simple types and not themselves dataclasses. I am familiar with jsonpickle, which however comes with a prominent security warning.

EDIT:

Answers have suggested the following libraries:

dacite

mashumaro (I used for a while, works well but I quickly ran into tricky corner cases)

pydantic (works very well, excellent documentation and fewer corner cases)

Body:
I would like to suggest using the Composite Pattern to solve this,
the main advantage is that you could continue adding classes to this pattern
and have them behave the same way.

from dataclasses import dataclass
from typing import List

@dataclass
class CompositeDict:
    def as_dict(self):
        retval = dict()
        for key, value in self.__dict__.items():
            if key in self.__dataclass_fields__.keys():
                if type(value) is list:
                    retval[key] = [item.as_dict() for item in value]
                else:
                    retval[key] = value
        return retval

@dataclass
class Point(CompositeDict):
    x: int
    y: int

@dataclass
class C(CompositeDict):
    mylist: List[Point]

c = C([Point(0, 0), Point(10, 4)])
tmp = {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
assert c.as_dict() == tmp

as a side note, you could employ a factory pattern within the CompositeDict class that would handle other cases like nested dicts, tuples and such, which would save much boilerplate.


问:
Using Twilio Studio Rest API V2
I'm wondering how can i use the Twilio Studio Rest API V2. In the below link, It is saying 'Studio v2 REST API is currently in pilot and available by invitation only.' how can i get the invitation?
The limitation of Studio Flow is that there can be only one developer working on a Studio flow at a time.
And there is no CI/CD through the Twilio Console.
Actually I'm wondering and searching for how can i integrate Twilio studio into CI/CD pipeline to automate Studio deployments and how can i enable multiple developers for working on same flow?
Does anybody know any tutorial about this subject? I didn't find on twilio docs.

https://www.twilio.com/docs/studio/rest-api/v2

答:
Sounds looks a very solid use case. If you email help@twilio.com (with your Twilio Account SID) or from the Twilio Console, in the upper right corner, via the ? (see image below), submit a ticket, Twilio support should be able to route your request to the proper team within Twilio to enable this feature.

You can copy/paste your above question into the ticket.

Title: Using Twilio Studio Rest API V2


问:
Twig Variable in Array
AuthContoller:

```<code>   return $this->render('pages/login.html.twig', [
        'LoginForm'  => $form->createView(),
        'lang'       => self::getStrings('en-en') // Returns an array,
        'message'    => $verify['string'],
    ]);
</code>```

Normally I call a string in a twig template with {{ lang.stringname }}. In this case I want to call a string with the value, which was submitted via 'message'.

I tried this:

```<code>{{ lang[message] }}
</code>```

and

```<code>{{ lang.[message] }}.
</code>```

The error message is:

```<code>Expected name or number.
</code>```

Does anyone have an idea? Thank you.

答:
The dot notation is a shortcut for an array[] - particularly useful for named arrays, but can also be used for numeric-indexes as well as. Use of the regular array is still possible, and that can take an independent variable as the key.

```<code>{{ lang[message] }}
</code>```

There is a TwigFiddle, based on one in @DarkBee's link to show it in use.

Title: Twig Variable in Array

Body:
AuthContoller:

   return $this->render('pages/login.html.twig', [
        'LoginForm'  => $form->createView(),
        'lang'       => self::getStrings('en-en') // Returns an array,
        'message'    => $verify['string'],
    ]);

Normally I call a string in a twig template with {{ lang.stringname }}. In this case I want to call a string with the value, which was submitted via 'message'.

I tried this:

{{ lang[message] }}

and

{{ lang.[message] }}.

The error message is:

Expected name or number.

Does anyone have an idea? Thank you.

Body:
The dot notation is a shortcut for an array[] - particularly useful for named arrays, but can also be used for numeric-indexes as well as. Use of the regular array is still possible, and that can take an independent variable as the key.

{{ lang[message] }}

There is a TwigFiddle, based on one in @DarkBee's link to show it in use.


问:
Alternative Method for popoverPresentationControllerDidDismissPopover?
I've just found out that popoverPresentationControllerDidDismissPopover method has been deprecated.
What is an alternative method for this?

答:
It appears that the UIPopoverPresentationControllerDelegate protocol includes the UIAdaptivePresentationControllerDelegate protocol, which has

    // Called on the delegate when the user has taken action to dismiss the presentation successfully, after all animations are finished.
    // This is not called if the presentation is dismissed programatically.
    @available(iOS 13.0, *)
    optional func presentationControllerDidDismiss(_ presentationController: UIPresentationController)
```

and presentationControllerDidDismiss() appears to be called when the popover is dismissed.

Body:
It appears that the UIPopoverPresentationControllerDelegate protocol includes the UIAdaptivePresentationControllerDelegate protocol, which has

    // Called on the delegate when the user has taken action to dismiss the presentation successfully, after all animations are finished.
    // This is not called if the presentation is dismissed programatically.
    @available(iOS 13.0, *)
    optional func presentationControllerDidDismiss(_ presentationController: UIPresentationController)

and presentationControllerDidDismiss() appears to be called when the popover is dismissed.


问:
Find count of each consecutive characters
Need to find the count of each consecutive characters in a row.
Ex: aaaabbccaa
output: 4a2b2c2a

Character may repeat but need to count only consecutive ones. I also need to maintain original sequence.

I tried following but it groups all characters so was not useful.

```<code>str.GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).ToList().ForEach(x => str+= x.Count + "" + x.Key)
</code>```

答:
Here is my non-LINQ version that is quite fast compared to LINQ or Regex:

```<code>    var prevChar = str[0];
    var ct = 1;
    var s = new StringBuilder();
    var len = str.Length;
    for (int j2 = 1; j2 < len; ++j2) {
        if (str[j2] == prevChar)
            ++ct;
        else {
            s.Append(ct);
            s.Append(prevChar);
            ct = 1;
            prevChar = str[j2];
        }
    }
    s.Append(ct);
    s.Append(prevChar);
    var final = s.ToString();
}
</code>```

My LINQ version looks like this, but uses a couple of extension methods I already had:

```<code>var ans = str.GroupByRuns().Select(s => $"{s.Count()}{s.Key}").Join();
</code>```

Body:
Need to find the count of each consecutive characters in a row.
Ex: aaaabbccaa
output: 4a2b2c2a

Character may repeat but need to count only consecutive ones. I also need to maintain original sequence.

I tried following but it groups all characters so was not useful.

str.GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).ToList().ForEach(x => str+= x.Count + "" + x.Key)

Body:
Here is my non-LINQ version that is quite fast compared to LINQ or Regex:

    var prevChar = str[0];
    var ct = 1;
    var s = new StringBuilder();
    var len = str.Length;
    for (int j2 = 1; j2 < len; ++j2) {
        if (str[j2] == prevChar)
            ++ct;
        else {
            s.Append(ct);
            s.Append(prevChar);
            ct = 1;
            prevChar = str[j2];
        }
    }
    s.Append(ct);
    s.Append(prevChar);
    var final = s.ToString();
}

My LINQ version looks like this, but uses a couple of extension methods I already had:

var ans = str.GroupByRuns().Select(s => $"{s.Count()}{s.Key}").Join();


问:
Salesforce Table Relationships for Business Analyst
I am a business analyst. I use Tableau a lot but have limited knowledge about the back-end of Salesforce. The majority of our company's data is stored in Salesforce and our data team does not support business users for understanding such topics.

In many of my projects, I use the Salesforce connector inside Tableau to extract Salesforce tables, but it requires knowledge about joins relationships among tables. Most of the time, I can guess correctly about the primary key among tables, but I still want to learn systematically about the data structure and have my data independence.

So, how do I learn the data structure by myself? Or how do I ask specific structure questions to data team so I don't trouble them as much?

答:
Do you have Salesforce account with "Customize Application" permission? If you don't have in production - maybe they'll be willing to promote you to sysadmin in one of sandboxes.

If you do - Setup -> Schema Builder might be easiest tool to visualise relations. It's bit old, flash-based but pretty neat way to model relationships. https://trailhead.salesforce.com/en/content/learn/modules/data_modeling/schema_builder

Another one might be workbench, http://workbench.developerforce.com/ It's not as neat but lets you experiment with metadata & queries, learn which object has what child relationships...

For standard objects if you have a primary key / foreign key you can use some lookup tables to learn more about target table. All Account Ids in all SF instances start with 001. Contacts with 003, Users with 005... Combine some blogs like http://www.fishofprey.com/2011/09/obscure-salesforce-object-key-prefixes.html with https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_account.htm and it's a good start. Won't help much with custom objects and fields (specific to your company) but well.

It's bit "meta" but you can query info about tables and columns too. After all - you might be more comfortable in Tableau ;) Querying Salesforce Object Column Names w/SOQL might give you some hints.


问:
Mongoid: Changing the order of documents in an embeds_many relation
I have a mongoid document which embeds other documents with a relation like
this:

embeds_many :blocks

Creating new blocks works fine, but I cannot manage to change the
order of existing embedded documents. For example I have three
embedded blocks and I want to move the last one to the first
position.What's the correct way to do that?

答:
I had to deal with this with mongoid's recursively_embeds_many feature, but it's essentially the same. There's nothing wrong as far as I can tell with literally rewriting the document. Write a model method to do something like:

```<code>def reverse_blocks
  reversed_blocks = blocks.to_a.reverse
  blocks.clear
  reversed_blocks.each do |b|
    blocks.create b.attributes
  end
  save
end
</code>```

That's not great code above, but it gives you an idea of how to do what you want to do. I'm not thrilled with having to go through that just to reorder stuff in an array, but there it is.

Body:
I had to deal with this with mongoid's recursively_embeds_many feature, but it's essentially the same. There's nothing wrong as far as I can tell with literally rewriting the document. Write a model method to do something like:

def reverse_blocks
  reversed_blocks = blocks.to_a.reverse
  blocks.clear
  reversed_blocks.each do |b|
    blocks.create b.attributes
  end
  save
end

That's not great code above, but it gives you an idea of how to do what you want to do. I'm not thrilled with having to go through that just to reorder stuff in an array, but there it is.


问:
Android 5 ADB notification dump wrong data
I built a pc program that works on your desktop and informs you about notifications, power-level, and lets you interact with your smartphone.
All over the ADB - so no app on the phone is required.
And all that in a stylish way.

But enough for that, it worked until android 5 came along.

The notification dump (adb shell dumpsys notifications) shows different outputs than in sdk <= 19

For example:

The extras region showed me detailed informations about the notifications.

      extras={
        android.title=String
        android.subText=null
        android.template=String
        android.showChronometer=Boolean (false)
        android.icon=Integer (2130837507)
        android.text=String
        android.progress=Integer (0)
        android.progressMax=Integer (0)
        android.showWhen=Boolean (true)
        android.rebuild.applicationInfo=ApplicationInfo (ApplicationInfo{14a2c165 com.nero.android.htc.sync})
        android.rebuild.contentView=Boolean (true)
        android.bigText=String
        android.infoText=null
        android.originatingUserId=Integer (0)
        android.progressIndeterminate=Boolean (false)
        android.rebuild=Boolean (true)
        android.rebuild.bigView=Boolean (true)
      }
```

This is an example of the android 5 Notification dump.
You see, there are only datatypes for strings, not the actual values.

Does anybody know how i can get the actual values? Like some parameters i am missing?

Or do you know an even better way of getting the notifications from the phone to the pc?

答:
On Android >= 6 use this command to get full text of notification extras:

adb shell dumpsys notification --noredact
```

<p>it will print both types and values</p>

```
      extras={
          android.title=String (Bring The Rain)
          android.reduced.images=Boolean (true)
          android.subText=null
          android.template=String (android.app.Notification$MediaStyle)
          toSingleLine=Boolean (false)
          android.text=String (Upon A Burning Body)
          android.appInfo=ApplicationInfo (ApplicationInfo{c8165e6 org.telegram.messenger})
          android.showWhen=Boolean (false)
          android.largeIcon=Icon (Icon(typ=BITMAP size=100x100))
          android.mediaSession=Token (android.media.session.MediaSession$Token@608a746)
          gameDndOn=Boolean (false)
          android.compactActions=int[] (3)
            [0] 0
            [1] 1
            [2] 2
      }
```

Body:
I built a pc program that works on your desktop and informs you about notifications, power-level, and lets you interact with your smartphone.
All over the ADB - so no app on the phone is required.
And all that in a stylish way.

But enough for that, it worked until android 5 came along.

The notification dump (adb shell dumpsys notifications) shows different outputs than in sdk <= 19

For example:

The extras region showed me detailed informations about the notifications.

      extras={
        android.title=String
        android.subText=null
        android.template=String
        android.showChronometer=Boolean (false)
        android.icon=Integer (2130837507)
        android.text=String
        android.progress=Integer (0)
        android.progressMax=Integer (0)
        android.showWhen=Boolean (true)
        android.rebuild.applicationInfo=ApplicationInfo (ApplicationInfo{14a2c165 com.nero.android.htc.sync})
        android.rebuild.contentView=Boolean (true)
        android.bigText=String
        android.infoText=null
        android.originatingUserId=Integer (0)
        android.progressIndeterminate=Boolean (false)
        android.rebuild=Boolean (true)
        android.rebuild.bigView=Boolean (true)
      }

This is an example of the android 5 Notification dump.
You see, there are only datatypes for strings, not the actual values.

Does anybody know how i can get the actual values? Like some parameters i am missing?

Or do you know an even better way of getting the notifications from the phone to the pc?

Body:
On Android >= 6 use this command to get full text of notification extras:

adb shell dumpsys notification --noredact

it will print both types and values

      extras={
          android.title=String (Bring The Rain)
          android.reduced.images=Boolean (true)
          android.subText=null
          android.template=String (android.app.Notification$MediaStyle)
          toSingleLine=Boolean (false)
          android.text=String (Upon A Burning Body)
          android.appInfo=ApplicationInfo (ApplicationInfo{c8165e6 org.telegram.messenger})
          android.showWhen=Boolean (false)
          android.largeIcon=Icon (Icon(typ=BITMAP size=100x100))
          android.mediaSession=Token (android.media.session.MediaSession$Token@608a746)
          gameDndOn=Boolean (false)
          android.compactActions=int[] (3)
            [0] 0
            [1] 1
            [2] 2
      }


问:
cumsum within repeating sequence
I have a dataframe that looks like this:

```<code>df <- data.frame((v1=c(4,5,6,1,2,3,4,5,6,1,2,3),v2=c(0,7,3,6,2,6,9,2,4,7,1,4))
</code>```

How do I get the cumsum for v2 as long as v1 is increasing and when v1 is decreasing (dropping from 6 to 1) the cumsum should restart. (Imagine the sequence in v1 goes multiple times from 1 to 6 but could start and end at any number of the sequence)
The result should look like this:

```<code>df <- data.frame((v1=c(4,5,6,1,2,3,4,5,6,1,2,3),v2=c(0,7,3,6,2,6,9,2,4,7,1,4), expected=c(0,7,10,6,8,14,23,25,29,7,8,12)
</code>```

Thanks for the help

答:
We can create a group based on the difference between adjacent elements of 'v1' and then do the cumsum

```<code>library(dplyr)
df %>%
   group_by(grp = cumsum(c(TRUE, diff(v1) < 0))) %>%
   mutate(new = cumsum(v2)) %>%
   ungroup %>%
   select(-grp)
</code>```

Or it can be done in base R

```<code>df$new <- with(df, ave(v2, cumsum(c(TRUE, diff(v1) < 0)), FUN = cumsum))
df$new
#[1]  0  7 10  6  8 14 23 25 29  7  8 12
</code>```

Title: cumsum within repeating sequence

Body:
I have a dataframe that looks like this:

df <- data.frame((v1=c(4,5,6,1,2,3,4,5,6,1,2,3),v2=c(0,7,3,6,2,6,9,2,4,7,1,4))

How do I get the cumsum for v2 as long as v1 is increasing and when v1 is decreasing (dropping from 6 to 1) the cumsum should restart. (Imagine the sequence in v1 goes multiple times from 1 to 6 but could start and end at any number of the sequence)
The result should look like this:

df <- data.frame((v1=c(4,5,6,1,2,3,4,5,6,1,2,3),v2=c(0,7,3,6,2,6,9,2,4,7,1,4), expected=c(0,7,10,6,8,14,23,25,29,7,8,12)

Thanks for the help

Body:
We can create a group based on the difference between adjacent elements of 'v1' and then do the cumsum

library(dplyr)
df %>%
   group_by(grp = cumsum(c(TRUE, diff(v1) < 0))) %>%
   mutate(new = cumsum(v2)) %>%
   ungroup %>%
   select(-grp)

Or it can be done in base R

df$new <- with(df, ave(v2, cumsum(c(TRUE, diff(v1) < 0)), FUN = cumsum))
df$new
#[1]  0  7 10  6  8 14 23 25 29  7  8 12


问:
Unable to connect to Orion Context Broker using Wirecloud
I am new to FIWARE. I managed to install Orion Context Broker on my local system following the steps mentioned in the FIWARE website. I am able to use CURL commands to create entities and also retrieve values.

I have also installed Wirecloud on my local system and able to access Wirecloud UI from my browser.

But I am unable to display the entities on the Wirecloud widgets.  I have tried all widgets including "NGSI Type Browser", NGSI Browser and NGSI Source operator.

All returning the same error: "ConnectionError: Unexpected response from WireCloud's proxy"

Please help me on how to proceed.  My NGSI-proxy is also running and listening on port 3000.  Screenshots attached.
 enter image description here

答: Can you try to replace localhost with IP address of your machine running Orion and Ngsiproxy?


问:
Reload page in framework7
Framework7 version: Framework7 5.4.1

In index.html ('/') I have a login button, that open a login.html (/login/) page. This page send a request, and if it's logged correctly, I save de ID of user in localstorage and redirect to index.html  ('/').

In index, I modify the login button if the user are logged, hiding the button, and showing a message:

```<code> if(localStorage.getItem('idCliente') == ''){
    $$('#login').html('<a class="col button button-fill menu color-green" href="/login/">Login</a>')
  }else{
    $$('#login').html('Welcome' + localStorage.getItem('nombreCliente')+'<a href="#" id="salir"> Salir</a>' )
  }
</code>```

Redirection works, but not reload a Dom. Does not show the button or text. If I reload page (F5), show the wellcome + user message.

I try clear history, and other route options, but does not work.

```<code>  app.views.main.router.clearPreviousHistory()
  app.views.main.router.navigate('/', {
    reloadCurrent: true,
    ignoreCache: true,
  });
</code>```

答:
you have to use</p>

```<code>pageAfterIn(e){
mainview.router.refreshPage();
//or
this.myrefreshFunction(); //call the refresh function which actually does the hiding
thing
}
</code>```

Title: Reload page in framework7

Body:
Framework7 version: Framework7 5.4.1

In index.html ('/') I have a login button, that open a login.html (/login/) page. This page send a request, and if it's logged correctly, I save de ID of user in localstorage and redirect to index.html  ('/').

In index, I modify the login button if the user are logged, hiding the button, and showing a message:

 if(localStorage.getItem('idCliente') == ''){
    $$('#login').html('Login')
  }else{
    $$('#login').html('Welcome' + localStorage.getItem('nombreCliente')+' Salir' )
  }

Redirection works, but not reload a Dom. Does not show the button or text. If I reload page (F5), show the wellcome + user message.

I try clear history, and other route options, but does not work.

  app.views.main.router.clearPreviousHistory()
  app.views.main.router.navigate('/', {
    reloadCurrent: true,
    ignoreCache: true,
  });

Body:
you have to use

pageAfterIn(e){
mainview.router.refreshPage();
//or
this.myrefreshFunction(); //call the refresh function which actually does the hiding
thing
}