问:
Replace child Fragment dynamically from Child Fragment itself
I am using a Viewpager which naturally contain fragments.
inside one of the fragments I have a sub fragment (child fragment)
each child fragment contains a button which calls the following to replace the child fragment itself

```<code>FragmentManager manager = getChildFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.containerProfileDetails, new ProfileDetailsAddressFragment());
transaction.commit();
</code>```

just to make it more visual:

1) is the parent fragment

2) is the child fragment.
I need to replace the child fragment by pressing a button inside the child fragment itself

```<code>┌--------┐
|   1    |
| ┌-----┐|
| | 2   ||
| |     ||
| └-----┘|
└--------┘
</code>```

Note: I know it is possible to replace the fragments using this approach, however, it seems that it is not possible to do this with child fragments as it throws following error.

java.lang.IllegalArgumentException: No view found for id 0x7f0f0104 (com.example.app:id/containerProfileDetails) for fragment ProfileDetailsAddressFragment

Update

Parent Fragment XML:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context="com.example.app.fragments.ProfileDetailsFragment">

<TextView
    android:id="@+id/lbl_page"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="42sp"
    tools:text="2"
    android:visibility="gone"/>

<FrameLayout
    android:id="@+id/containerProfileDetails"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ></FrameLayout>
</LinearLayout>
</code>```

Child Fragment XML:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.app.fragments.ProfileDetailsUserFragment">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Fragment Profile User Details" />

<Button
    android:id="@+id/btnProfileDetailsUserNext"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center"/>

</FrameLayout>
</code>```

Parent Fragment Java:

```<code> public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_profile_details, container, false);
    lblPage = (TextView) view.findViewById(R.id.lbl_page);

    FragmentManager manager = getChildFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.add(R.id.containerProfileDetails, new ProfileDetailsUserFragment());
    transaction.commit();
    return view;
}
</code>```

Child Fragment Java:

```<code>    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_profile_details_user, container, false);

    Button _btnProfileDetailsUserNext = (Button) v.findViewById(R.id.btnProfileDetailsUserNext);
    _btnProfileDetailsUserNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getChildFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.containerProfileDetails, new ProfileDetailsAddressFragment());
            transaction.commit();
        }
    });
    return v;
}
</code>```

答:
This will not work because in the Child Fragment, the fragment transaction is looking for a container with id R.id.containerProfileDetails. This container is not in the Child Fragment, but it is in the Parent Fragment.

What you need to do is to create a callback from the Child Fragment to the Parent Fragment. In the Onclick in your Child Fragment, call the callback to the Parent Fragment and then in the Parent Fragment, replace the Child Fragment with the desired Fragment.

Body:
I am using a Viewpager which naturally contain fragments.
inside one of the fragments I have a sub fragment (child fragment)
each child fragment contains a button which calls the following to replace the child fragment itself

FragmentManager manager = getChildFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.containerProfileDetails, new ProfileDetailsAddressFragment());
transaction.commit();

just to make it more visual:

1) is the parent fragment

2) is the child fragment.
I need to replace the child fragment by pressing a button inside the child fragment itself

┌--------┐
|   1    |
| ┌-----┐|
| | 2   ||
| |     ||
| └-----┘|
└--------┘

Note: I know it is possible to replace the fragments using this approach, however, it seems that it is not possible to do this with child fragments as it throws following error.

java.lang.IllegalArgumentException: No view found for id 0x7f0f0104 (com.example.app:id/containerProfileDetails) for fragment ProfileDetailsAddressFragment

Update

Parent Fragment XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context="com.example.app.fragments.ProfileDetailsFragment">

<TextView
    android:id="@+id/lbl_page"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="42sp"
    tools:text="2"
    android:visibility="gone"/>

<FrameLayout
    android:id="@+id/containerProfileDetails"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ></FrameLayout>
</LinearLayout>

Child Fragment XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.app.fragments.ProfileDetailsUserFragment">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Fragment Profile User Details" />

<Button
    android:id="@+id/btnProfileDetailsUserNext"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center"/>

</FrameLayout>

Parent Fragment Java:

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_profile_details, container, false);
    lblPage = (TextView) view.findViewById(R.id.lbl_page);

    FragmentManager manager = getChildFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.add(R.id.containerProfileDetails, new ProfileDetailsUserFragment());
    transaction.commit();
    return view;
}

Child Fragment Java:

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_profile_details_user, container, false);

    Button _btnProfileDetailsUserNext = (Button) v.findViewById(R.id.btnProfileDetailsUserNext);
    _btnProfileDetailsUserNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getChildFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.containerProfileDetails, new ProfileDetailsAddressFragment());
            transaction.commit();
        }
    });
    return v;
}


来源: stackexchange

问:
Confused between time complexity of following Dijkstra Algorithm Implementation
I was trying to implement Dijkstra using Adjacency list in java. I came across one of the implementation of Dijkstra in java, but i am confused whether it is O(ElogV) solution or 0(V^2) solution. Link to the code is : http://www.vogella.com/tutorials/JavaAlgorithmsDijkstra/article.html.
I am confused because optimized implementation of Dijkstra in c++ involve use of priority queues, but here priority queues are not used.</p>

答:
The time complexity of Dijkstra's algorithm using an Adjacency list is

With Adjacency List and Priority queue:

O((v+e) log v). If the graph is dense, then e will be v^2. (Fo example, a complete graph has (n(n/1)/2) = O(v^2) edges, so e >> v.)

For denser graphs, we can use a Fibonacci Heap instead of a priority queue.

With Adjacency List and Fibonacci Heap:

TC will be O( e + v log v)

since in denser graph e ~ v^2

TC will be O(v^2 + v log v) ~ O(v^2)

ContentLicense: CC BY-SA 3.0


问:
Dependent type automatic deduction
is it possible to do something like:

```<code>template<class T, T type>
constexpr auto f(/* type used in some way... */) // -> decltype (etc. in case of C++11)
  {
  return std::integral_constant<T,t>{};
  }

constexpr auto z = f(3); // z is deduced as an integral_constant<int,3>;
</code>```

It's for sure not possible using a runtime value, but 3 in this case is a compile time value. Maybe someone knows some trick I'm not aware of...

[edit]
  constexpr auto z2 = f<3>(); // This would be ok too

I just would like to avoid to repeat the type..

答:
You can use an auto template parameter in C++17:

```<code>template <auto T>
constexpr auto f()
{
    return std::integral_constant<decltype(T), T>{};
}
</code>```

Usage:

```<code>f<3>(); // integral_constant<int, 3>
</code>```

Alternatively, you need to wrap your value in a compile-time friendly way:

```<code>template <int X>
struct int_
{
    using type = int;
    static constexpr value = X;
};

template <typename T>
constexpr auto f(T)
{
    return std::integral_constant<typename T::type, T::value>{};
}
</code>```

Usage:

```<code>f(int_<3>{});
</code>```

Title: Dependent type automatic deduction

Body:
is it possible to do something like:

template<class T, T type>
constexpr auto f(/* type used in some way... */) // -> decltype (etc. in case of C++11)
  {
  return std::integral_constant<T,t>{};
  }

constexpr auto z = f(3); // z is deduced as an integral_constant<int,3>;

It's for sure not possible using a runtime value, but 3 in this case is a compile time value. Maybe someone knows some trick I'm not aware of...

[edit]
  constexpr auto z2 = f<3>(); // This would be ok too

I just would like to avoid to repeat the type..

Body:
You can use an auto template parameter in C++17:

template <auto T>
constexpr auto f()
{
    return std::integral_constant<decltype(T), T>{};
}

Usage:

f<3>(); // integral_constant<int, 3>

Alternatively, you need to wrap your value in a compile-time friendly way:

template <int X>
struct int_
{
    using type = int;
    static constexpr value = X;
};

template <typename T>
constexpr auto f(T)
{
    return std::integral_constant<typename T::type, T::value>{};
}

Usage:

f(int_<3>{});


问:
how can i group excerpts by fields in solr/lucene?
When I index the following document in Solr:

```<code>[
  {
    "id" : "978-0641723445",
    "name" : "The Lightning Thief",
    "author" : "Rick Riordan",
    "series_t" : "Rick Jackson and the Olympians",
  }
,
  {
    "id" : "978-1423103349",
    "cat" : ["book","paperback"],
    "name" : "The Sea of Monsters",
    "author" : "Rick Riordan",
    "series_t" : "Rick Jackson and the Olympians",
  }
]
</code>```

and run the following query:
http://localhost:8983/solr/gettingstarted/select?hl.fl=name&hl=on&indent=on&q=rick&rows=20&wt=json

I'd like to have an excerpt that consists of each matched field's name and a sub-excerpt of the field's contents (the actual format of the sub-excerpt is not so important):

```<code>"responseHeader": {
    "status": 0,
    "QTime": 1,
    "params": { ...
    },
    "response": {
        "numFound": 2,
        "start": 0,
        "docs": [{
                "id": "978-0641723445",
                .. {
                    "id": "978-1423103349",
                    ..
                }],
            "highlighting": {
                "978-0641723445": {
                    "author": "Rick Riordan",
                    "series_t": "Rick Riordan and..."
                },
                "978-1423103349": {
                    "author": "Rick Riordan",
                    "series_t": "Rick Riordan and..."

                }
            }
        }
    }
</code>```

How do I have to change my solr query to accomplish this? Or does this change require a custom solr/lucene highlighter?

答: Went with @MatsLindh's solution (see comment).</p>

Body:
When I index the following document in Solr:

[
  {
    "id" : "978-0641723445",
    "name" : "The Lightning Thief",
    "author" : "Rick Riordan",
    "series_t" : "Rick Jackson and the Olympians",
  }
,
  {
    "id" : "978-1423103349",
    "cat" : ["book","paperback"],
    "name" : "The Sea of Monsters",
    "author" : "Rick Riordan",
    "series_t" : "Rick Jackson and the Olympians",
  }
]

and run the following query:
http://localhost:8983/solr/gettingstarted/select?hl.fl=name&hl=on&indent=on&q=rick&rows=20&wt=json

I'd like to have an excerpt that consists of each matched field's name and a sub-excerpt of the field's contents (the actual format of the sub-excerpt is not so important):

"responseHeader": {
    "status": 0,
    "QTime": 1,
    "params": { ...
    },
    "response": {
        "numFound": 2,
        "start": 0,
        "docs": [{
                "id": "978-0641723445",
                .. {
                    "id": "978-1423103349",
                    ..
                }],
            "highlighting": {
                "978-0641723445": {
                    "author": "Rick Riordan",
                    "series_t": "Rick Riordan and..."
                },
                "978-1423103349": {
                    "author": "Rick Riordan",
                    "series_t": "Rick Riordan and..."

                }
            }
        }
    }

How do I have to change my solr query to accomplish this? Or does this change require a custom solr/lucene highlighter?


问:
Script can't find library when run as cron job, works fine when run manually
I am creating the script below in cronjob. It is manually getting generated. But, when in cron, it is failing to generate the files.

Below is my unix cron script.

```<code>#!/usr/local/bin/bash
var=`perl -w -e '$d=1*86400;@t=localtime (time -$d); printf "%.2d%.2d%.2d", $t[5]+1900,$t[4]+1,$t[3];'`

var="`echo $var |cut -c3-8`"

i=1;

while [ $i -le 8 ]
do

    cd /home/svfe/bin
    ./bills_unloader -d $var -f $i
    i=`expr $i + 1`
done

echo "Done !
</code>```

When I try to debug the script, I am finding below error.

/usr/lib/hpux64/dld.so: Unable to find library 'libclntsh.so.11.1'.
  /home/swa/swa2/autoload/bills_unloader.sh: line 19:  7078 Killed

  ./bills_unloader -d 170606 -f $i

Why is the command failing in cron, but working fine when executed manually?

答:
Most probably you have LD_LIBRARY_PATH variable set in your CLI environment, but it is not available when script is run under cron. Add a line:

```<code>declare -x > /tmp/variables.log.$(date +%s).$$
</code>```

at the beginning of the script, the compare the logs from manual run and cron run. If necessary, set the LD_LIBRARY_PATH properly in your script.

As it is a hpux system, it could be also SHLIB_PATH.

Body:
I am creating the script below in cronjob. It is manually getting generated. But, when in cron, it is failing to generate the files.

Below is my unix cron script.

#!/usr/local/bin/bash
var=`perl -w -e '$d=1*86400;@t=localtime (time -$d); printf "%.2d%.2d%.2d", $t[5]+1900,$t[4]+1,$t[3];'`

var="`echo $var |cut -c3-8`"

i=1;

while [ $i -le 8 ]
do

    cd /home/svfe/bin
    ./bills_unloader -d $var -f $i
    i=`expr $i + 1`
done

echo "Done !

When I try to debug the script, I am finding below error.

/usr/lib/hpux64/dld.so: Unable to find library 'libclntsh.so.11.1'.
  /home/swa/swa2/autoload/bills_unloader.sh: line 19:  7078 Killed

  ./bills_unloader -d 170606 -f $i

Why is the command failing in cron, but working fine when executed manually?

Body:
Most probably you have LD_LIBRARY_PATH variable set in your CLI environment, but it is not available when script is run under cron. Add a line:

declare -x > /tmp/variables.log.$(date +%s).$$

at the beginning of the script, the compare the logs from manual run and cron run. If necessary, set the LD_LIBRARY_PATH properly in your script.

As it is a hpux system, it could be also SHLIB_PATH.


问:
Clear Interval issue for a nested setInterval
I'm trying to clearInterval an interval that is already set.
My first setInterval object has a piece of code that does something every 12 seconds, also within the same function, there is another setInterval object that does something every 1 second within this 12 sec timeframe.

So the problem here is, I can do clearInterval for the main (outer) setInterval object, but nothing happens to the inner.

Please refer to the Code snippet.

```<code>start.addEventListener("click", function() {

    interval = setInterval(function() {

        Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

        interval1 = setInterval(startTimer, 1000);

    }, 12000);

});

stop.addEventListener("click", function() {
    clearInterval(interval);
    clearInterval(interval1);
});
</code>```

So, I tried to clear interval the inner setInterval object first and then outer later, still no luck and nothing happens.

Any quick solutions, suggestions are really appreciated as I can't proceed any further with this issue on the way.

Thanks in advance.

答:
```<code>interval = setInterval(function() {

    Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

    interval1 = setInterval(startTimer, 1000);

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

Means that you create a new interval and store it at interval1 every 12 seconds. So after one minute, youve got five timers running that will trigger startTimer, interval1 is just pointing to the last one. You may move the interval1 out of interval:

```<code> interval = setInterval(function() {

    Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

}, 12000);

interval1 = setInterval(startTimer, 1000);
</code>```

Or if you really want to kill your browser with tons of intervals, you could store the interval1s in  an array:

```<code>intervals1=[];
 interval = setInterval(function() {

    Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

    intervals1.push(setInterval(startTimer, 1000));

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

To terminate all intervals:

```<code>intervals1.forEach(interval=>destroyInterval(interval));
</code>```

Note that its bad style not to declare variables, so you may do:

```<code>var interval,interval1;
</code>```

in the global scope.

Body:
I'm trying to clearInterval an interval that is already set.
My first setInterval object has a piece of code that does something every 12 seconds, also within the same function, there is another setInterval object that does something every 1 second within this 12 sec timeframe.

So the problem here is, I can do clearInterval for the main (outer) setInterval object, but nothing happens to the inner.

Please refer to the Code snippet.

start.addEventListener("click", function() {

    interval = setInterval(function() {

        Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

        interval1 = setInterval(startTimer, 1000);

    }, 12000);

});

stop.addEventListener("click", function() {
    clearInterval(interval);
    clearInterval(interval1);
});

So, I tried to clear interval the inner setInterval object first and then outer later, still no luck and nothing happens.

Any quick solutions, suggestions are really appreciated as I can't proceed any further with this issue on the way.

Thanks in advance.

Body:
interval = setInterval(function() {

    Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

    interval1 = setInterval(startTimer, 1000);

}, 12000);

Means that you create a new interval and store it at interval1 every 12 seconds. So after one minute, youve got five timers running that will trigger startTimer, interval1 is just pointing to the last one. You may move the interval1 out of interval:

 interval = setInterval(function() {

    Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

}, 12000);

interval1 = setInterval(startTimer, 1000);

Or if you really want to kill your browser with tons of intervals, you could store the interval1s in  an array:

intervals1=[];
 interval = setInterval(function() {

    Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

    intervals1.push(setInterval(startTimer, 1000));

}, 12000);

To terminate all intervals:

intervals1.forEach(interval=>destroyInterval(interval));

Note that its bad style not to declare variables, so you may do:

var interval,interval1;

in the global scope.


问:
Feign client : Long in a Map<String, Object> decoded as Integer
```<code>public interface ItemsClient {
    @RequestLine("POST /items")
    public Map<String, Object> post(Map<String, Object> item);
}
</code>```

Then

```<code>ItemsClient itemsClient = Feign.builder().decoder(new GsonDecoder()).encoder(new GsonEncoder()).target(ItemsClient.class, ROOT_URI);
Map<String, Object> myNewItemWithId = itemsClient.post(myNewItem);
</code>```

The server send a response with a body like :

```<code>{
    "id" : 108171343002018,
    "name" : "myNewItem among many and many !"
}
</code>```

But then the value of myNewItemWithId.get("id"); is 2147483647, the maximum value of Integer.

Is there a way to tell GsonDecoder to decode the integer numbers into Long ?

答:
It works with the JacksonDecoder.</p>

```<code><dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-jackson</artifactId>
    <version>9.0.0</version>
</dependency>
</code>```

Body:
public interface ItemsClient {
    @RequestLine("POST /items")
    public Map<String, Object> post(Map<String, Object> item);
}

Then

ItemsClient itemsClient = Feign.builder().decoder(new GsonDecoder()).encoder(new GsonEncoder()).target(ItemsClient.class, ROOT_URI);
Map<String, Object> myNewItemWithId = itemsClient.post(myNewItem);

The server send a response with a body like :

{
    "id" : 108171343002018,
    "name" : "myNewItem among many and many !"
}

But then the value of myNewItemWithId.get("id"); is 2147483647, the maximum value of Integer.

Is there a way to tell GsonDecoder to decode the integer numbers into Long ?

Body:
It works with the JacksonDecoder.

<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-jackson</artifactId>
    <version>9.0.0</version>
</dependency>


问:
How to create a git pull request on a public github repository
There is a public github repository to which I want to create a pull request. I have a project on my local machine that I need to check in and send it to them for review. I have tried the following and failed </p>

```<code>git clone public repo
# create new branch
# add code in the branch
git add/commit changes to this new branch
git push
</code>```

<p>When I do the git push I enter my github account credentials and it fails. I know that this should fail because I don't have access to their repo but what I am doing wrong? Do I need to create some sort of an account with them? </p>

答:
You first have to fork the project :

Then you can work on your version of the code.

You will finally push your branch to your repository and then you will be able to create a pull request on the main project.

You can find extra info here: Fork a repo or Contribute to someone's repository

PS: Related to How do I contribute to other's code in GitHub?

Body:
There is a public github repository to which I want to create a pull request. I have a project on my local machine that I need to check in and send it to them for review. I have tried the following and failed

git clone public repo
# create new branch
# add code in the branch
git add/commit changes to this new branch
git push

When I do the git push I enter my github account credentials and it fails. I know that this should fail because I don't have access to their repo but what I am doing wrong? Do I need to create some sort of an account with them?


问:
unable to append data using java-script given by explode function
i am trying to read input from a file using explode function.  when i am passing the values to a java-script variable and the appending a div tag with elements of the array i get undefined as out.

<?php

$strings = file_get_contents('questions.txt');
$new_string = explode('
', $strings);
$count = count($new_string);
echo $count;

?>
<!DOCTYPE html>

 <title>TEST</title>

```

contents from question.txt:
1.Principle: When a person who has made a promise to another perso
n to do something does not fulfill his promise, the other person beco
mes entitled to receive, from the person who did not fulfill his promi
se, compensation in the form of money.
Facts: ‘X’ made a promise to ‘Y’ to repair his car engine. ‘Y’ made the
payment for repair. After the repair, ‘Y’ went for a drive in the same c
ar. While driving the car, ‘Y’ met with an accident due to bursting of a
tyre.

1. ‘X’ will not be entitled to receive compensation.

2. ‘Y’ will not be entitled to receive compensation from ‘X’.

3. ‘Y’ will be entitled to receive compensation from ‘X’ in the form of
money.

4. ‘X’ will be entitled to receive compensation from ‘Y’ in the form of
money.

答:
console.log(string) gives the following output
["1.Principle: When a person who has made a promise …’ met with an accident due to bursting of a↵tyre.", "↵1. ‘X’ will not be entitled to receive compensation.", "↵2. ‘Y’ will not be entitled to receive compensation from ‘X’.", "↵3. ‘Y’ will be entitled to receive compensation from ‘X’ in the form of↵money.", "↵4. ‘X’ will be entitled to receive compensation from ‘Y’ in the form of↵money.", "↵↵2.Principle: Where one of the parties to a contr…nt from the patient. The patient refused t↵o pay.", "↵1. The contract is enforceable against the doctor.", "↵2. The contract is not enforceable as doctor was in dominating posit↵ion.", "↵3. The contract is enforceable against the patient by the doctor.", "↵4. The contract is not enforceable without the consent of the patien↵t.", "↵↵3.Principle: Penal laws provide that whoever vol…rested the man and produced him↵before the Court.", "↵1. Court will punish the man for rape.", "↵2. Court will not punish the police officer.", "↵3. Court will punish the police officer.", "↵4. Court will not punish the man for rape.", "↵↵4.Principle: Whoever takes away with him any min…umbai wit↵hout informing the parents of the girl.", "↵1. ‘A’ committed an offence against the girl as well as her parents.", "↵2. ‘A’ committed an offence against the girl.", "↵3. ‘A’ committed no offence against the parents of the girl.", "↵4. ‘A’ committed no offence against the girl as well as her parents.", "↵↵↵GENERAL KNOWLEDGE↵↵5.The Hubble telescope of NASA is located in", "↵1. Iceland", "↵2. Canada", "↵3. Space", "↵4. NASA headquarters", "↵↵6.The first Commercial Court and Commercial Disputes Resolution Ce↵ntre was inaugurated at", "↵1. Mumbai, Maharastra", "↵2. Ahmedabad, Gujarat", "↵3. Visakapatinam, Andhra Pradesh", "↵4. Raipur, Chattisgarh", "↵↵7.Among the following who was crowned as ‘Miss Supernational’ duri↵ng 2016?", "↵1. Alia Bhat", "↵2. Aishwarya Rai", "↵3. Shilpa Shetty", "↵4. Srinidhi Shetty", "↵↵8.How many billionaires India has lost since demonetization on Novem↵ber 8, 2016?", "↵1. Eight", "↵2. Two", "↵3. Eleven", "↵4. Eighteen", ""]</p>

Body:
i am trying to read input from a file using explode function.  when i am passing the values to a java-script variable and the appending a div tag with elements of the array i get undefined as out.

<?php

$strings = file_get_contents('questions.txt');
$new_string = explode('
', $strings);
$count = count($new_string);
echo $count;

?>
<!DOCTYPE html>

 <title>TEST</title>

contents from question.txt:
1.Principle: When a person who has made a promise to another perso
n to do something does not fulfill his promise, the other person beco
mes entitled to receive, from the person who did not fulfill his promi
se, compensation in the form of money.
Facts: ‘X’ made a promise to ‘Y’ to repair his car engine. ‘Y’ made the
payment for repair. After the repair, ‘Y’ went for a drive in the same c
ar. While driving the car, ‘Y’ met with an accident due to bursting of a
tyre.

1. ‘X’ will not be entitled to receive compensation.

2. ‘Y’ will not be entitled to receive compensation from ‘X’.

3. ‘Y’ will be entitled to receive compensation from ‘X’ in the form of
money.

4. ‘X’ will be entitled to receive compensation from ‘Y’ in the form of
money.


问:
How to inject new instance of same component in Angular2
[UPDATE] Please read the comment history to understand the context.

All:

I am pretty new to angular2, when I follow its quickstart guide, one question confuses me:

I simplify the app.component.ts as:

```<code>import { Component } from "angular2/core";
@Component({
    selector: "my-app",
    template: "<div>{{title}}</div>"
})
export class AppComponent {
        title = "Tour of Heroes" + Math.random();
}
</code>```

And I add another my-app tag into index.html like:

```<code>  <body>
    <my-app>Loading...</my-app>
    <my-app>Loading...</my-app>
  </body>
</code>```

I wonder why the second one can not get rendered?

Another question related to this is:

If I put two instance of same component, each one will keep their own member variable, but if I inject service into one component, then all component instances share the same service instance, I find the only obvious diff is they use different annotation( other than this, they both export a class): @Component and @Injectable, and one in directives array while the other in providers array. I wonder if these 2 annotation tell angular how can treat the instance or the directives array and providers array do that?

答:
To my knowledge, apart from the main component you can use any other component multiple times in the same html page.

Can achieve this by using @Input decorator
Declare an attribute to your selector element/directive in html and get the value of that attribute in Component by using @Input decorator

import { Component,Input } from "angular2/core";

```<code>@Component({
    selector: "my-app",
    template: "<div>{{title}}</div>"
})
export class AppComponent {
        @Input() title;
}
  <body>
    <my-app title = "somedata1">Loading...</my-app>
    <my-app title = "somedata2">Loading...</my-app>
  </body>
</code>```

Can find an example in this link

Angular2 .. Using the same component to show different data on the same page depending on service response

Body:
[UPDATE] Please read the comment history to understand the context.

All:

I am pretty new to angular2, when I follow its quickstart guide, one question confuses me:

I simplify the app.component.ts as:

import { Component } from "angular2/core";
@Component({
    selector: "my-app",
    template: "
{{title}}
"
})
export class AppComponent {
        title = "Tour of Heroes" + Math.random();
}

And I add another my-app tag into index.html like:

    <my-app>Loading...</my-app>
    <my-app>Loading...</my-app>

I wonder why the second one can not get rendered?

Another question related to this is:

If I put two instance of same component, each one will keep their own member variable, but if I inject service into one component, then all component instances share the same service instance, I find the only obvious diff is they use different annotation( other than this, they both export a class): @Component and @Injectable, and one in directives array while the other in providers array. I wonder if these 2 annotation tell angular how can treat the instance or the directives array and providers array do that?

Body:
To my knowledge, apart from the main component you can use any other component multiple times in the same html page.

Can achieve this by using @Input decorator
Declare an attribute to your selector element/directive in html and get the value of that attribute in Component by using @Input decorator

import { Component,Input } from "angular2/core";

@Component({
    selector: "my-app",
    template: "<div>{{title}}</div>"
})
export class AppComponent {
        @Input() title;
}
  <body>
    <my-app title = "somedata1">Loading...</my-app>
    <my-app title = "somedata2">Loading...</my-app>
  </body>

Can find an example in this link

Angular2 .. Using the same component to show different data on the same page depending on service response


问:
Accessing current controller executing in DelegatingHandler
I was wondering if it's possible to access the controller being executed (or about to be executed) in the SendAsync method of the DelegatingHandler?  I can't seem to figure out how to get access to it, and I figure it's because it executes outside of the controller execution...

Is it possible to refer to it?

答:
Extending the @GalacticBoy solution, it would be better to use </p>

```<code>public class MyHandler : DelegatingHandler
{
    private static IHttpControllerSelector _controllerSelector = null;

    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        if (_controllerSelector == null)
        {
            var config = request.GetConfiguration();
            _controllerSelector = config.Services.GetService(typeof(IHttpControllerSelector)) as IHttpControllerSelector;
        }

        try
        {
            // descriptor here will contain information about the controller to which the request will be routed. If it's null (i.e. controller not found), it will throw an exception
            var descriptor = _controllerSelector.SelectController(request);

        }
        catch
        {
            // controller not found
        }

        // continue
        return base.SendAsync(request, cancellationToken);
    }
}
</code>```

Body:
Extending the @GalacticBoy solution, it would be better to use

public class MyHandler : DelegatingHandler
{
    private static IHttpControllerSelector _controllerSelector = null;

    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        if (_controllerSelector == null)
        {
            var config = request.GetConfiguration();
            _controllerSelector = config.Services.GetService(typeof(IHttpControllerSelector)) as IHttpControllerSelector;
        }

        try
        {
            // descriptor here will contain information about the controller to which the request will be routed. If it's null (i.e. controller not found), it will throw an exception
            var descriptor = _controllerSelector.SelectController(request);

        }
        catch
        {
            // controller not found
        }

        // continue
        return base.SendAsync(request, cancellationToken);
    }
}


问:
How to show the text from edit text input layout to list view?
I am trying to get a text from edit text input layout and show the text on list view when click next edit text drop down button. Like this

答:
Edittext.getText.ToString() will give you the entered text in editText.

And for drop down you should use Spinner.


问:
nightwatch - check for popup window, after each click event
Is there a way in nightwatch to check whether a popup window appears after each click event?

I have a problem that randomly an error message appear and I don't want to write for each click event the same callback function.

I have already tried out the after and afterEach commands in the Global.js but then the commands will only run after the whole test suite.

I also have tried it local within a test file, although it also does not cover all single click events, even though the official website writes "... while beforeEach and afterEach are ran before and after each testcase (test step)"?

Solution I'm looking for:

```<code>.waitForElementVisible('selector')
    .click('selector')
    .click('selector')

</code>```

Solution I have come up with so far:

```<code>.waitForElementVisible('selector')
    .click('selector', isPresent)
    .click('selector', isPresent)
</code>```

isPresent as a callback function, which does the checking and close the popup window if it appears.

Is there another way to write a function (with or without after and/or forEach), so that it will be called after each click event or after each command. Thus, I don't have to write the isPresent repetitive code?

答:
You can insert something like this in your page object file:

```<code>var popupCommand = {
 popupCheck:function(){
return this.waitForElementVisible('selector', 5000)
  .click('selector', isPresent)
  .click('selector', isPresent)

},

module.exports = {
commands:[popupCommand],
elements:{
firstElement: {selector: 'xpath',locateStrategy: 'xpath'},
secondElement: {selector: 'css'},

 }
}
</code>```

Where 'popupCommand' will be the name of your page object file, for example 'Popup'. And also you will have to insert your isPresent callback function here so you can use it.
I did my best to explain you as much as possible what and how to do that :)

ContentLicense: CC BY-SA 4.0

Body:
Is there a way in nightwatch to check whether a popup window appears after each click event?

I have a problem that randomly an error message appear and I don't want to write for each click event the same callback function.

I have already tried out the after and afterEach commands in the Global.js but then the commands will only run after the whole test suite.

I also have tried it local within a test file, although it also does not cover all single click events, even though the official website writes "... while beforeEach and afterEach are ran before and after each testcase (test step)"?

Solution I'm looking for:

.waitForElementVisible('selector')
    .click('selector')
    .click('selector')

Solution I have come up with so far:

.waitForElementVisible('selector')
    .click('selector', isPresent)
    .click('selector', isPresent)

isPresent as a callback function, which does the checking and close the popup window if it appears.

Is there another way to write a function (with or without after and/or forEach), so that it will be called after each click event or after each command. Thus, I don't have to write the isPresent repetitive code?

Body:
You can insert something like this in your page object file:

var popupCommand = {
 popupCheck:function(){
return this.waitForElementVisible('selector', 5000)
  .click('selector', isPresent)
  .click('selector', isPresent)

},

module.exports = {
commands:[popupCommand],
elements:{
firstElement: {selector: 'xpath',locateStrategy: 'xpath'},
secondElement: {selector: 'css'},

 }
}

Where 'popupCommand' will be the name of your page object file, for example 'Popup'. And also you will have to insert your isPresent callback function here so you can use it.
I did my best to explain you as much as possible what and how to do that :)


问:
Angular 4 pass data between 2 not related components
I have a questions about passing data in Angular.

First, I don't have a structure as <parent><child [data]=parent.data></child></parent>

My structure is

```<code><container>
  <navbar>
    <summary></summary>
    <child-summary><child-summary>
  </navbar>
  <content></content>
</container>
</code>```

So, in  I have a select that do send value to <child-summary /> and <content />.

OnSelect method is well fired with (change) inside  component.

So, I tried with @Input, @Output and @EventEmitter directives, but I don't see how retrieve the event as @Input of the component, unless to go on parent/child pattern. All examples I've founded has a relation between component.

EDIT : Example with BehaviorSubject not working (all connected service to API works well, only observable is fired at start but not when select has value changed)

shared service = company.service.ts (used to retrieve company data)

```<code>import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class SrvCompany {

    private accountsNumber = new BehaviorSubject<string[]>([]);
    currentAccountsNumber = this.accountsNumber.asObservable();

    changeMessage(accountsNumber: string[]) {
        this.accountsNumber.next(accountsNumber);
    }

    private _companyUrl = 'api/tiers/';

    constructor(private http: Http) { }

    getSociete(): Promise<Response> {
        let url = this._companyUrl;
        return this.http.get(url).toPromise();
    }
}
</code>```

invoice.component.ts (the "child")

```<code>import { Component, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvInvoice } from './invoice.service';
import { SrvCompany } from '../company/company.service';

@Component({
    selector: 'invoice',
    templateUrl: 'tsScripts/invoice/invoice.html',
    providers: [SrvInvoice, SrvCompany]
})

export class InvoiceComponent implements OnInit  {

    invoice: any;

    constructor(private srvInvoice: SrvInvoice, private srvCompany: SrvCompany)
    {

    }

    ngOnInit(): void {
        //this.getInvoice("F001");

        // Invoice data is linked to accounts number from company.
        this.srvCompany.currentAccountsNumber.subscribe(accountsNumber => {
            console.log(accountsNumber);
            if (accountsNumber.length > 0) {
                this.srvInvoice.getInvoice(accountsNumber).then(data => this.invoice = data.json());
            }
        });
    }

    //getInvoice(id: any) {
    //    this.srvInvoice.getInvoice(id).then(data => this.invoice = data.json());
    //}
}
</code>```

company.component.ts (the trigerring "parent")

```<code>import { Component, Inject, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvCompany } from './company.service';

@Component({
    selector: 'company',
    templateUrl: 'tsScripts/company/company.html',
    providers: [SrvCompany]
})

export class CompanyComponent implements OnInit {

    societes: any[];
    soc: Response[]; // debug purpose
    selectedSociete: any;

    ville: any;
    ref: any;
    cp: any;
    accountNumber: any[];

    constructor(private srvSociete: SrvCompany)
    {

    }

    ngOnInit(): void {
        this.getSocietes();
    }

    getSocietes(): void {

        this.srvSociete.getSociete()
            .then(data => this.societes = data.json())
            .then(data => this.selectItem(this.societes[0].Id));
    }

    selectItem(value: any) {
        this.selectedSociete = this.societes.filter((item: any) => item.Id === value)[0];
        this.cp = this.selectedSociete.CodePostal;
        this.ville = this.selectedSociete.Ville;
        this.ref = this.selectedSociete.Id;
        this.accountNumber = this.selectedSociete.Accounts;
        console.log(this.accountNumber);
        this.srvSociete.changeMessage(this.accountNumber);
    }
}
</code>```

答:
There are two solutions for this.

This can be done through shared service by using observable's.

You can use ngrx/store for this. This is similar to Redux arch. You will be getting data from state.

Body:
I have a questions about passing data in Angular.

First, I don't have a structure as <parent><child [data]=parent.data></child></parent>

My structure is

<container>
  <navbar>

    <child-summary><child-summary>
  </navbar>
  <content></content>
</container>

So, in  I have a select that do send value to <child-summary /> and <content />.

OnSelect method is well fired with (change) inside  component.

So, I tried with @Input, @Output and @EventEmitter directives, but I don't see how retrieve the event as @Input of the component, unless to go on parent/child pattern. All examples I've founded has a relation between component.

EDIT : Example with BehaviorSubject not working (all connected service to API works well, only observable is fired at start but not when select has value changed)

shared service = company.service.ts (used to retrieve company data)

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class SrvCompany {

    private accountsNumber = new BehaviorSubject<string[]>([]);
    currentAccountsNumber = this.accountsNumber.asObservable();

    changeMessage(accountsNumber: string[]) {
        this.accountsNumber.next(accountsNumber);
    }

    private _companyUrl = 'api/tiers/';

    constructor(private http: Http) { }

    getSociete(): Promise<Response> {
        let url = this._companyUrl;
        return this.http.get(url).toPromise();
    }
}

invoice.component.ts (the "child")

import { Component, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvInvoice } from './invoice.service';
import { SrvCompany } from '../company/company.service';

@Component({
    selector: 'invoice',
    templateUrl: 'tsScripts/invoice/invoice.html',
    providers: [SrvInvoice, SrvCompany]
})

export class InvoiceComponent implements OnInit  {

    invoice: any;

    constructor(private srvInvoice: SrvInvoice, private srvCompany: SrvCompany)
    {

    }

    ngOnInit(): void {
        //this.getInvoice("F001");

        // Invoice data is linked to accounts number from company.
        this.srvCompany.currentAccountsNumber.subscribe(accountsNumber => {
            console.log(accountsNumber);
            if (accountsNumber.length > 0) {
                this.srvInvoice.getInvoice(accountsNumber).then(data => this.invoice = data.json());
            }
        });
    }

    //getInvoice(id: any) {
    //    this.srvInvoice.getInvoice(id).then(data => this.invoice = data.json());
    //}
}

company.component.ts (the trigerring "parent")

import { Component, Inject, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvCompany } from './company.service';

@Component({
    selector: 'company',
    templateUrl: 'tsScripts/company/company.html',
    providers: [SrvCompany]
})

export class CompanyComponent implements OnInit {

    societes: any[];
    soc: Response[]; // debug purpose
    selectedSociete: any;

    ville: any;
    ref: any;
    cp: any;
    accountNumber: any[];

    constructor(private srvSociete: SrvCompany)
    {

    }

    ngOnInit(): void {
        this.getSocietes();
    }

    getSocietes(): void {

        this.srvSociete.getSociete()
            .then(data => this.societes = data.json())
            .then(data => this.selectItem(this.societes[0].Id));
    }

    selectItem(value: any) {
        this.selectedSociete = this.societes.filter((item: any) => item.Id === value)[0];
        this.cp = this.selectedSociete.CodePostal;
        this.ville = this.selectedSociete.Ville;
        this.ref = this.selectedSociete.Id;
        this.accountNumber = this.selectedSociete.Accounts;
        console.log(this.accountNumber);
        this.srvSociete.changeMessage(this.accountNumber);
    }
}


问:
C# base class/Interface with a generic method that accepts the derived class as a parameter
I would like to have a method defined on the base class (and in an interface) that accepts a derived class as its parameter.

i.e.

```<code>abstract class Base : IBase
{
    public void CloneMeToProvidedEntity(??? destination) {};
}

public class Derived : Base
{
     public override void CloneMeToProvidedEntity(Derived destination)
     {
         blah blah ....
     }
}
</code>```

I would be eternally grateful if someone can tell me what the Interface would look like and how to do this... or if possible

With Anticipation

Lance

答:
You're probably looking for:

```<code>interface IBase<T>
{
    void CloneMeToProvidedEntity(T destination);
}

public abstract class Base<T> : IBase<T>
{
    public virtual void CloneMeToProvidedEntity(T destination) { }
}

public class Derived : Base<Derived>
{
    public override void CloneMeToProvidedEntity(Derived destination)
    {

    }
}
</code>```

Thanks @Phil

Body:
I would like to have a method defined on the base class (and in an interface) that accepts a derived class as its parameter.

i.e.

abstract class Base : IBase
{
    public void CloneMeToProvidedEntity(??? destination) {};
}

public class Derived : Base
{
     public override void CloneMeToProvidedEntity(Derived destination)
     {
         blah blah ....
     }
}

I would be eternally grateful if someone can tell me what the Interface would look like and how to do this... or if possible

With Anticipation

Lance

Body:
You're probably looking for:

interface IBase<T>
{
    void CloneMeToProvidedEntity(T destination);
}

public abstract class Base<T> : IBase<T>
{
    public virtual void CloneMeToProvidedEntity(T destination) { }
}

public class Derived : Base<Derived>
{
    public override void CloneMeToProvidedEntity(Derived destination)
    {

    }
}

Thanks @Phil


问:
R shiny one code to display graph, table and download data
In shiny, I want to use the same data set to produce and display a graph and a table, and to download the data in the table in csv format.

I start by loading a data table under server with code like

```<code>DTGlobal <- readRDS("bigfile")
</code>```

I shiny selectInput() to set up some user input like the following

```<code>selectInput(inputId = "ScenarioName", label = "xxx", choices = scenarioNames)
</code>```

Currently I create the same scenario-specific dataset in renderTable() and renderPlot() with

```<code>scenarioName <- input$availabilityScenarioName
DTlocal <- data.table::copy(DTGlobal[scenario %in% scenarioName)
add some further manipulations of DTlocal here
</code>```

So far I have done graphs and tables by essentially duplicating code in renderPlot() and renderTable(). I can do the same thing with downloadHandler(). But I was wondering if there was some way to create the data at the server level which I could then access in functions below that. I think I could use newDTGlobal <<- DTlocal in renderPlot() (which is called first) but I think this would make it available to everyone. And if they ran the same renderPlot() that would wipe out my data.

答:
Figuring out how to use the reactive technology did the trick. Here's a code snippet of what I am now doing. It gets variable values from input and generates a data table using that information.

```<code>data.foodAvail <- reactive({
    countryName <- input$availabilityCountryName
    scenarioName <- input$availabilityScenarioName
    dt <- data.table::copy(dt.foodAvail.foodGroup)
    spiderData <- spiderGraphData(countryName, scenarioName, dt, displayColumnName = "food_group_code")
  })
</code>```

The next bit of code shows how I use this (both chunks of code are in the server). The relevant bit of this is data.foodAvail(). This is the value generated above that is specific to the user-chosen input values.

The data.table copy is needed because data.foodAvail() is altered by a data table operation involving := in the spiderGraphData function.

```<code>output$availabilitySpiderGraphP1 <- renderggiraph({
    dt <- data.table::dt <- data.table::copy(data.foodAvail()))
    scenarioName <- unique(dt$scenario)
    dt[, region_code.IMPACT159 := NULL]
    p <- spiderGraphOutput(dt, scenarioName)
    ggiraph(code = print(p), zoom_max = 1, width = .5)
  })
</code>```

Body:
In shiny, I want to use the same data set to produce and display a graph and a table, and to download the data in the table in csv format.

I start by loading a data table under server with code like

DTGlobal <- readRDS("bigfile")

I shiny selectInput() to set up some user input like the following

selectInput(inputId = "ScenarioName", label = "xxx", choices = scenarioNames)

Currently I create the same scenario-specific dataset in renderTable() and renderPlot() with

scenarioName <- input$availabilityScenarioName
DTlocal <- data.table::copy(DTGlobal[scenario %in% scenarioName)
add some further manipulations of DTlocal here

So far I have done graphs and tables by essentially duplicating code in renderPlot() and renderTable(). I can do the same thing with downloadHandler(). But I was wondering if there was some way to create the data at the server level which I could then access in functions below that. I think I could use newDTGlobal <<- DTlocal in renderPlot() (which is called first) but I think this would make it available to everyone. And if they ran the same renderPlot() that would wipe out my data.

Body:
Figuring out how to use the reactive technology did the trick. Here's a code snippet of what I am now doing. It gets variable values from input and generates a data table using that information.

data.foodAvail <- reactive({
    countryName <- input$availabilityCountryName
    scenarioName <- input$availabilityScenarioName
    dt <- data.table::copy(dt.foodAvail.foodGroup)
    spiderData <- spiderGraphData(countryName, scenarioName, dt, displayColumnName = "food_group_code")
  })

The next bit of code shows how I use this (both chunks of code are in the server). The relevant bit of this is data.foodAvail(). This is the value generated above that is specific to the user-chosen input values.

The data.table copy is needed because data.foodAvail() is altered by a data table operation involving := in the spiderGraphData function.

output$availabilitySpiderGraphP1 <- renderggiraph({
    dt <- data.table::dt <- data.table::copy(data.foodAvail()))
    scenarioName <- unique(dt$scenario)
    dt[, region_code.IMPACT159 := NULL]
    p <- spiderGraphOutput(dt, scenarioName)
    ggiraph(code = print(p), zoom_max = 1, width = .5)
  })


问:
Login to application with instagram?
I am try login to application with Instagram, I am using from this LINK but I can login just with my account Instagram and I can't login with others accounts .</p>

答:
you should invite them and they accept you invite!

just you can add 3 people to your application.

follow this link to see more details :
https://www.instagram.com/developer/sandbox/

Title: Login to application with instagram?


问:
How to advance to the next form input when the current input has a value?
I am having a form with lots of entries. I would like to change my focus to the next textbox, once I entered the value in the current textbox. and want to continue this process up to the last field. My question is, is it possible to simulate what happens when pressing the tab key through Javascript coding once I enter the value in the text box.

Without pressing the tab key in keyboard, I would like to bring the same functionality through Javascript. Is this possible?

答:
This simulates a tab through a form and gives focus to the next input when the enter key is pressed.

```<code>window.onkeypress = function(e) {
    if (e.which == 13) {
        e.preventDefault();
        var inputs = document.getElementsByTagName('input');
        for (var i = 0; i < inputs.length; i++) {
        if (document.activeElement.id == inputs[i].id && i+1 < inputs.length ) {
            inputs[i+1].focus();
            break;
        }
    }

</code>```

Updating on the recommendation from @order.

Body:
This simulates a tab through a form and gives focus to the next input when the enter key is pressed.

window.onkeypress = function(e) {
    if (e.which == 13) {
        e.preventDefault();
        var inputs = document.getElementsByTagName('input');
        for (var i = 0; i < inputs.length; i++) {
        if (document.activeElement.id == inputs[i].id && i+1 < inputs.length ) {
            inputs[i+1].focus();
            break;
        }
    }

Updating on the recommendation from @order.


问:
One app with many servers
Let say I have an Angular 2 application. I need to get data from many pages by REST API. I have also node js server which communicates with database. How should I call APIs from Angular 2 app? Should I call APIs directly from Angular 2 app or through node js server? Option 1 is faster but option 2 gives me control what is going to be send to front end. Which option is better?

Option 1:

```<code>    Angular 2 app
    /     \      \
   /       \      ....
node      API 1   API N
server
</code>```

Option 2:

```<code>Angular 2 app
     |
     |
 node server
 /       \
/    ...  \
API 1      API N
</code>```

Regards

答:
Personally I would go with the node server as sort of proxy :)

Reasons:

If you have a backend anyway, you should use it

If something changes i.e. the urls of the apis, you can change it on the server

You have everything in one place

Your frontend is smaller and simpler

You follow a clean MVC-architecture

And lastly but I think it's quite important: You keep track of who, called when which api. This is very useful for security or statistics

Reasons not to do that:

Your backend gets a little bit more complex

You may have a little performance advantage

Title: One app with many servers

Body:
Let say I have an Angular 2 application. I need to get data from many pages by REST API. I have also node js server which communicates with database. How should I call APIs from Angular 2 app? Should I call APIs directly from Angular 2 app or through node js server? Option 1 is faster but option 2 gives me control what is going to be send to front end. Which option is better?

Option 1:

    Angular 2 app
    /     \      \
   /       \      ....
node      API 1   API N
server

Option 2:

Angular 2 app
     |
     |
 node server
 /       \
/    ...  \
API 1      API N

Regards


问:
Converting a System.Windows.Media.Drawing object to Bitmap bytes
I have a System.Windows.Media.Drawing object that I am wanting to convert into a Bitmap object, and then from there extract the bytes that represent the image. I've looked about the internet and I can't seem to find how to do what I need, so any help would be appreciated.

答:
So I finally found a way to convert a System.Windows.Media.Drawing object to a System.Drawing.Bitmap object, and from that get a byte[] object representing the image data. The following is not pretty but does actually work.

public static byte[] DrawingToBytes(Drawing drawing)
{
    DrawingVisual visual = new DrawingVisual();
    using (DrawingContext context = visual.RenderOpen())
    {
        // If using the BitmapEncoder uncomment the following line to get a white background.
        // context.DrawRectangle(Brushes.White, null, drawing.bounds);
        context.DrawDrawing(drawing);
    }

    int width = (int)(drawing.Bounds.Width)
    int height = (int)(drawing.Bounds.Height)
    Bitmap bmp = new Bitmap(width, height);
    Bitmap bmpOut;

    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.Clear(System.Drawing.Color.White);
        RenderTargetBitmap rtBmp = new RenderTargetBitmap(width, height,
                                           bmp.HorizontalResolution,
                                           bmp.VerticalResolution,
                                           PixelFormats.Pbgra32);
        rtBmp.Render(visual);

        // Alternative using BmpBitmapEncoder, use in place of what comes after if you wish.
        // MemoryStream stream = new MemoryStream();
        // BitmapEncoder encoder = new BmpBitmapEncoder();
        // encoder.Frames.Add(BitmapFrame.Create(rtBmp));
        // encoder.save(stream);

        int stride = width * ((rtBmp.Format.BitsPerPixel + 7) / 8);
        byte[] bits = new byte[height * stride];
        bitmapSource.CopyPixels(bits, stride, 0);

        unsafe
        {
            fixed (byte* pBits = bits)
            {
                IntPtr ptr = new IntPtr(pBits);
                bmpOut = new Bitmap(width, height, stride,
                                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb, ptr);
             }
        }

        g.DrawImage(bmpOut, 0, 0, bmp.Width, bmp.Height);
    }

    byte[] bytes;
    using (MemoryStream ms = new MemoryStream())
    {
        bmp.Save(ms, ImageFormat.bmp);
        data = ms.ToArray();
    }

    return bytes;
}
```

So yeah, it's horrible but it actually works.

Body:
So I finally found a way to convert a System.Windows.Media.Drawing object to a System.Drawing.Bitmap object, and from that get a byte[] object representing the image data. The following is not pretty but does actually work.

public static byte[] DrawingToBytes(Drawing drawing)
{
    DrawingVisual visual = new DrawingVisual();
    using (DrawingContext context = visual.RenderOpen())
    {
        // If using the BitmapEncoder uncomment the following line to get a white background.
        // context.DrawRectangle(Brushes.White, null, drawing.bounds);
        context.DrawDrawing(drawing);
    }

    int width = (int)(drawing.Bounds.Width)
    int height = (int)(drawing.Bounds.Height)
    Bitmap bmp = new Bitmap(width, height);
    Bitmap bmpOut;

    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.Clear(System.Drawing.Color.White);
        RenderTargetBitmap rtBmp = new RenderTargetBitmap(width, height,
                                           bmp.HorizontalResolution,
                                           bmp.VerticalResolution,
                                           PixelFormats.Pbgra32);
        rtBmp.Render(visual);

        // Alternative using BmpBitmapEncoder, use in place of what comes after if you wish.
        // MemoryStream stream = new MemoryStream();
        // BitmapEncoder encoder = new BmpBitmapEncoder();
        // encoder.Frames.Add(BitmapFrame.Create(rtBmp));
        // encoder.save(stream);

        int stride = width * ((rtBmp.Format.BitsPerPixel + 7) / 8);
        byte[] bits = new byte[height * stride];
        bitmapSource.CopyPixels(bits, stride, 0);

        unsafe
        {
            fixed (byte* pBits = bits)
            {
                IntPtr ptr = new IntPtr(pBits);
                bmpOut = new Bitmap(width, height, stride,
                                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb, ptr);
             }
        }

        g.DrawImage(bmpOut, 0, 0, bmp.Width, bmp.Height);
    }

    byte[] bytes;
    using (MemoryStream ms = new MemoryStream())
    {
        bmp.Save(ms, ImageFormat.bmp);
        data = ms.ToArray();
    }

    return bytes;
}

So yeah, it's horrible but it actually works.


问:
List combinations in defined range
I am writing parallel rainbow tables generator using parallel python and multiple machines. So far, I have it working on a single machine. It creates all possible passwords, hashes them, saves to file. It takes max_pass_len, file as arguments. Charset is predefined. Here's the code:

```<code>def hashAndSave(listOfComb, fileObject):
    for item in listOfComb:
        hashedVal = crypt(item, 'po')
        fileObject.write("%s:%s\n" % (hashedVal, item))

def gen_rt_save(max_pw_len, file):
    charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

    for i in range(3, max_pw_len):
        lista = [''.join(j) for j in combinations_with_replacement(charset, i)]
        hashAndSave(lista, file)
</code>```

In order to parallelize it I need to split work between several machines. They need to know where start and stop generating passwords.

I figured I need a function which takes two arguments as parameters - start and stop point. Charset is global and has to be fully used in that combinations.

Simplest way would be to pick subset defined by two specific combinations from the list of all possible combinations for given charset and length range. However it takes time and space, and I need to avoid that.

Example:

```<code>charset='abcdefghi' #minified charset, normally 62 characters
ranged_comb(abf,defg)
result -> # it is not combination between to lists! there are specific functions for that, and they would not use full charset, only whats in lists
abf
abg
abh
abi
aca
acb
...
defd
defe
deff
defg
</code>```

I thought about using lists of indexes of charset letters as parameters to use it in for loops. Yet I can't really use fors because their number might vary. How to create such function?

答:
Since for brute-forcing passwords/generating rainbow tables you don't need a strict lexicographic order, as long as you go through all permutations (with repeats), this is quite simple:

```<code>def get_permutation_by_index(source, size, index):
    result = []
    for _ in range(size):
        result.append(source[index % len(source)])
        index = index // len(source)
    return result
</code>```

Then all you need is an index of your permutation to get it from your iterable (strings of characters work, too). What it does is essentially looping through every possible element position for a given size, offset by the passed index, and stores it in the result list. You can use return "".join(result) instead if you're interested in getting a string out of it.

Now your workers can use this function to generate their 'password' range chunks. The simplest way of distribution would be if your workers would receive a single index from a distributor, perform their task and wait for the next index, however, unless your hashing function is excruciatingly slow spawning your workers, data transfer and such might end up slower than executing everything linearly in the main process. That's why you'd ideally want your workers to crunch over larger chunks at a time to justify distributing the whole process. Thus, you'd want your worker to accept a range and do something like:

```<code>def worker(source, size, start, end):
    result = []
    for i in range(start, end):
        result.append(get_permutation_by_index(source, size, i))  # add to the result
    return result
</code>```

Then all you need is a 'distributor' - a central dispatcher that will conduct the workers and split the workload among them. Since our workers don't accept varying sizes (that's an exercise I'll leave for you to figure out, you have all the ingredients) your 'distributor' will need to advance through sizes and keep a track what chunks it sends to your workers. This means that, for smaller and edge chunks, your workers will be receiving lesser workload than defined, but in the grand scheme of things this won't matter much for your use case. So, a simple distributor would look like:

```<code>def distributor(source, start, end, chunk_size=1000):
    result = []
    for size in range(start, end + 1):  # for each size in the given range...
        total = len(source) ** size  # max number of permutations for this size
        for chunk in range(0, total, chunk_size):  # for each chunk...
            data = worker(source, size, chunk, min(chunk + chunk_size, total))  # process...
            result.append(data)  # store the result...
    return result
</code>```

Where start and end represent the number of source elements you want to permute through your workers, and chunk_size represents the number of permutations each worker should process in an ideal case - as I mentioned, this won't be the case if a total number of permutations for a given size is lower than the chunk_size or if there is less unprocessed permutations left for a given size than the chunk_size value, but those are edge cases and I'll leave it for you to figure out how to distribute even more evenly. Also, keep in mind that the returned result will be a list of lists returned from our workers - you'll have to flatten it if you want to treat all the results equally.

But wait, isn't this a linear execution using a single process? Well, of course it is! What we did here is effectively decoupled workers from the distributor so now we can add as many arbitrary levels of separation and/or parallelization in-between without affecting our execution. For example, here's how to make our workers run in parallel:

```<code>from multiprocessing import Pool
import time

def get_permutation_by_index(source, size, index):
    result = []
    for _ in range(size):
        result.append(source[index % len(source)])
        index = index // len(source)
    return result

# let's have our worker perform a naive ascii-shift Caesar cipher
def worker(source, size, start, end):
    result = []
    for i in range(start, end):
        time.sleep(0.2)  # simulate a long operation by adding 200 milliseconds of pause
        permutation = get_permutation_by_index(source, size, i)
        # naive Caesar cipher - simple ascii shift by +4 places
        result.append("".join([chr(ord(x) + 4) for x in permutation]))
    return result

def distributor(source, start, end, workers=10, chunk_size=10):
    pool = Pool(processes=workers)  # initiate our Pool with a specified number of workers
    jobs = set()  # store our worker result references
    for size in range(start, end + 1):  # for each size in the given range...
        total = len(source) ** size  # max number of permutations for this size
        for chunk in range(0, total, chunk_size):  # for each chunk...
            # add a call to the worker to our Pool
            r = pool.apply_async(worker,
                                 (source, size, chunk, min(chunk + chunk_size, total)))
            jobs.add(r)  # add our ApplyResult in the jobs set for a later checkup
    result = []
    while jobs:  # loop as long as we're waiting for results...
        for job in jobs:
            if job.ready():  # current worker finished processing...
                result.append(job.get())  # store our result...
                jobs.remove(job)
                break
        time.sleep(0.05)  # let other threads get a chance to breathe a little...
    return result  # keep in mind that this is NOT an ordered result

if __name__ == "__main__":  # important protection for cross-platform use

    # call 6 threaded workers to sift through all 2 and 3-letter permutations
    # of "abcd", using the default chunk size ('ciphers per worker') of 10
    caesar_permutations = distributor("abcd", 2, 3, 6)

    print([perm for x in caesar_permutations for perm in x])  # print flattened results

# ['gg', 'hg', 'eh', 'fh', 'gh', 'hh', 'eff', 'fff', 'gff', 'hff', 'egf', 'fgf', 'ggf',
#  'hgf', 'ehf', 'fhf', 'ghf', 'hhf', 'eeg', 'feg', 'geg', 'heg', 'efg', 'ffg', 'gfg',
#  'hfg', 'eee', 'fee', 'gee', 'hee', 'efe', 'ffe', 'gfe', 'hfe', 'ege', 'fge', 'ee',
#  'fe', 'ge', 'he', 'ef', 'ff', 'gf', 'hf', 'eg', 'fg', 'gge', 'hge', 'ehe', 'fhe',
#  'ghe', 'hhe', 'eef', 'fef', 'gef', 'hef', 'ehh', 'fhh', 'ghh', 'hhh', 'egg', 'fgg',
#  'ggg', 'hgg', 'ehg', 'fhg', 'ghg', 'hhg', 'eeh', 'feh', 'geh', 'heh', 'efh', 'ffh',
#  'gfh', 'hfh', 'egh', 'fgh', 'ggh', 'hgh']
</code>```

Voila! Everything executed in parallel (and over multiple cores if the underlying OS did its scheduling properly). This should be sufficient for your use case - all you need is to add your communication or I/O code in the worker function and let the actual code be executed by a receiver on the other side, then when you get the results return them back to the distributor. You can also directly write your tables in the distributor() instead of waiting for everything to finish.

And if you're going to execute this exclusively over a network, you don't really need it in a multiprocess setting, threads would be sufficient to handle the I/O latency, so just replace the multiprocess import with: from multiprocessing.pool import ThreadPool as Pool (don't let the module name fool you, this is a threading interface, not a multiprocessing one!).

Title: List combinations in defined range

Body:
I am writing parallel rainbow tables generator using parallel python and multiple machines. So far, I have it working on a single machine. It creates all possible passwords, hashes them, saves to file. It takes max_pass_len, file as arguments. Charset is predefined. Here's the code:

def hashAndSave(listOfComb, fileObject):
    for item in listOfComb:
        hashedVal = crypt(item, 'po')
        fileObject.write("%s:%s\n" % (hashedVal, item))

def gen_rt_save(max_pw_len, file):
    charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

    for i in range(3, max_pw_len):
        lista = [''.join(j) for j in combinations_with_replacement(charset, i)]
        hashAndSave(lista, file)

In order to parallelize it I need to split work between several machines. They need to know where start and stop generating passwords.

I figured I need a function which takes two arguments as parameters - start and stop point. Charset is global and has to be fully used in that combinations.

Simplest way would be to pick subset defined by two specific combinations from the list of all possible combinations for given charset and length range. However it takes time and space, and I need to avoid that.

Example:

charset='abcdefghi' #minified charset, normally 62 characters
ranged_comb(abf,defg)
result -> # it is not combination between to lists! there are specific functions for that, and they would not use full charset, only whats in lists
abf
abg
abh
abi
aca
acb
...
defd
defe
deff
defg

I thought about using lists of indexes of charset letters as parameters to use it in for loops. Yet I can't really use fors because their number might vary. How to create such function?

Body:
Since for brute-forcing passwords/generating rainbow tables you don't need a strict lexicographic order, as long as you go through all permutations (with repeats), this is quite simple:

def get_permutation_by_index(source, size, index):
    result = []
    for _ in range(size):
        result.append(source[index % len(source)])
        index = index // len(source)
    return result

Then all you need is an index of your permutation to get it from your iterable (strings of characters work, too). What it does is essentially looping through every possible element position for a given size, offset by the passed index, and stores it in the result list. You can use return "".join(result) instead if you're interested in getting a string out of it.

Now your workers can use this function to generate their 'password' range chunks. The simplest way of distribution would be if your workers would receive a single index from a distributor, perform their task and wait for the next index, however, unless your hashing function is excruciatingly slow spawning your workers, data transfer and such might end up slower than executing everything linearly in the main process. That's why you'd ideally want your workers to crunch over larger chunks at a time to justify distributing the whole process. Thus, you'd want your worker to accept a range and do something like:

def worker(source, size, start, end):
    result = []
    for i in range(start, end):
        result.append(get_permutation_by_index(source, size, i))  # add to the result
    return result

Then all you need is a 'distributor' - a central dispatcher that will conduct the workers and split the workload among them. Since our workers don't accept varying sizes (that's an exercise I'll leave for you to figure out, you have all the ingredients) your 'distributor' will need to advance through sizes and keep a track what chunks it sends to your workers. This means that, for smaller and edge chunks, your workers will be receiving lesser workload than defined, but in the grand scheme of things this won't matter much for your use case. So, a simple distributor would look like:

def distributor(source, start, end, chunk_size=1000):
    result = []
    for size in range(start, end + 1):  # for each size in the given range...
        total = len(source) ** size  # max number of permutations for this size
        for chunk in range(0, total, chunk_size):  # for each chunk...
            data = worker(source, size, chunk, min(chunk + chunk_size, total))  # process...
            result.append(data)  # store the result...
    return result

Where start and end represent the number of source elements you want to permute through your workers, and chunk_size represents the number of permutations each worker should process in an ideal case - as I mentioned, this won't be the case if a total number of permutations for a given size is lower than the chunk_size or if there is less unprocessed permutations left for a given size than the chunk_size value, but those are edge cases and I'll leave it for you to figure out how to distribute even more evenly. Also, keep in mind that the returned result will be a list of lists returned from our workers - you'll have to flatten it if you want to treat all the results equally.

But wait, isn't this a linear execution using a single process? Well, of course it is! What we did here is effectively decoupled workers from the distributor so now we can add as many arbitrary levels of separation and/or parallelization in-between without affecting our execution. For example, here's how to make our workers run in parallel:

from multiprocessing import Pool
import time

def get_permutation_by_index(source, size, index):
    result = []
    for _ in range(size):
        result.append(source[index % len(source)])
        index = index // len(source)
    return result

# let's have our worker perform a naive ascii-shift Caesar cipher
def worker(source, size, start, end):
    result = []
    for i in range(start, end):
        time.sleep(0.2)  # simulate a long operation by adding 200 milliseconds of pause
        permutation = get_permutation_by_index(source, size, i)
        # naive Caesar cipher - simple ascii shift by +4 places
        result.append("".join([chr(ord(x) + 4) for x in permutation]))
    return result

def distributor(source, start, end, workers=10, chunk_size=10):
    pool = Pool(processes=workers)  # initiate our Pool with a specified number of workers
    jobs = set()  # store our worker result references
    for size in range(start, end + 1):  # for each size in the given range...
        total = len(source) ** size  # max number of permutations for this size
        for chunk in range(0, total, chunk_size):  # for each chunk...
            # add a call to the worker to our Pool
            r = pool.apply_async(worker,
                                 (source, size, chunk, min(chunk + chunk_size, total)))
            jobs.add(r)  # add our ApplyResult in the jobs set for a later checkup
    result = []
    while jobs:  # loop as long as we're waiting for results...
        for job in jobs:
            if job.ready():  # current worker finished processing...
                result.append(job.get())  # store our result...
                jobs.remove(job)
                break
        time.sleep(0.05)  # let other threads get a chance to breathe a little...
    return result  # keep in mind that this is NOT an ordered result

if __name__ == "__main__":  # important protection for cross-platform use

    # call 6 threaded workers to sift through all 2 and 3-letter permutations
    # of "abcd", using the default chunk size ('ciphers per worker') of 10
    caesar_permutations = distributor("abcd", 2, 3, 6)

    print([perm for x in caesar_permutations for perm in x])  # print flattened results

# ['gg', 'hg', 'eh', 'fh', 'gh', 'hh', 'eff', 'fff', 'gff', 'hff', 'egf', 'fgf', 'ggf',
#  'hgf', 'ehf', 'fhf', 'ghf', 'hhf', 'eeg', 'feg', 'geg', 'heg', 'efg', 'ffg', 'gfg',
#  'hfg', 'eee', 'fee', 'gee', 'hee', 'efe', 'ffe', 'gfe', 'hfe', 'ege', 'fge', 'ee',
#  'fe', 'ge', 'he', 'ef', 'ff', 'gf', 'hf', 'eg', 'fg', 'gge', 'hge', 'ehe', 'fhe',
#  'ghe', 'hhe', 'eef', 'fef', 'gef', 'hef', 'ehh', 'fhh', 'ghh', 'hhh', 'egg', 'fgg',
#  'ggg', 'hgg', 'ehg', 'fhg', 'ghg', 'hhg', 'eeh', 'feh', 'geh', 'heh', 'efh', 'ffh',
#  'gfh', 'hfh', 'egh', 'fgh', 'ggh', 'hgh']

Voila! Everything executed in parallel (and over multiple cores if the underlying OS did its scheduling properly). This should be sufficient for your use case - all you need is to add your communication or I/O code in the worker function and let the actual code be executed by a receiver on the other side, then when you get the results return them back to the distributor. You can also directly write your tables in the distributor() instead of waiting for everything to finish.

And if you're going to execute this exclusively over a network, you don't really need it in a multiprocess setting, threads would be sufficient to handle the I/O latency, so just replace the multiprocess import with: from multiprocessing.pool import ThreadPool as Pool (don't let the module name fool you, this is a threading interface, not a multiprocessing one!).


问:
BroadcastReceiver dies with app
If i let the phone sit for a long time like 15 minutes i lose my receiver but i thought it was to persist like a service after being killed for memory.

Manifest:

```<code><receiver
    android:name=".WearableReceiver"
    android:enabled="false">
    <intent-filter>
        <action android:name="com.example.johnbravado.MESSAGE_PROCESSED"/>
    </intent-filter>
</receiver>
</code>```

In Activity to start receiver

```<code>ComponentName component = new ComponentName(CounterActivity.this, WearableReceiver.class);
getPackageManager()
    .setComponentEnabledSetting(component,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP);
</code>```

The receiver

```<code>@Override
public void onReceive(Context context, Intent intent) {
    // TODO: This method is called when the BroadcastReceiver is receiving
    // an Intent broadcast.
    //MyConstants.getInstance().showToast("Message Rcvd");
    PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "com.example.johnbravado");
    wakeLock.acquire();
    // Do Work
    MyConstants.getInstance().msgReqAction(intent.getIntExtra(MyConstants.BROADCAST_DATA_REQ, 0));

    wakeLock.release();
}
</code>```

The broadcast sender

```<code>String BROADCAST_ACTION_RESP = "com.example.johnbravado.MESSAGE_PROCESSED"
@Override
public void onMessageReceived(final MessageEvent messageEvent) {
    nodeId = messageEvent.getSourceNodeId();
    String incomingPath = messageEvent.getPath();
    int incomingReq = Integer.parseInt(new String(messageEvent.getData()));

    if(incomingPath.equalsIgnoreCase(MyConstants.MSG_COUNTER_REQ_PATH)) {
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(BROADCAST_ACTION_RESP);
        broadcastIntent.putExtra(MyConstants.BROADCAST_DATA_REQ, incomingReq);
        sendBroadcast(broadcastIntent);

    }else if(incomingPath.equalsIgnoreCase(MyConstants.MSG_DEFAULT_PATH)){

    }
}
</code>```

only way I get this to persist for long periods of time is to invoke a service

```<code>wearableReceiverIntent = new Intent(this, WearableReceiverService.class);
if(!WearableReceiverService.isRunning())
    startService(wearableReceiverIntent);
</code>```

the service

```<code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Let it continue running until it is stopped.
    IntentFilter filter = new IntentFilter(MyConstants.BROADCAST_ACTION_RESP);
    filter.addCategory(Intent.CATEGORY_DEFAULT);
    receiver = new WearableReceiver();
    registerReceiver(receiver, filter);

Notification notification = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_notif_bible)
        .setContentText("Preaching").build();
startForeground(MyConstants.NOTIF_COUNTING_SERVICE, notification);

    isRunning = true;
    return START_STICKY;
}
</code>```

If I run the service it persists for long periods of time but it drains the battery unnecessarily considering I interact only once every 10 minutes. I was under impression Broadcast receiver would work like service except for short bursts of work. invoke the service if you need to do long actions.

答:
I had the same problem due on my Asus ZenPad due to the Asus Mobile Manager app, specifically the "Auto start manager" was blocking the intent to my app.

Deactivating the app (uninstall is not possible) worth nothing, the solution has been to leave the app installed but whitelist my developing app so it can receive broadcast like PACKAGE_REPLACE. (Pay attention that the switches are confusing, you actually have to touch on "blocked" so it turns on into "allowed" to enable it.

I think another option is to update or change the ROM (choosing one without all that bloatware).

Title: BroadcastReceiver dies with app

Body:
If i let the phone sit for a long time like 15 minutes i lose my receiver but i thought it was to persist like a service after being killed for memory.

Manifest:

<receiver
    android:name=".WearableReceiver"
    android:enabled="false">
    <intent-filter>
        <action android:name="com.example.johnbravado.MESSAGE_PROCESSED"/>
    </intent-filter>
</receiver>

In Activity to start receiver

ComponentName component = new ComponentName(CounterActivity.this, WearableReceiver.class);
getPackageManager()
    .setComponentEnabledSetting(component,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP);

The receiver

@Override
public void onReceive(Context context, Intent intent) {
    // TODO: This method is called when the BroadcastReceiver is receiving
    // an Intent broadcast.
    //MyConstants.getInstance().showToast("Message Rcvd");
    PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "com.example.johnbravado");
    wakeLock.acquire();
    // Do Work
    MyConstants.getInstance().msgReqAction(intent.getIntExtra(MyConstants.BROADCAST_DATA_REQ, 0));

    wakeLock.release();
}

The broadcast sender

String BROADCAST_ACTION_RESP = "com.example.johnbravado.MESSAGE_PROCESSED"
@Override
public void onMessageReceived(final MessageEvent messageEvent) {
    nodeId = messageEvent.getSourceNodeId();
    String incomingPath = messageEvent.getPath();
    int incomingReq = Integer.parseInt(new String(messageEvent.getData()));

    if(incomingPath.equalsIgnoreCase(MyConstants.MSG_COUNTER_REQ_PATH)) {
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(BROADCAST_ACTION_RESP);
        broadcastIntent.putExtra(MyConstants.BROADCAST_DATA_REQ, incomingReq);
        sendBroadcast(broadcastIntent);

    }else if(incomingPath.equalsIgnoreCase(MyConstants.MSG_DEFAULT_PATH)){

    }
}

only way I get this to persist for long periods of time is to invoke a service

wearableReceiverIntent = new Intent(this, WearableReceiverService.class);
if(!WearableReceiverService.isRunning())
    startService(wearableReceiverIntent);

the service

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Let it continue running until it is stopped.
    IntentFilter filter = new IntentFilter(MyConstants.BROADCAST_ACTION_RESP);
    filter.addCategory(Intent.CATEGORY_DEFAULT);
    receiver = new WearableReceiver();
    registerReceiver(receiver, filter);

Notification notification = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_notif_bible)
        .setContentText("Preaching").build();
startForeground(MyConstants.NOTIF_COUNTING_SERVICE, notification);

    isRunning = true;
    return START_STICKY;
}

If I run the service it persists for long periods of time but it drains the battery unnecessarily considering I interact only once every 10 minutes. I was under impression Broadcast receiver would work like service except for short bursts of work. invoke the service if you need to do long actions.


问:
Trying to make a countdown with a twist
I'm trying to make a countdown timer like little script. I want it to look like this:

```<code>0 years left until your event.
0 months left until your event.
10 days left until your event.
234 hours left until your event.
14020 minutes left until your event.
841166 seconds left until your event.
</code>```

As you can see it's not a "normal" countdown. I want it to be like this, total amount of seconds, total amount of minutes left etc. Now I'm running into trouble trying to make it actually count-down. Just the seconds are working fine, I'm using this piece of code for that:

```<code>def secondsLeft(eventDate):
    while secondsUntil:
        toPrint = "%s seconds left until your event." %(secondsUntil)
        print(toPrint, end='\r')
        time.sleep(1)
        secondsUntil -= 1
</code>```

However, when trying to do the same for the minutes, replacing with time.sleep(60) it's not printing out the seconds anymore!

I think it has to do with the while loop. However, I don't know what to do about it... Any help in the right direction is appreciated!!

答: If you wait a minute the whole program will be stopped for a minute. It can't decrease the seconds. What you want to do is, keep waiting only a second per while interation and add this line mins, secs = divmod(secondsUntil, 60). You can print mins for the minutesUntil

Title: Trying to make a countdown with a twist

Body:
I'm trying to make a countdown timer like little script. I want it to look like this:

0 years left until your event.
0 months left until your event.
10 days left until your event.
234 hours left until your event.
14020 minutes left until your event.
841166 seconds left until your event.

As you can see it's not a "normal" countdown. I want it to be like this, total amount of seconds, total amount of minutes left etc. Now I'm running into trouble trying to make it actually count-down. Just the seconds are working fine, I'm using this piece of code for that:

def secondsLeft(eventDate):
    while secondsUntil:
        toPrint = "%s seconds left until your event." %(secondsUntil)
        print(toPrint, end='\r')
        time.sleep(1)
        secondsUntil -= 1

However, when trying to do the same for the minutes, replacing with time.sleep(60) it's not printing out the seconds anymore!

I think it has to do with the while loop. However, I don't know what to do about it... Any help in the right direction is appreciated!!


问:
highcharter hcaes "group" usage while plotting large amounts of data with highchart2()
I am trying to plot large datasets in scatterplots using highcharter package (> 50k rows of data), after some reading I found out that the highchart2() function includes the boost module from highcharts which should improve the performance a lot when plotting large amounts of data. Take the following example:

```<code>library(highcharter) # I'm using the latest version from github (0.5.0.9999)

x <- data.frame(a = rnorm(5000),
                b = rnorm(5000),
                cat = c(rep("Yes", 2500), rep("No",2500)))

highchart() %>%
  hc_add_series(data = x, type = "scatter", hcaes(x=a, y=b, group=cat))
</code>```

This should correctly create a scatterplot but with already some performance issues due to the amount of data. This is why I switched to highchart2() but to my surprise the plot does not show any data points when trying:

```<code>highchart2() %>%
  hc_add_series(data = x, type = "scatter", hcaes(x=a, y=b, group=cat))
</code>```

And after some more searching and reading I found out that when using list_parse2() the plot is rendered much faster, so I tried this:

```<code>highchart2() %>%
  hc_add_series(data = list_parse2(x), type = "scatter", hcaes(x=a, y=b, group=cat))
</code>```

And of course it doesnt work, because I changed the structure of the input data, and stripped the names of the variables I was giving to hcaes(). Then, when I tried this:

```<code>highchart2() %>%
  hc_add_series(data = list_parse2(x), type = "scatter")
</code>```

I got a very fast rendered plot, BUT I cannot get the grouping working that will differentiate between "Yes" and "No" at each point, so all points are now the same color.

So my question would be, how can I efficiently plot large datasets with highcharter while keeping the ability to assign a variable to the "group" parameter in hcaes()?

Thanks in advance for your help.

答:
A mini disclaimer: The hcaes work only if the data object is a data.frame.

Now, you can use dplyr, to get a data frame of series using the group_by function and then use the auxiliar function hc_add_series_listto add simultaniously more than one series.

```<code>library(highcharter)  # I'm using the latest version from github (0.5.0.9999)

x <- data.frame(a = rnorm(5000), b = rnorm(5000), cat = c(rep("Yes", 2500),
  rep("No", 2500)))

library(dplyr)

xseries <- x %>%
  # use `name` to name  series according the value of `cat` avariable
  group_by(name = cat) %>%
  do(data = list_parse2(.)) %>%
  # add type of series
  mutate(type = "scatter")

# A data frame of series
xseries
#> Source: local data frame [2 x 3]
#> Groups: <by row>
#>
#> # A tibble: 2 x 3
#>     name           data    type
#>   <fctr>         <list>   <chr>
#> 1     No <list [2,500]> scatter
#> 2    Yes <list [2,500]> scatter
</code>```

And finally:

```<code>highchart2() %>%
  hc_add_series_list(xseries)
</code>```

Body:
I am trying to plot large datasets in scatterplots using highcharter package (> 50k rows of data), after some reading I found out that the highchart2() function includes the boost module from highcharts which should improve the performance a lot when plotting large amounts of data. Take the following example:

library(highcharter) # I'm using the latest version from github (0.5.0.9999)

x <- data.frame(a = rnorm(5000),
                b = rnorm(5000),
                cat = c(rep("Yes", 2500), rep("No",2500)))

highchart() %>%
  hc_add_series(data = x, type = "scatter", hcaes(x=a, y=b, group=cat))

This should correctly create a scatterplot but with already some performance issues due to the amount of data. This is why I switched to highchart2() but to my surprise the plot does not show any data points when trying:

highchart2() %>%
  hc_add_series(data = x, type = "scatter", hcaes(x=a, y=b, group=cat))

And after some more searching and reading I found out that when using list_parse2() the plot is rendered much faster, so I tried this:

highchart2() %>%
  hc_add_series(data = list_parse2(x), type = "scatter", hcaes(x=a, y=b, group=cat))

And of course it doesnt work, because I changed the structure of the input data, and stripped the names of the variables I was giving to hcaes(). Then, when I tried this:

highchart2() %>%
  hc_add_series(data = list_parse2(x), type = "scatter")

I got a very fast rendered plot, BUT I cannot get the grouping working that will differentiate between "Yes" and "No" at each point, so all points are now the same color.

So my question would be, how can I efficiently plot large datasets with highcharter while keeping the ability to assign a variable to the "group" parameter in hcaes()?

Thanks in advance for your help.

Body:
A mini disclaimer: The hcaes work only if the data object is a data.frame.

Now, you can use dplyr, to get a data frame of series using the group_by function and then use the auxiliar function hc_add_series_listto add simultaniously more than one series.

library(highcharter)  # I'm using the latest version from github (0.5.0.9999)

x <- data.frame(a = rnorm(5000), b = rnorm(5000), cat = c(rep("Yes", 2500),
  rep("No", 2500)))

library(dplyr)

xseries <- x %>%
  # use `name` to name  series according the value of `cat` avariable
  group_by(name = cat) %>%
  do(data = list_parse2(.)) %>%
  # add type of series
  mutate(type = "scatter")

# A data frame of series
xseries
#> Source: local data frame [2 x 3]
#> Groups: <by row>
#>
#> # A tibble: 2 x 3
#>     name           data    type
#>   <fctr>         <list>   <chr>
#> 1     No <list [2,500]> scatter
#> 2    Yes <list [2,500]> scatter

And finally:

highchart2() %>%
  hc_add_series_list(xseries)