问:
How to access props from useEffect hook in Reactjs
I am fetching data from a news API and storing it in my state upon completion, then also passing the value of the state as props to a child component.

The data returned by the API is an array of objects. I only want to pass one element (object) of that array(which is now in my state) to my child component. So, I did just that by using the arrays conventional traversal method ([]) to pass one element, but unfortunately, when I tried using the useEffect hook in my child component to console log the props (which worked ), I was unable to access the properties of my element (object) from neither the hook nor from the body of the component as it kept on telling me that its undefined and that I have to cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. So I tried passing that one element as an array using the splice method in order to be traversed from the child component using the map method (which worked), however, I was still unable to access the properties from the useEffect hook.

Parent Component (Home.js)

```<code> ...
const [data, setData]= useState([])
 useEffect(()=>{

        const fetch= async()=>{
            const response= await axios(url)
            const results= response.data
            setData(results.articles.slice(0,5))
        }
        fetch()

    },[url])

return(
    <>
    <Categories onClick={fetchCategory}/>
    <section className={classes.latest}>
    <Vertical postArray={data.slice(0,1)} postObject={data[0]}/>
    </section>
    </>
)
}

export default Home
</code>```

Child component (Vertical.js)

```<code>const Vertical=(props)=>{

useEffect(() => {
    // console.log('postArray',props.postArray.title)
    console.log('postObject',props.postObject.title)

}, )

return(
    <>
    {/* <article key={props.postObject.content} className={classes.article}>
        <figure className={classes.article_figure}>
            <img src='' alt="article alternative"/>
        </figure>
        <div className={classes.article_details}>
            <h2>{props.postObject.title}</h2>
            <p>{props.postObject.description}</p>

        </div>
    </article> */}
    {props.postArray.map(post=>(
        <article key={post.content} className={classes.article}>
        <figure className={classes.article_figure}>
            <img src='' alt="article alternative"/>
        </figure>
        <div className={classes.article_details}>
            <h2>{post.title}</h2>
            <p>{post.description}</p>

        </div>
    </article>
    ))}
    </>
)
}

export default Vertical
</code>```

The reason for this is that I need to access an URL which is inside the passed object in order to make another to fetch the thumbnail for that post.

答:
you need to give dependencies to the useEffect, for it to watch and console

```<code>useEffect(() => {
    // console.log('postArray',props.postArray.title)
    console.log('postObject',props.postObject.title)

},[props.postObject.title]) //this will ensure that this prop is watched for changes
</code>```

Edit: for all those with undefined errors you can do the following change in the dependency

```<code>useEffect(() => {
        // console.log('postArray',props.postArray.title)
        console.log('postObject',props?.postObject?.title) // optional-chaining would take care of the undefined check

    },[props?.postObject?.title]) // optional-chaining would take care of the undefined check
</code>```

Body:
I am fetching data from a news API and storing it in my state upon completion, then also passing the value of the state as props to a child component.

The data returned by the API is an array of objects. I only want to pass one element (object) of that array(which is now in my state) to my child component. So, I did just that by using the arrays conventional traversal method ([]) to pass one element, but unfortunately, when I tried using the useEffect hook in my child component to console log the props (which worked ), I was unable to access the properties of my element (object) from neither the hook nor from the body of the component as it kept on telling me that its undefined and that I have to cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. So I tried passing that one element as an array using the splice method in order to be traversed from the child component using the map method (which worked), however, I was still unable to access the properties from the useEffect hook.

Parent Component (Home.js)

 ...
const [data, setData]= useState([])
 useEffect(()=>{

        const fetch= async()=>{
            const response= await axios(url)
            const results= response.data
            setData(results.articles.slice(0,5))
        }
        fetch()

    },[url])

return(
    <>
    <Categories onClick={fetchCategory}/>

    <Vertical postArray={data.slice(0,1)} postObject={data[0]}/>

    </>
)
}

export default Home

Child component (Vertical.js)

const Vertical=(props)=>{

useEffect(() => {
    // console.log('postArray',props.postArray.title)
    console.log('postObject',props.postObject.title)

}, )

return(
    <>
    {/*

{props.postObject.title}

{props.postObject.description}

 */}
    {props.postArray.map(post=>(

{post.title}

{post.description}

    ))}
    </>
)
}

export default Vertical

The reason for this is that I need to access an URL which is inside the passed object in order to make another to fetch the thumbnail for that post.

Body:
you need to give dependencies to the useEffect, for it to watch and console

useEffect(() => {
    // console.log('postArray',props.postArray.title)
    console.log('postObject',props.postObject.title)

},[props.postObject.title]) //this will ensure that this prop is watched for changes

Edit: for all those with undefined errors you can do the following change in the dependency

useEffect(() => {
        // console.log('postArray',props.postArray.title)
        console.log('postObject',props?.postObject?.title) // optional-chaining would take care of the undefined check

    },[props?.postObject?.title]) // optional-chaining would take care of the undefined check


来源: stackexchange

答: The trace.nam file in UnetSim currently only logs PHY frames. If you are analyzing higher layer protocols, this may not be the ideal log file to work from. It is perhaps better that you log your packets to log-0.txt in your agent using log.info() and use that for your analysis instead.

ContentLicense: CC BY-SA 4.0

Title: Tracing packets from source to destination for multi-hop communication using trace.nam in unetstack

Body:
We implemented multi-hop routing protocol for underwater communication. Now we want to evaluate the performance of that routing protocol using parameters like- end to end delay, hop-count etc. We analyzed trace.nam to trace the packets from source to destination. Once a packet is originated from source, forwarded to next hop like that it will reach destination after multiple forwarding. But the problem is packet id at each forwarding node is changes. Due to this difficult to trace the packet and collect statistics (suppose 100 packet sent).

Not finding common parameter value in trace file to trace packets.

# BEGIN SIMULATION 1
n -t 1559191523.506000 -s 1 -x 0.000000 -y 0.000000 -Z 0.000000 -a 1
+ -t 1559191523.510000 -s 1 -d 0 -i 250111054 -p 0 -x {1.0 0.4 -1 ------- null}
n -t 1559191523.511000 -s 2 -x 0.000000 -y 0.000000 -Z -35.000000 -a 2
n -t 1559191523.513000 -s 3 -x 0.000000 -y 0.000000 -Z -75.000000 -a 3
n -t 1559191523.514000 -s 5 -x 0.000000 -y 99.000000 -Z -118.000000 -a 5
n -t 1559191523.514000 -s 4 -x 0.000000 -y 0.000000 -Z -120.000000 -a 4
- -t 1559191523.564000 -s 1 -d 0 -i 250111054 -p 0 -x {1.0 0.4 -1 ------- null}
r -t 1559191523.958000 -s 1 -d 2 -i 250111054 -p 0 -x {1.0 0.4 -1 ------- null}
r -t 1559191523.969000 -s 1 -d 3 -i 250111054 -p 0 -x {1.0 0.4 -1 ------- null}
d -t 1559191524.005000 -s 1 -d 4 -i 250111054 -p 0 -x {1.0 0.4 -1 ------- null} -y BAD_FRAME
d -t 1559191524.021000 -s 1 -d 5 -i 250111054 -p 0 -x {1.0 0.4 -1 ------- null} -y BAD_FRAME
+ -t 1559191550.251000 -s 2 -d 0 -i 270543411 -p 0 -x {2.0 0.4 -1 ------- null}
- -t 1559191550.302000 -s 2 -d 0 -i 270543411 -p 0 -x {2.0 0.4 -1 ------- null}
r -t 1559191550.678000 -s 2 -d 1 -i 270543411 -p 0 -x {2.0 0.4 -1 ------- null}
r -t 1559191550.683000 -s 2 -d 3 -i 270543411 -p 0 -x {2.0 0.4 -1 ------- null}
r -t 1559191550.713000 -s 2 -d 4 -i 270543411 -p 0 -x {2.0 0.4 -1 ------- null}
d -t 1559191550.742000 -s 2 -d 5 -i 270543411 -p 0 -x {2.0 0.4 -1 ------- null} -y BAD_FRAME
+ -t 1559191551.741000 -s 3 -d 0 -i 236268410 -p 0 -x {3.0 0.4 -1 ------- null}
- -t 1559191551.792000 -s 3 -d 0 -i 236268410 -p 0 -x {3.0 0.4 -1 ------- null}
r -t 1559191552.174000 -s 3 -d 2 -i 236268410 -p 0 -x {3.0 0.4 -1 ------- null}
r -t 1559191552.178000 -s 3 -d 4 -i 236268410 -p 0 -x {3.0 0.4 -1 ------- null}
r -t 1559191552.196000 -s 3 -d 1 -i 236268410 -p 0 -x {3.0 0.4 -1 ------- null}
d -t 1559191552.220000 -s 3 -d 5 -i 236268410 -p 0 -x {3.0 0.4 -1 ------- null} -y BAD_FRAME
+ -t 1559191586.676000 -s 4 -d 0 -i -694431325 -p 0 -x {4.0 0.4 -1 ------- null}
- -t 1559191586.728000 -s 4 -d 0 -i -694431325 -p 0 -x {4.0 0.4 -1 ------- null}
r -t 1559191587.112000 -s 4 -d 3 -i -694431325 -p 0 -x {4.0 0.4 -1 ------- null}
r -t 1559191587.139000 -s 4 -d 2 -i -694431325 -p 0 -x {4.0 0.4 -1 ------- null}
r -t 1559191587.149000 -s 4 -d 5 -i -694431325 -p 0 -x {4.0 0.4 -1 ------- null}
d -t 1559191587.161000 -s 4 -d 1 -i -694431325 -p 0 -x {4.0 0.4 -1 ------- null} -y BAD_FRAME
+ -t 1559191626.953000 -s 5 -d 0 -i -1642203870 -p 0 -x {5.0 0.4 -1 ------- null}
- -t 1559191627.005000 -s 5 -d 0 -i -1642203870 -p 0 -x {5.0 0.4 -1 ------- null}
r -t 1559191627.425000 -s 5 -d 4 -i -1642203870 -p 0 -x {5.0 0.4 -1 ------- null}
d -t 1559191627.430000 -s 5 -d 3 -i -1642203870 -p 0 -x {5.0 0.4 -1 ------- null} -y BAD_FRAME
d -t 1559191627.446000 -s 5 -d 2 -i -1642203870 -p 0 -x {5.0 0.4 -1 ------- null} -y BAD_FRAME
d -t 1559191627.462000 -s 5 -d 1 -i -1642203870 -p 0 -x {5.0 0.4 -1 ------- null} -y BAD_FRAME

+ -t 1559191741.605000 -s 5 -d 4 -i -1230929328 -p 1 -x {5.0 4.2 -1 ------- null}
- -t 1559191741.655000 -s 5 -d 4 -i -1230929328 -p 1 -x {5.0 4.2 -1 ------- null}
r -t 1559191742.268000 -s 5 -d 4 -i -1230929328 -p 1 -x {5.0 4.2 -1 ------- null}
d -t 1559191742.274000 -s 5 -d 3 -i -1230929328 -p 1 -x {5.0 4.2 -1 ------- null} -y BAD_FRAME
d -t 1559191742.287000 -s 5 -d 2 -i -1230929328 -p 1 -x {5.0 4.2 -1 ------- null} -y BAD_FRAME
+ -t 1559191742.300000 -s 4 -d 5 -i -2045618010 -p 0 -x {4.0 5.2 -1 ------- null}
d -t 1559191742.306000 -s 5 -d 1 -i -1230929328 -p 1 -x {5.0 4.2 -1 ------- null} -y BAD_FRAME
+ -t 1559191742.316000 -s 4 -d 2 -i -1660400851 -p 1 -x {4.0 2.2 -1 ------- null}
- -t 1559191742.351000 -s 4 -d 5 -i -2045618010 -p 0 -x {4.0 5.2 -1 ------- null}
r -t 1559191742.736000 -s 4 -d 3 -i -2045618010 -p 0 -x {4.0 5.2 -1 ------- null}
- -t 1559191742.756000 -s 4 -d 2 -i -1660400851 -p 1 -x {4.0 2.2 -1 ------- null}
r -t 1559191742.762000 -s 4 -d 2 -i -2045618010 -p 0 -x {4.0 5.2 -1 ------- null}
r -t 1559191742.772000 -s 4 -d 5 -i -2045618010 -p 0 -x {4.0 5.2 -1 ------- null}
d -t 1559191742.786000 -s 4 -d 1 -i -2045618010 -p 0 -x {4.0 5.2 -1 ------- null} -y BAD_FRAME
r -t 1559191743.330000 -s 4 -d 3 -i -1660400851 -p 1 -x {4.0 2.2 -1 ------- null}
r -t 1559191743.357000 -s 4 -d 2 -i -1660400851 -p 1 -x {4.0 2.2 -1 ------- null}
+ -t 1559191743.358000 -s 2 -d 4 -i 1941993078 -p 0 -x {2.0 4.2 -1 ------- null}
+ -t 1559191743.362000 -s 2 -d 1 -i 1563463759 -p 1 -x {2.0 1.2 -1 ------- null}
r -t 1559191743.365000 -s 4 -d 5 -i -1660400851 -p 1 -x {4.0 2.2 -1 ------- null}
d -t 1559191743.380000 -s 4 -d 1 -i -1660400851 -p 1 -x {4.0 2.2 -1 ------- null} -y BAD_FRAME
- -t 1559191743.410000 -s 2 -d 4 -i 1941993078 -p 0 -x {2.0 4.2 -1 ------- null}
r -t 1559191743.787000 -s 2 -d 1 -i 1941993078 -p 0 -x {2.0 4.2 -1 ------- null}
r -t 1559191743.791000 -s 2 -d 3 -i 1941993078 -p 0 -x {2.0 4.2 -1 ------- null}
- -t 1559191743.813000 -s 2 -d 1 -i 1563463759 -p 1 -x {2.0 1.2 -1 ------- null}
r -t 1559191743.821000 -s 2 -d 4 -i 1941993078 -p 0 -x {2.0 4.2 -1 ------- null}
d -t 1559191743.849000 -s 2 -d 5 -i 1941993078 -p 0 -x {2.0 4.2 -1 ------- null} -y BAD_FRAME
r -t 1559191744.383000 -s 2 -d 1 -i 1563463759 -p 1 -x {2.0 1.2 -1 ------- null}
r -t 1559191744.387000 -s 2 -d 3 -i 1563463759 -p 1 -x {2.0 1.2 -1 ------- null}
+ -t 1559191744.388000 -s 1 -d 2 -i 1520738108 -p 0 -x {1.0 2.2 -1 ------- null}
r -t 1559191744.416000 -s 2 -d 4 -i 1563463759 -p 1 -x {2.0 1.2 -1 ------- null}
- -t 1559191744.440000 -s 1 -d 2 -i 1520738108 -p 0 -x {1.0 2.2 -1 ------- null}
d -t 1559191744.446000 -s 2 -d 5 -i 1563463759 -p 1 -x {2.0 1.2 -1 ------- null} -y BAD_FRAME
r -t 1559191744.817000 -s 1 -d 2 -i 1520738108 -p 0 -x {1.0 2.2 -1 ------- null}
r -t 1559191744.843000 -s 1 -d 3 -i 1520738108 -p 0 -x {1.0 2.2 -1 ------- null}
d -t 1559191744.874000 -s 1 -d 4 -i 1520738108 -p 0 -x {1.0 2.2 -1 ------- null} -y BAD_FRAME
d -t 1559191744.897000 -s 1 -d 5 -i 1520738108 -p 0 -x {1.0 2.2 -1 ------- null} -y BAD_FRAME
+ -t 1559191798.872000 -s 4 -d 2 -i 706565595 -p 1 -x {4.0 2.2 -1 ------- null}
- -t 1559191798.925000 -s 4 -d 2 -i 706565595 -p 1 -x {4.0 2.2 -1 ------- null}
r -t 1559191799.500000 -s 4 -d 3 -i 706565595 -p 1 -x {4.0 2.2 -1 ------- null}
r -t 1559191799.527000 -s 4 -d 2 -i 706565595 -p 1 -x {4.0 2.2 -1 ------- null}
+ -t 1559191799.530000 -s 2 -d 4 -i -476134347 -p 0 -x {2.0 4.2 -1 ------- null}
r -t 1559191799.535000 -s 4 -d 5 -i 706565595 -p 1 -x {4.0 2.2 -1 ------- null}
+ -t 1559191799.536000 -s 2 -d 1 -i -70258 -p 1 -x {2.0 1.2 -1 ------- null}
d -t 1559191799.548000 -s 4 -d 1 -i 706565595 -p 1 -x {4.0 2.2 -1 ------- null} -y BAD_FRAME
- -t 1559191799.582000 -s 2 -d 4 -i -476134347 -p 0 -x {2.0 4.2 -1 ------- null}
r -t 1559191799.958000 -s 2 -d 1 -i -476134347 -p 0 -x {2.0 4.2 -1 ------- null}
r -t 1559191799.961000 -s 2 -d 3 -i -476134347 -p 0 -x {2.0 4.2 -1 ------- null}
- -t 1559191799.985000 -s 2 -d 1 -i -70258 -p 1 -x {2.0 1.2 -1 ------- null}
r -t 1559191799.992000 -s 2 -d 4 -i -476134347 -p 0 -x {2.0 4.2 -1 ------- null}
d -t 1559191800.020000 -s 2 -d 5 -i -476134347 -p 0 -x {2.0 4.2 -1 ------- null} -y BAD_FRAME
r -t 1559191800.552000 -s 2 -d 1 -i -70258 -p 1 -x {2.0 1.2 -1 ------- null}
+ -t 1559191800.554000 -s 1 -d 2 -i -924478001 -p 0 -x {1.0 2.2 -1 ------- null}
r -t 1559191800.555000 -s 2 -d 3 -i -70258 -p 1 -x {2.0 1.2 -1 ------- null}
r -t 1559191800.588000 -s 2 -d 4 -i -70258 -p 1 -x {2.0 1.2 -1 ------- null}
- -t 1559191800.605000 -s 1 -d 2 -i -924478001 -p 0 -x {1.0 2.2 -1 ------- null}
d -t 1559191800.615000 -s 2 -d 5 -i -70258 -p 1 -x {2.0 1.2 -1 ------- null} -y BAD_FRAME
r -t 1559191800.982000 -s 1 -d 2 -i -924478001 -p 0 -x {1.0 2.2 -1 ------- null}
r -t 1559191801.009000 -s 1 -d 3 -i -924478001 -p 0 -x {1.0 2.2 -1 ------- null}
d -t 1559191801.041000 -s 1 -d 4 -i -924478001 -p 0 -x {1.0 2.2 -1 ------- null} -y BAD_FRAME
d -t 1559191801.063000 -s 1 -d 5 -i -924478001 -p 0 -x {1.0 2.2 -1 ------- null} -y BAD_FRAME

In the above trace.nam from line no. 1-36 beacons to set-up routing table.
Traces from line no. 39-98 indicating data packet forwarding originated at node 4 and 5.


问:
Hide echo from apt-get in python
How can i hide the process of installing java (apt-get openjdk-6-jre) when it's runned in python?
So i can replace it with
"Installing Java..." till it's ready.

Thanks in advance.

答:
```<code>proc = subprocess.Popen('apt-get install openjdk-6-jre', stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
output, errors = proc.communicate()
return_Value = proc.returncode
</code>```

This puts the program output into a string in Python, where you should probably check it for errors. See subprocess docs. (Unlike the redirect to /dev/null, this is cross-platform.)

ContentLicense: CC BY-SA 3.0

Title: Hide echo from apt-get in python

Body:
proc = subprocess.Popen('apt-get install openjdk-6-jre', stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
output, errors = proc.communicate()
return_Value = proc.returncode

This puts the program output into a string in Python, where you should probably check it for errors. See subprocess docs. (Unlike the redirect to /dev/null, this is cross-platform.)


问:
Testing Android PreferenceFragment with Espresso
I am trying to write tests for the PreferenceFragments fragment in Settings.

However, I've been getting this error:
android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: is assignable from class: class android.widget.AdapterView

The code for the Test is the following:

```<code>@RunWith(AndroidJUnit4.class)
@SmallTest
public class SettingsFragmentTest {

    @Rule
    public ActivityTestRule<SettingsActivity> mActivityRule = new ActivityTestRule<>(
            SettingsActivity.class);

    @Test
    public void preferredLocationShouldBeVisibleOnDisplay(){
        mActivityRule.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                SettingsFragment settingsFragment = startSettingsFragment();
            }
        });

        // This check passes correctly
        onView(withId(R.id.weather_settings_fragment))
                .check(matches(isCompletelyDisplayed()));

        // This check gives me the NoMatchingViewException
        onData(allOf(is(instanceOf(Preference.class)),
                withKey("location")))
                .check(matches(isCompletelyDisplayed()));
    }

    private SettingsFragment startSettingsFragment(){
        SettingsActivity activity = mActivityRule.getActivity();
        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
        SettingsFragment settingsFragment = new SettingsFragment();

        transaction.replace(R.id.weather_settings_fragment, settingsFragment, "settingsFragment");
        transaction.commit();

        return settingsFragment;
    }
}
</code>```

The settings_activity layout looks as follows:

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:name="com.example.android.sunshine.SettingsFragment"
          android:id="@+id/weather_settings_fragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />
</code>```

And the Preferences Screen layout is the following:

```<code><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">

    <EditTextPreference
        android:defaultValue="@string/pref_location_default"
        android:inputType="text"
        android:key="@string/pref_location_key"
        android:singleLine="true"
        android:title="@string/pref_location_label" />

    <ListPreference
        android:defaultValue="@string/pref_units_metric"
        android:entries="@array/pref_units_options"
        android:entryValues="@array/pref_units_values"
        android:key="@string/pref_units_key"
    android:title="@string/pref_units_label" />

<CheckBoxPreference
    android:defaultValue="@bool/show_notifications_by_default"
    android:key="@string/pref_enable_notifications_key"
    android:summaryOff="@string/pref_enable_notifications_false"
    android:summaryOn="@string/pref_enable_notifications_true"
    android:title="@string/pref_enable_notifications_label" />

</PreferenceScreen>
</code>```

I haven't been able to find any examples or information online on how to test PreferenceFragments. Most of the information related to testing Activities.

答:
```<code>@Test
    public void clickListPreference() throws Exception{

        // Check if it is displayed
        Context appContext = InstrumentationRegistry.getTargetContext();

        onData(allOf(
           is(instanceOf(Preference.class)),
           withKey(appContext.getResources().getString(R.string.pref_units_key))))
          .check(matches(isDisplayed()));

        // Check if click is working
        onData(allOf(
           is(instanceOf(Preference.class)),
           withKey(appContext.getResources().getString(R.string.pref_units_key))))
          .onChildView(withText(appContext.getResources()
              .getString(R.string.pref_units_label))).perform(click());
 }
</code>```

Hope this will help you..

Body:
I am trying to write tests for the PreferenceFragments fragment in Settings.

However, I've been getting this error:
android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: is assignable from class: class android.widget.AdapterView

The code for the Test is the following:

@RunWith(AndroidJUnit4.class)
@SmallTest
public class SettingsFragmentTest {

    @Rule
    public ActivityTestRule<SettingsActivity> mActivityRule = new ActivityTestRule<>(
            SettingsActivity.class);

    @Test
    public void preferredLocationShouldBeVisibleOnDisplay(){
        mActivityRule.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                SettingsFragment settingsFragment = startSettingsFragment();
            }
        });

        // This check passes correctly
        onView(withId(R.id.weather_settings_fragment))
                .check(matches(isCompletelyDisplayed()));

        // This check gives me the NoMatchingViewException
        onData(allOf(is(instanceOf(Preference.class)),
                withKey("location")))
                .check(matches(isCompletelyDisplayed()));
    }

    private SettingsFragment startSettingsFragment(){
        SettingsActivity activity = mActivityRule.getActivity();
        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
        SettingsFragment settingsFragment = new SettingsFragment();

        transaction.replace(R.id.weather_settings_fragment, settingsFragment, "settingsFragment");
        transaction.commit();

        return settingsFragment;
    }
}

The settings_activity layout looks as follows:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:name="com.example.android.sunshine.SettingsFragment"
          android:id="@+id/weather_settings_fragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />

And the Preferences Screen layout is the following:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">

    <EditTextPreference
        android:defaultValue="@string/pref_location_default"
        android:inputType="text"
        android:key="@string/pref_location_key"
        android:singleLine="true"
        android:title="@string/pref_location_label" />

    <ListPreference
        android:defaultValue="@string/pref_units_metric"
        android:entries="@array/pref_units_options"
        android:entryValues="@array/pref_units_values"
        android:key="@string/pref_units_key"
    android:title="@string/pref_units_label" />

<CheckBoxPreference
    android:defaultValue="@bool/show_notifications_by_default"
    android:key="@string/pref_enable_notifications_key"
    android:summaryOff="@string/pref_enable_notifications_false"
    android:summaryOn="@string/pref_enable_notifications_true"
    android:title="@string/pref_enable_notifications_label" />

</PreferenceScreen>

I haven't been able to find any examples or information online on how to test PreferenceFragments. Most of the information related to testing Activities.

Body:
@Test
    public void clickListPreference() throws Exception{

        // Check if it is displayed
        Context appContext = InstrumentationRegistry.getTargetContext();

        onData(allOf(
           is(instanceOf(Preference.class)),
           withKey(appContext.getResources().getString(R.string.pref_units_key))))
          .check(matches(isDisplayed()));

        // Check if click is working
        onData(allOf(
           is(instanceOf(Preference.class)),
           withKey(appContext.getResources().getString(R.string.pref_units_key))))
          .onChildView(withText(appContext.getResources()
              .getString(R.string.pref_units_label))).perform(click());
 }

Hope this will help you..


问:
Vuejs RangeError: Invalid string length
I am new to VueJS, when I try to compile this code it works fine:

```<code><template>
  <div id="users-table">
    <ServerTable url="users" :columns="columns" :options="options"></ServerTable>
  </div>
</template>
</code>```

However when I add another tag (any tag) like that:

```<code><template>
     <h1>Header</h1>
  <div id="users-table">
    <ServerTable url="users" :columns="columns" :options="options"></ServerTable>
  </div>
</template>
</code>```

I am getting an error

```<code>Module build failed (from ./node_modules/vue-loader/lib/loaders/templateLoader.js):
RangeError: Invalid string length
    at repeat$1
</code>```

What am I doing wrong?

答:
Just put the whole content in a single root element.</p>

```<code><template>
  <div>
    <h1>Header</h1>
    <div id="users-table">
      <ServerTable url="users" :columns="columns" :options="options"></ServerTable>
    </div>
  </div>
</template>
</code>```

Title: Vuejs RangeError: Invalid string length

Body:
I am new to VueJS, when I try to compile this code it works fine:

<template>

    <ServerTable url="users" :columns="columns" :options="options"></ServerTable>

</template>

However when I add another tag (any tag) like that:

<template>

Header

    <ServerTable url="users" :columns="columns" :options="options"></ServerTable>

</template>

I am getting an error

Module build failed (from ./node_modules/vue-loader/lib/loaders/templateLoader.js):
RangeError: Invalid string length
    at repeat$1

What am I doing wrong?

Body:
Just put the whole content in a single root element.

<template>
  <div>
    <h1>Header</h1>
    <div id="users-table">
      <ServerTable url="users" :columns="columns" :options="options"></ServerTable>
    </div>
  </div>
</template>


问:
Extract attribute 'value' from BeautifulSoup xml
I am trying to extract search keywords from SOAP xml schema with BeautifulSoup and cannot figure out how to extract value attributes.

I have tried using soap.find_all but it will not let me extract the value attribute.

Here is what I have so far:

```<code>soap = requests.get('http://ecp.iedadata.org/soap_search_schema.xsd')
soapXML = soap.content.decode("utf-8")
soapSoup = BeautifulSoup(soapXML, "xml")
level1 = soapSoup.findAll('xs:attribute', {'name':'level1'})[0]
level1['value']
</code>```

And this is where I have an issue. According to BeautifulSoup documentation this should output all the 'value' attributes.

```<code>print(level1):

<xs:attribute name="level1" use="optional">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value=""/>
<xs:enumeration value="alteration"/>
<xs:enumeration value="igneous"/>
<xs:enumeration value="metamorphic"/>
<xs:enumeration value="notfound"/>
<xs:enumeration value="ore"/>
<xs:enumeration value="sedimentary"/>
<xs:enumeration value="vein"/>
<xs:enumeration value="xenolith"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</code>```

So as you can see, I am trying to get the text from the value attribute in all of the xs:enumeration tags. The end result would be a list of search terms for level1. i.e.:

(alteration, igneous, metamorphic, notfound, ore, sedimentary, vein, xenolith)

I cannot just call on the xs:enumeration tag as there are multiple keywords (i.e. level2, level3, SampleType... etc.) and each have different xs:enumeration values.

Here is the error on the last line (level1['value'])

KeyError                                  Traceback (most recent call last)
   in
  ----> 1 level1test['value']

~/anaconda3/envs/py37/lib/python3.7/site-packages/bs4/element.py in getitem(self, key)
     1069         """tag[key] returns the value of the 'key' attribute for the tag,
     1070         and throws an exception if it's not there."""
  -> 1071         return self.attrs[key]
     1072
     1073     def iter(self):

KeyError: 'value'

答:
Simply use the value attribute selector

```<code>import requests
from bs4 import BeautifulSoup as bs

soap = requests.get('http://ecp.iedadata.org/soap_search_schema.xsd')
soapXML = soap.content.decode("utf-8")
soapSoup =bs(soapXML, "xml")
enumeration_values = [item['value'] for item in  soapSoup.select("[value]") if item['value']]
print(enumeration_values)
</code>```

Marginally faster would be to use the type selector

```<code>import requests
from bs4 import BeautifulSoup as bs

soap = requests.get('http://ecp.iedadata.org/soap_search_schema.xsd')
soapXML = soap.content.decode("utf-8")
soapSoup =bs(soapXML, "xml")
enumeration_values = [item['value'] for item in  soapSoup.select("enumeration") if item['value']]
print(enumeration_values)
</code>```

Body:
I am trying to extract search keywords from SOAP xml schema with BeautifulSoup and cannot figure out how to extract value attributes.

I have tried using soap.find_all but it will not let me extract the value attribute.

Here is what I have so far:

soap = requests.get('http://ecp.iedadata.org/soap_search_schema.xsd')
soapXML = soap.content.decode("utf-8")
soapSoup = BeautifulSoup(soapXML, "xml")
level1 = soapSoup.findAll('xs:attribute', {'name':'level1'})[0]
level1['value']

And this is where I have an issue. According to BeautifulSoup documentation this should output all the 'value' attributes.

print(level1):

<xs:attribute name="level1" use="optional">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value=""/>
<xs:enumeration value="alteration"/>
<xs:enumeration value="igneous"/>
<xs:enumeration value="metamorphic"/>
<xs:enumeration value="notfound"/>
<xs:enumeration value="ore"/>
<xs:enumeration value="sedimentary"/>
<xs:enumeration value="vein"/>
<xs:enumeration value="xenolith"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>

So as you can see, I am trying to get the text from the value attribute in all of the xs:enumeration tags. The end result would be a list of search terms for level1. i.e.:

(alteration, igneous, metamorphic, notfound, ore, sedimentary, vein, xenolith)

I cannot just call on the xs:enumeration tag as there are multiple keywords (i.e. level2, level3, SampleType... etc.) and each have different xs:enumeration values.

Here is the error on the last line (level1['value'])

KeyError                                  Traceback (most recent call last)
   in
  ----> 1 level1test['value']

~/anaconda3/envs/py37/lib/python3.7/site-packages/bs4/element.py in getitem(self, key)
     1069         """tag[key] returns the value of the 'key' attribute for the tag,
     1070         and throws an exception if it's not there."""
  -> 1071         return self.attrs[key]
     1072
     1073     def iter(self):

KeyError: 'value'

Body:
Simply use the value attribute selector

import requests
from bs4 import BeautifulSoup as bs

soap = requests.get('http://ecp.iedadata.org/soap_search_schema.xsd')
soapXML = soap.content.decode("utf-8")
soapSoup =bs(soapXML, "xml")
enumeration_values = [item['value'] for item in  soapSoup.select("[value]") if item['value']]
print(enumeration_values)

Marginally faster would be to use the type selector

import requests
from bs4 import BeautifulSoup as bs

soap = requests.get('http://ecp.iedadata.org/soap_search_schema.xsd')
soapXML = soap.content.decode("utf-8")
soapSoup =bs(soapXML, "xml")
enumeration_values = [item['value'] for item in  soapSoup.select("enumeration") if item['value']]
print(enumeration_values)


问:
Calendar week end days issue
I am getting a calendar instance

```<code>Calendar.getInstance()
</code>```

In one mobile it is showing Saturday as weekend while in another it is showing Sunday as weekend
The timezone of both devices is same

If i set the calendar instance locale to US or any other country it works perfectly.
But i dont want it to be constant. I want it to be regional but consistent on all devices

I want the weekend on both devices same if the time zone is same

答:
You can try something like.</p>

```<code>Calendar sundayFirst = Calendar.getInstance();
sundayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
</code>```

Title: Calendar week end days issue

Body:
I am getting a calendar instance

Calendar.getInstance()

In one mobile it is showing Saturday as weekend while in another it is showing Sunday as weekend
The timezone of both devices is same

If i set the calendar instance locale to US or any other country it works perfectly.
But i dont want it to be constant. I want it to be regional but consistent on all devices

I want the weekend on both devices same if the time zone is same

Body:
You can try something like.

Calendar sundayFirst = Calendar.getInstance();
sundayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);


问:
How to call a function when user clicks Yes or No in ConfirmAlert Plugin of ReactJS
I am using the ConfirmAlert plugin of ReactJs which provides the flexibility to choose what should happen when user clicks Yes or No on the confirm Dialog box. But when I click on Yes, i want a function to get invoked which performs some chunk of work. But the problem is that the function does not get called when I click "Yes". I dont know what mistake am I doing.

I can achieve this using window.confirm() method. But i want to make use of ConfirmAlert plugin provided by ReactJs.

```<code>  handleClick = (value) => {
            value.map(item => {
         if (item.props.status) {
                      confirmAlert({
                            title: "message",
                            message: "Are you sure?",
                            buttons: [
                                      {
                                        label: 'Yes',
                                        onclick: () =>

         (this.formCollection(item.props.name, item.props.id) // Does not Fire.
                                       },
                                       {
                                         label: 'No',
                                         onClick: () => window.alert("Subscription Aborted!!") // Works fine.
                                       }
                                    ]
                                 })
                             }
                         })
                       }

               formCollection = (name, id) => {
                          // doing desired work here.
                         }

             <input type = "button" onclick={this.handleClick(alerts)} />
</code>```

I expect the formCollection method to get triggerd when user clicks "Yes" on the confirm dialog box.

答:
The event name should be in camelCase   </p>

```<code>                buttons: [{
                label: 'Yes',
                onClick: () =>

                    this.formCollection(item.props.name, item.props.id)
                    },
                {
                    label: 'No',
                    onClick: () => window.alert("Subscription Aborted!!")
                }
            ]
</code>```

Body:
I am using the ConfirmAlert plugin of ReactJs which provides the flexibility to choose what should happen when user clicks Yes or No on the confirm Dialog box. But when I click on Yes, i want a function to get invoked which performs some chunk of work. But the problem is that the function does not get called when I click "Yes". I dont know what mistake am I doing.

I can achieve this using window.confirm() method. But i want to make use of ConfirmAlert plugin provided by ReactJs.

  handleClick = (value) => {
            value.map(item => {
         if (item.props.status) {
                      confirmAlert({
                            title: "message",
                            message: "Are you sure?",
                            buttons: [
                                      {
                                        label: 'Yes',
                                        onclick: () =>

         (this.formCollection(item.props.name, item.props.id) // Does not Fire.
                                       },
                                       {
                                         label: 'No',
                                         onClick: () => window.alert("Subscription Aborted!!") // Works fine.
                                       }
                                    ]
                                 })
                             }
                         })
                       }

               formCollection = (name, id) => {
                          // doing desired work here.
                         }

             <input type = "button" onclick={this.handleClick(alerts)} />

I expect the formCollection method to get triggerd when user clicks "Yes" on the confirm dialog box.

Body:
The event name should be in camelCase

                buttons: [{
                label: 'Yes',
                onClick: () =>

                    this.formCollection(item.props.name, item.props.id)
                    },
                {
                    label: 'No',
                    onClick: () => window.alert("Subscription Aborted!!")
                }
            ]


问:
Unable to find Vuex module action in Nuxt
I'm working on a Nuxt site with a custom Django back end, and I'm trying to set up a mechanism where when the app loads, I call a /token/ URL to get a CSRF token, and then store it in Vuex state to be used in a custom header that is set for every subsequent request.

First, here is my store/index.js:

```<code>import Vue from 'vue'
import Vuex from 'vuex'
import auth from '@/store/auth'

const debug = process.env.NODE_ENV !== 'production'

Vue.use(Vuex)

const store = () => {
  return new Vuex.Store({
    namespaced: true,
    modules: {
      auth
    }
  })
}
export default store
</code>```

and store/auth.js:

```<code>import { SET_TOKEN } from './types'

const state = () => ({
  token: ''
})

const getters = {
  token: state => state.token
}

const actions = {
  setToken({ commit, dispatch }, token) {
    commit(SET_TOKEN)
  }
}

const mutations = {
  [SET_TOKEN](state, token) {
    state.token = token
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
</code>```

One thing I can't figure it is where to put my mounted function so it's always triggered on page reload. In a regular Vue app, it's App.vue, but I haven't been able to find what that same thing is in Nuxt. For now, I just use index.vue. I'm also using the @axios Nuxt module to communicate with the back end.

```<code><script>
import Cookie from 'js-cookie'

export default {
  mounted() {
    this.getCSRFToken()
  },
  methods: {
    async getCSRFToken() {
      // Call the URL that sets the csrftoken cookie
      const tokenRequest = await this.$axios.$get('/token/')
      // Get the cookie value
      const token = Cookie.get('csrftoken')
      // Save it to the store./
      this.$store.dispatch('auth/setToken', token)
    }
  }
}
</script>
</code>```

I can call the URL just fine and get the value from the cookie, but when I go to dispatch my action, I get an error that says [vuex] unknown action type: auth/setToken.

I followed the example here to set up my state. My questions are these:

What is a common starting point in Nuxt that I can use to always load this on page refresh/initial load?

What do I need to change in my setup so that my action is found?

答:
The issue is that your auth module is not namespaced.

Change the default export to

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
```

<p>You should probably remove <code>namespaced: true</code> from your root store.</p>

<hr>

<p>I recommend you change to using Nuxt's Module Mode as the Classic Mode you're using will be removed in Nuxt 3. For example</p>

<pre class="lang-js prettyprint-override"><code>// store/auth.js
import { SET_TOKEN } from './types'

export const state = () => ({
  token: ''
})

export const actions = {
  setToken({ commit, dispatch }, token) {
    commit(SET_TOKEN)
  }
}

export const mutations = {
  [SET_TOKEN](state, token) {
    state.token = token
  }
}
</code>```

Body:
I'm working on a Nuxt site with a custom Django back end, and I'm trying to set up a mechanism where when the app loads, I call a /token/ URL to get a CSRF token, and then store it in Vuex state to be used in a custom header that is set for every subsequent request.

First, here is my store/index.js:

import Vue from 'vue'
import Vuex from 'vuex'
import auth from '@/store/auth'

const debug = process.env.NODE_ENV !== 'production'

Vue.use(Vuex)

const store = () => {
  return new Vuex.Store({
    namespaced: true,
    modules: {
      auth
    }
  })
}
export default store

and store/auth.js:

import { SET_TOKEN } from './types'

const state = () => ({
  token: ''
})

const getters = {
  token: state => state.token
}

const actions = {
  setToken({ commit, dispatch }, token) {
    commit(SET_TOKEN)
  }
}

const mutations = {
  [SET_TOKEN](state, token) {
    state.token = token
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}

One thing I can't figure it is where to put my mounted function so it's always triggered on page reload. In a regular Vue app, it's App.vue, but I haven't been able to find what that same thing is in Nuxt. For now, I just use index.vue. I'm also using the @axios Nuxt module to communicate with the back end.

I can call the URL just fine and get the value from the cookie, but when I go to dispatch my action, I get an error that says [vuex] unknown action type: auth/setToken.

I followed the example here to set up my state. My questions are these:

What is a common starting point in Nuxt that I can use to always load this on page refresh/initial load?

What do I need to change in my setup so that my action is found?

Body:
The issue is that your auth module is not namespaced.

Change the default export to

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}

You should probably remove namespaced: true from your root store.

I recommend you change to using Nuxt's Module Mode as the Classic Mode you're using will be removed in Nuxt 3. For example

// store/auth.js
import { SET_TOKEN } from './types'

export const state = () => ({
  token: ''
})

export const actions = {
  setToken({ commit, dispatch }, token) {
    commit(SET_TOKEN)
  }
}

export const mutations = {
  [SET_TOKEN](state, token) {
    state.token = token
  }
}


问:
How do I use Python to trigger the download of a file from a website?
I'm trying to set up a script to pull data from a website on a daily basis and I'm having trouble getting Python to actually read the table - I'm not a professional coder. I've tried two methods:

1) Scrape the table (headers, rows, etc) using Beautiful Soup, and

2) Use the website's export with excel button

Here is the precise website:
https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200

So far my code is:

#Imports
import requests
import urllib.request
import pandas as pd
from lxml import html
import lxml.html as lh
from bs4 import BeautifulSoup
`URL ='https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200'`

#Create a handle, page, to handle the contents of the website
requests.packages.urllib3.disable_warnings()
page = requests.get(URL, verify=False)
```

<p>I think the easiest method would be to trigger the "export" function with the </p>

```xpath //*[@id="content"]/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[1]/a
```

All help is greatly appreciated!

答:
Your website is appending dynamic table data with the export button. So basically you need to use Selenium package to handle dynamic data. download selenium web driver as per your browser.

for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

```<code>unzip ~/Downloads/chromedriver_linux64.zip -d ~/Downloads
chmod +x ~/Downloads/chromedriver
sudo mv -f ~/Downloads/chromedriver /usr/local/share/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver
</code>```

selenium tutorial

https://selenium-python.readthedocs.io/

Export Excel file:

```<code>from selenium import webdriver
import time

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200')
time.sleep(3)
excel_button = driver.find_element_by_xpath("//div[@id='content']/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[2]/a")

print(excel_button.click())
</code>```

where "/usr/bin/chromedriver" chrome web driver path.

Body:
I'm trying to set up a script to pull data from a website on a daily basis and I'm having trouble getting Python to actually read the table - I'm not a professional coder. I've tried two methods:

1) Scrape the table (headers, rows, etc) using Beautiful Soup, and

2) Use the website's export with excel button

Here is the precise website:
https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200

So far my code is:

#Imports
import requests
import urllib.request
import pandas as pd
from lxml import html
import lxml.html as lh
from bs4 import BeautifulSoup
`URL ='https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200'`

#Create a handle, page, to handle the contents of the website
requests.packages.urllib3.disable_warnings()
page = requests.get(URL, verify=False)

I think the easiest method would be to trigger the "export" function with the

xpath //*[@id="content"]/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[1]/a

All help is greatly appreciated!

Body:
Your website is appending dynamic table data with the export button. So basically you need to use Selenium package to handle dynamic data. download selenium web driver as per your browser.

for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

unzip ~/Downloads/chromedriver_linux64.zip -d ~/Downloads
chmod +x ~/Downloads/chromedriver
sudo mv -f ~/Downloads/chromedriver /usr/local/share/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver

selenium tutorial

https://selenium-python.readthedocs.io/

Export Excel file:

from selenium import webdriver
import time

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200')
time.sleep(3)
excel_button = driver.find_element_by_xpath("//div[@id='content']/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[2]/a")

print(excel_button.click())

where "/usr/bin/chromedriver" chrome web driver path.


问:
Excluding elements from an old array and creating a new array
I have an array that has 3 different values, I want to create a new array that has only the values that are smaller that 12 (for example).

```<code>import array as arr

numbers = arr.array([10,12, 12, 13])

numbers.remove(12)
numbers.remove(13)
print(numbers)
</code>```

I don't know how to add them in a new array

答:
Assumption:

you want only unique elements from the initial list

the elements should be less than 12

Code:

```<code>initial_list = [10, 12, 12, 13]
new_list = [i for i in list(set(initial_list)) if i<12]
print(new_list)
</code>```

Output:

```<code>[10]
</code>```

Explanation:

The above code first creates a set of unique elements from the initial list.  Then it selects the only items that meet the condition i<12 using a list comprehension.

N.B.: If you are bound to use array module, @Praveenkumar's answer is the way to use.

Body:
I have an array that has 3 different values, I want to create a new array that has only the values that are smaller that 12 (for example).

import array as arr

numbers = arr.array([10,12, 12, 13])

numbers.remove(12)
numbers.remove(13)
print(numbers)

I don't know how to add them in a new array

Body:
Assumption:

you want only unique elements from the initial list

the elements should be less than 12

Code:

initial_list = [10, 12, 12, 13]
new_list = [i for i in list(set(initial_list)) if i<12]
print(new_list)

Output:

[10]

Explanation:

The above code first creates a set of unique elements from the initial list.  Then it selects the only items that meet the condition i<12 using a list comprehension.

N.B.: If you are bound to use array module, @Praveenkumar's answer is the way to use.


问:
iOS - share instances / memory between UI test and app
Is there a way to share instances / data between the app and the UI test being run? My understanding is that they run as two different apps and that make it impossible but I wanted to check. I was thinking of something like:

```<code>// included in both my app and the UI test
class Foo {
  let shared: Foo()
  var value = ""
}

// In the UI test:
class BasicAccessibility: XCTestCase {
  func testFoo() {
    Foo.shared.value = "bar"
  }
}

// In the app
class FooController: UIViewController {
  override func viewDidLoad() {
    label.value = Foo.shared.value
  }
}
</code>```

I'm trying to simulate device gyroscope from the UI tests, so in my case Foo would be some gyro manager instance. My best alternative atm it to include a UI element in the app that the test can interact with, which kind of sucks.

=== edit ===

I don't think This question is similar since it's not about UI test and the UI test app has different settings and abilities than a normal app.

答:
I don't know if this is a very good idea, but it's something that I'm trying and it seems to work well. If anyone knows a very bad reason to do this let me know.

create a file named Person.swift and add it to both app target and UITestTarget.

struct Person: Codable {
    let name: String
    let age: Int
    let height: Int
    let weight: Int
}
```

<p>In your UITests "serialize" the object and send it over launch environment dictionary.</p>

<pre class="lang-swift prettyprint-override"><code>class UITestingDataUITests: XCTestCase {

    let app = XCUIApplication()

    override func setUp() {
        continueAfterFailure = false

        let person = Person(name: "Tom Cruise", age: 56, height: 170, weight: 60)
        let json = String(data: try! JSONEncoder().encode(person), encoding: .utf8)

        continueAfterFailure = false
        app.launchArguments.append("isUITesting")
        app.launchEnvironment["custom-object-person"] = json
        app.launch()
    }
</code>```

In your app delegate access the object:

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {

        let personInfo = ProcessInfo.processInfo.environment["custom-object-person"]!
        let person = try! JSONDecoder().decode(Person.self, from: personInfo.data(using: .utf8)!)
        print(person)

        return true
    }

```

Body:
Is there a way to share instances / data between the app and the UI test being run? My understanding is that they run as two different apps and that make it impossible but I wanted to check. I was thinking of something like:

// included in both my app and the UI test
class Foo {
  let shared: Foo()
  var value = ""
}

// In the UI test:
class BasicAccessibility: XCTestCase {
  func testFoo() {
    Foo.shared.value = "bar"
  }
}

// In the app
class FooController: UIViewController {
  override func viewDidLoad() {
    label.value = Foo.shared.value
  }
}

I'm trying to simulate device gyroscope from the UI tests, so in my case Foo would be some gyro manager instance. My best alternative atm it to include a UI element in the app that the test can interact with, which kind of sucks.

=== edit ===

I don't think This question is similar since it's not about UI test and the UI test app has different settings and abilities than a normal app.

Body:
I don't know if this is a very good idea, but it's something that I'm trying and it seems to work well. If anyone knows a very bad reason to do this let me know.

create a file named Person.swift and add it to both app target and UITestTarget.

struct Person: Codable {
    let name: String
    let age: Int
    let height: Int
    let weight: Int
}

In your UITests "serialize" the object and send it over launch environment dictionary.

class UITestingDataUITests: XCTestCase {

    let app = XCUIApplication()

    override func setUp() {
        continueAfterFailure = false

        let person = Person(name: "Tom Cruise", age: 56, height: 170, weight: 60)
        let json = String(data: try! JSONEncoder().encode(person), encoding: .utf8)

        continueAfterFailure = false
        app.launchArguments.append("isUITesting")
        app.launchEnvironment["custom-object-person"] = json
        app.launch()
    }

In your app delegate access the object:

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {

        let personInfo = ProcessInfo.processInfo.environment["custom-object-person"]!
        let person = try! JSONDecoder().decode(Person.self, from: personInfo.data(using: .utf8)!)
        print(person)

        return true
    }


问:
Can const value be changed using initialiser list?
I have initialized the const reference z and tried to reinitialize it using initializer list and the output I am getting is the changed value.
No errors no warnings.</p>

```<code>#include <iostream>
using namespace std;
class Point {
    private:
    const int &z=9;

    public:
    Point (int &c):z(c){}

    int get_setz(){
        return z;
    }

};

int main()
{
    int m=3;
    Point p(m);
    cout << p.get_setz();
    return 0;
}

Output :
3
</code>```

答:
I have initialized the const reference z and tried to reinitialize

You tried, but you didn't. When a constructor member initialization list is used to initialize a member, any default member initializer is ignored. z never referred to a temporary with the value 9. So the rules of C++ are still very much in play, you may not reseat a reference, and there was never even an attempt to do so.

And had you not initialized z with c, you'd have a dangling reference and code with undefined behavior on your hands. Because that 9 is not an object, it's a literal. References can only bind to objects, and so you'd have bound it to a temporary that would have gone out of scope once the initialization of your object was complete.

Body:
I have initialized the const reference z and tried to reinitialize it using initializer list and the output I am getting is the changed value.
No errors no warnings.

#include <iostream>
using namespace std;
class Point {
    private:
    const int &z=9;

    public:
    Point (int &c):z(c){}

    int get_setz(){
        return z;
    }

};

int main()
{
    int m=3;
    Point p(m);
    cout << p.get_setz();
    return 0;
}

Output :
3


问:
How to map Azure Functions secrets from Key Vault automatically
I was wondering if it's possible to initialize the queue trigger or even the blob trigger off a connection string that is read from azure vault.

Right now, we have to set these data connection via environment settings via blade properties.  However, I wanted to just use the service principal to retrieve the token for the azure key vault to get all these connection strings.

I'm trying to figure how to get this working in java.

Thanks,
Derek

答:
I have already given my answer in above, this answer is for @Matt Sanders's comment,
i just want to explain how MSI working in the Azure Environment,

"I have 2 user assigned identities, 1 has permissions to KeyVault, the other does not. How can you specify the correct user assigned an identity to use for retrieving the secret? I'm guessing this is not possible and User Assigned Identities are not supported even though they are listed in your answer. – Matt Sanders"

when you want to use Azure Manage Identity Service, your application must register in the Azure AD, for an example, lets say multiple users accessing your web application and, within your web application, you 'r trying to access vVault's secrets, In that case, vault doesnt care about the users that consume your application, it cares about the application,

please reffer below image,

I as showing the picture, only Azure Function added as an Identity to the vault, other applications are not,

so whoever using Azure function can access vault's secrets, according to this example only A and B can access secrets,


问:
Difference between transformDexArchiveWithDexMergerForRelease and transformDexArchiveWithDexMergerForDebug task?
When I run assembleDebug, debug apk of the application is generated successfully but on trying assembleRelease, it results into failure at transformDexArchiveWithDexMergerForDebug task.

Following is the snippet of the exact error:

```<code>FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:transformDexArchiveWithDexMergerForRelease'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException:
Program type already present: android.support.annotation.AnimRes
</code>```

I would like to know why this error doesn't occur with assembleDebug?

What exactly is the difference between transformDexArchiveWithDexMergerForDebug and transformDexArchiveWithDexMergerForRelease?

P.S. I have tried clean and rebuild of the project.

答:
One reason for this to happen is multidex . Probably in gradle in your debug version you have

```<code>    `multidexEnabled true
</code>```

which lets you bypass the 64k limit for your debug version hence the apk is created successfully. What usually happens for production code is you don't enable multidex and use proguard to reduce the referenced code size to not bypass the 64k limit.

Body:
When I run assembleDebug, debug apk of the application is generated successfully but on trying assembleRelease, it results into failure at transformDexArchiveWithDexMergerForDebug task.

Following is the snippet of the exact error:

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:transformDexArchiveWithDexMergerForRelease'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException:
Program type already present: android.support.annotation.AnimRes

I would like to know why this error doesn't occur with assembleDebug?

What exactly is the difference between transformDexArchiveWithDexMergerForDebug and transformDexArchiveWithDexMergerForRelease?

P.S. I have tried clean and rebuild of the project.

Body:
One reason for this to happen is multidex . Probably in gradle in your debug version you have

    `multidexEnabled true

which lets you bypass the 64k limit for your debug version hence the apk is created successfully. What usually happens for production code is you don't enable multidex and use proguard to reduce the referenced code size to not bypass the 64k limit.


问:
Getting counts in MultiLabelBinarizer
How can I get counts of items in MultiLabelBinarizer?

```<code>import pandas as pd
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()

pd.DataFrame(mlb.fit_transform([(1,1,2), (3,3,2,5)]),columns=mlb.classes_)

Out[0]:
   1  2  3  5
0  1  1  0  0
1  0  1  1  1
</code>```

Instead of this, I want to get

```<code>Out[0]:
   1  2  3  5
0  2  1  0  0
1  0  1  2  1
</code>```

As 1 is repeated 2 times in row 1 and 3 is repeated 2 times in row 2

答:
```<code>from collections import Counter

data = [(1,1,2), (3,3,2,5)]
pd.DataFrame([Counter(x) for x in data]).fillna(0)
</code>```

Output:

```<code>    1       2   3       5
0   2.0     1   0.0     0.0
1   0.0     1   2.0     1.0
</code>```

Title: Getting counts in MultiLabelBinarizer

Body:
How can I get counts of items in MultiLabelBinarizer?

import pandas as pd
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()

pd.DataFrame(mlb.fit_transform([(1,1,2), (3,3,2,5)]),columns=mlb.classes_)

Out[0]:
   1  2  3  5
0  1  1  0  0
1  0  1  1  1

Instead of this, I want to get

Out[0]:
   1  2  3  5
0  2  1  0  0
1  0  1  2  1

As 1 is repeated 2 times in row 1 and 3 is repeated 2 times in row 2

Body:
from collections import Counter

data = [(1,1,2), (3,3,2,5)]
pd.DataFrame([Counter(x) for x in data]).fillna(0)

Output:

    1       2   3       5
0   2.0     1   0.0     0.0
1   0.0     1   2.0     1.0


问:
How to fix "Error: Could not find or load main class ”-Djava.library.path=.usr.local.hadoop.lib” while installing hadoop
I am trying to install Hadoop 2.9.2 on Ubuntu.

I have set same path to JAVA_HOME in ~/.bashrc and env.sh files.Two separate directories for data node and name node are created under hadoop_store with the right path.The java version is "java-11-openjdk-amd64".
I am still facing an error while formating the namenode in the hadoop file system. Please help me in resolving it.

The link to the page whose instrutions I have been following.
https://www.digitalvidya.com/blog/install-hadoop-on-ubuntu-and-run-your-first-mapreduce-program/

This is the error:

```<code>hduser@ubuntu:~$ hadoop namenode -format
DEPRECATED: Use of this script to execute hdfs command is deprecated.
Instead use the hdfs command for it.

Error: Could not find or load main class ”-Djava.library.path=.usr.local.hadoop.lib”
Caused by: java.lang.ClassNotFoundException: ”-Djava.library.path=.usr.local.hadoop.lib”

</code>```

答:
check your ~/.bashrc

if you add line

export HADOOP_OPTS="-Djava.library.path=$HADOOP_HOME/lib"

make sure the "" is correct

Body:
I am trying to install Hadoop 2.9.2 on Ubuntu.

I have set same path to JAVA_HOME in ~/.bashrc and env.sh files.Two separate directories for data node and name node are created under hadoop_store with the right path.The java version is "java-11-openjdk-amd64".
I am still facing an error while formating the namenode in the hadoop file system. Please help me in resolving it.

The link to the page whose instrutions I have been following.
https://www.digitalvidya.com/blog/install-hadoop-on-ubuntu-and-run-your-first-mapreduce-program/

This is the error:

hduser@ubuntu:~$ hadoop namenode -format
DEPRECATED: Use of this script to execute hdfs command is deprecated.
Instead use the hdfs command for it.

Error: Could not find or load main class ”-Djava.library.path=.usr.local.hadoop.lib”
Caused by: java.lang.ClassNotFoundException: ”-Djava.library.path=.usr.local.hadoop.lib”


答:
```<code>numbers = [10,12,13,14]
newarr = []
for i in numbers:
    if i<12:
        newarr.append(i)
print(newarr)
</code>```

Use a python list and iterate over the previous list(Use list, not an array), check for the required condition and add(append) the results to a new list.

Title: Excluding elements from an old array and creating a new array

Body:
numbers = [10,12,13,14]
newarr = []
for i in numbers:
    if i<12:
        newarr.append(i)
print(newarr)

Use a python list and iterate over the previous list(Use list, not an array), check for the required condition and add(append) the results to a new list.


问:
How do I customize the menu option in options_from_collection_for_select in Rails 3?
I have this in my view:

```<code><%
@plan = Plan.limit(4).all
plan ||= Plan.find(params[:plan_id])

%>

<%= select_tag "Plan", options_from_collection_for_select(@plan, 'id', 'name', plan.id) %><br />
</code>```

That produces the following:

```<code><select id="Plan" name="Plan"><option value="1">Gecko</option>
<option value="2" selected="selected">Iguana</option>
</select>
</code>```

However, I would like it to produce the following options:

```<code><select id="Plan" name="Plan"><option value="1">Gecko ($50)</option>
<option value="2" selected="selected">Iguana ($99)</option>
</select>
</code>```

Where the price in brackets is plan.amount.

答:
You could create a method in your model which returns the value you want to present:</p>

```<code>class Plan < ActiveRecord::Base
  ...

  def display_name
    "#{self.name} (#{self.amount})"
  end
end

# View
<%= select_tag "Plan", options_from_collection_for_select(@plan, 'id', 'display_name', plan.id) %>
</code>```

Body:
I have this in my view:

<%
@plan = Plan.limit(4).all
plan ||= Plan.find(params[:plan_id])

%>

<%= select_tag "Plan", options_from_collection_for_select(@plan, 'id', 'name', plan.id) %>

That produces the following:

<select id="Plan" name="Plan"><option value="1">Gecko</option>
<option value="2" selected="selected">Iguana</option>
</select>

However, I would like it to produce the following options:

<select id="Plan" name="Plan"><option value="1">Gecko ($50)</option>
<option value="2" selected="selected">Iguana ($99)</option>
</select>

Where the price in brackets is plan.amount.

Body:
You could create a method in your model which returns the value you want to present:

class Plan < ActiveRecord::Base
  ...

  def display_name
    "#{self.name} (#{self.amount})"
  end
end

# View
<%= select_tag "Plan", options_from_collection_for_select(@plan, 'id', 'display_name', plan.id) %>


问:
Exception "error MSB3024: Could not copy the file..." is thrown when attempting to build in DevOps pipeline using .Net Core 3.0 SDK (preview5)
I am attempting to build a .Net Core 3.0 (preview) project in a DevOps build pipeline.

The steps in my azure-pipelines.yml executes up to the "docker build" step, successfully initiating the build process.
The Docker file is read and executed up to the "dotnet build" step after which the following error is thrown.

error MSB3024: Could not copy the file "/src/obj/Release/netcoreapp3.0/" to the destination file "/app/", because the destination is a folder instead of a file. To copy the source file into a folder, consider using the DestinationFolder parameter instead of DestinationFiles. [/src/.csproj]

I have attempted to build locally by executing dotnet build ".csproj" -c Release -o /app
The build then succeeds with 0 errors and 0 warnings. Could this be related to an SDK issue in DevOps?

Any advice would be greatly appreciated.

The build command from my Docker file.

```<code>RUN dotnet build "<project>.csproj" -c Release -o /app
</code>```

```<code>--- {OMITED}
---1ff83de4bdba
Step 5/16 : WORKDIR /src
---Running in 972629766fad
Removing intermediate container 972629766fad
---1325ecd8e7c3
Step 6/16 : COPY ["<projectname>.csproj", "<projectname>/"]
---a4ba463683dc
Step 7/16 : RUN dotnet restore "<projectname>/<projectname>.csproj"
---Running in 82bb9095d412
Restore completed in 14.08 sec for /src/<projectname>/<projectname>.csproj.
Removing intermediate container 82bb9095d412
---7b0cc236782e
Step 8/16 : COPY . .
---884bb695bfb3
Step 9/16 : WORKDIR /src
---Running in 817b001e2060
Removing intermediate container 817b001e2060
---40b8690ecb63
Step 10/16 : RUN dotnet build "<projectname>.csproj" -c Release -o /app
---Running in 48d79b81c3cb
Microsoft (R) Build Engine version 16.0.462+g62fb89029d for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

Restore completed in 531.02 ms for /src/<projectname>.csproj.
/usr/share/dotnet/sdk/3.0.100-preview5-011568/Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.RuntimeIdentifierInference.targets(157,5): message NETSDK1057: You are using a preview version of .NET Core. See: https://aka.ms/dotnet-core-preview [/src/<projectname>.csproj]
/usr/share/dotnet/sdk/3.0.100-preview5-011568/Microsoft.Common.CurrentVersion.targets(4560,5): error MSB3024: Could not copy the file "/src/obj/Release/netcoreapp3.0/<projectname>" to the destination file "/app/<projectname>", because the destination is a folder instead of a file. To copy the source file into a folder, consider using the DestinationFolder parameter instead of DestinationFiles. [/src/<projectname>.csproj]

Build FAILED.

/usr/share/dotnet/sdk/3.0.100-preview5-011568/Microsoft.Common.CurrentVersion.targets(4560,5): **error MSB3024: Could not copy the file "/src/obj/Release/netcoreapp3.0/<projectname>" to the destination file "/app/<projectname>", because the destination is a folder instead of a file. To copy the source file into a folder, consider using the DestinationFolder parameter instead of DestinationFiles. **[/src/<projectname>.csproj]
    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:11.43
The command '/bin/sh -c dotnet build "<projectname>.csproj" -c Release -o /app' returned a non-zero code: 1
##[error]Bash exited with code '1'.
##[section]Finishing: docker build
</code>```

答: I am assuming this is an issue with the .Net Core 3.0 preview5 SDK. I have created the project in .Net Core 2.2 and it build successfully.</p>

Body:
I am attempting to build a .Net Core 3.0 (preview) project in a DevOps build pipeline.

The steps in my azure-pipelines.yml executes up to the "docker build" step, successfully initiating the build process.
The Docker file is read and executed up to the "dotnet build" step after which the following error is thrown.

error MSB3024: Could not copy the file "/src/obj/Release/netcoreapp3.0/" to the destination file "/app/", because the destination is a folder instead of a file. To copy the source file into a folder, consider using the DestinationFolder parameter instead of DestinationFiles. [/src/.csproj]

I have attempted to build locally by executing dotnet build ".csproj" -c Release -o /app
The build then succeeds with 0 errors and 0 warnings. Could this be related to an SDK issue in DevOps?

Any advice would be greatly appreciated.

The build command from my Docker file.

RUN dotnet build "<project>.csproj" -c Release -o /app

--- {OMITED}
---1ff83de4bdba
Step 5/16 : WORKDIR /src
---Running in 972629766fad
Removing intermediate container 972629766fad
---1325ecd8e7c3
Step 6/16 : COPY ["<projectname>.csproj", "<projectname>/"]
---a4ba463683dc
Step 7/16 : RUN dotnet restore "<projectname>/<projectname>.csproj"
---Running in 82bb9095d412
Restore completed in 14.08 sec for /src/<projectname>/<projectname>.csproj.
Removing intermediate container 82bb9095d412
---7b0cc236782e
Step 8/16 : COPY . .
---884bb695bfb3
Step 9/16 : WORKDIR /src
---Running in 817b001e2060
Removing intermediate container 817b001e2060
---40b8690ecb63
Step 10/16 : RUN dotnet build "<projectname>.csproj" -c Release -o /app
---Running in 48d79b81c3cb
Microsoft (R) Build Engine version 16.0.462+g62fb89029d for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

Restore completed in 531.02 ms for /src/<projectname>.csproj.
/usr/share/dotnet/sdk/3.0.100-preview5-011568/Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.RuntimeIdentifierInference.targets(157,5): message NETSDK1057: You are using a preview version of .NET Core. See: https://aka.ms/dotnet-core-preview [/src/<projectname>.csproj]
/usr/share/dotnet/sdk/3.0.100-preview5-011568/Microsoft.Common.CurrentVersion.targets(4560,5): error MSB3024: Could not copy the file "/src/obj/Release/netcoreapp3.0/<projectname>" to the destination file "/app/<projectname>", because the destination is a folder instead of a file. To copy the source file into a folder, consider using the DestinationFolder parameter instead of DestinationFiles. [/src/<projectname>.csproj]

Build FAILED.

/usr/share/dotnet/sdk/3.0.100-preview5-011568/Microsoft.Common.CurrentVersion.targets(4560,5): **error MSB3024: Could not copy the file "/src/obj/Release/netcoreapp3.0/<projectname>" to the destination file "/app/<projectname>", because the destination is a folder instead of a file. To copy the source file into a folder, consider using the DestinationFolder parameter instead of DestinationFiles. **[/src/<projectname>.csproj]
    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:11.43
The command '/bin/sh -c dotnet build "<projectname>.csproj" -c Release -o /app' returned a non-zero code: 1
##[error]Bash exited with code '1'.
##[section]Finishing: docker build


问:
Angular Filter by 2 dates
I need to add a Filter of the Date range. Mean I need to show only that data which user input from the date and to date. I have an array of data in which there is only one date is showing. But I want to filter it like this user input any 2 dates (From and To) And in the array I only that data show which are between input dates.

```<code>   <div class="row">
   <div class="col-12">
     <div class="content-header">Claims Status</div>
       <p class="content-sub-header">Claims Settled 23</p>
   </div>
  </div>

 <section id="extended">

   <div class="row">
     <div class="col-sm-12">
       <div class="card">

    <div class="row" >
     <div class="col-sm bg-primary text-white" style="text-align: center;" ><div>Claims<br>(settled)</div><div *ngIf="statusunsettledcc">  {{statusunsettledcc}}</div></div>
    <div class="col-sm bg-success text-white" style="text-align: center;"><div>Claim Amount<br>(settled)</div><div *ngIf="statusunsettledamount">{{statusunsettledamount | number : fractionSize}}</div></div>
    <div class="col-sm bg-danger text-white" style="text-align: center;" ><div>Claims<br>(unsettled)</div><div *ngIf="status2settledcc">{{status2settledcc}}</div></div>
    <div class="col-sm bg-warning text-white" style="text-align: center;"><div>Claim Amount<br>(unsettled)</div><div *ngIf="status2settledamount">{{status2settledamount | number : fractionSize}}</div></div>
    </div>

  <div class="card-header">
    <div class="card-title-wrap bar-success">
      <h4 class="card-title">Claims</h4>
    </div>
  </div>
  <div class="card-body">
    <div class="card-block">

      <div class="row">
        <div class="col-md-3">
          <div class="form-group" >
            <label for="">Search Name</label>

            <input type="text" class="form-control" [(ngModel)]="userFilter.member_name" placeholder="Search name" name="search">
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group" >
            <label for="">Search Claim No</label>
            <input type="search"
            class="form-control" placeholder="Claim No" [(ngModel)]="userFilter.claim_no">
          </div>
        </div>

   <div class="col-md-3 form-group">
        <input type="date" class="form-control" [(ngModel)]="from"> //From date
    </div>
    <div class="col-md-3 form-group">
        <input type="date" class="form-control" [(ngModel)]="to"> //To Date
    </div>

        <div class="col-md-3" *ngIf="company">
          <div class="form-group">
            <label for="">Company</label>
            <select class="form-control" [(ngModel)]="userFilter.company_id" (change)="getClaims()">
              <option value='' >All</option>
              <option value="999">Airlink Communication</option>
              <option value="637">Ascertia (Pvt) Ltd</option>
              <option value="1053">Frontier Works Organization</option>
              <option value="1174">Ebryx (pvt) Ltd</option>
              <option value="274">HY Enterprises (Pvt) Limited</option>
              <option value="459">Naimat Saleem trust NST (US GROUP)</option>
              <option value="659">Samad Rubber Works (Pvt) Ltd</option>
              <option value="56">Sundry Clients</option>
              <option value="620">TIMEXPERTS (PRIVATE) Limited</option>
              <option value="39">US Apparel & Textile (Pvt) Limited</option>
              <option value="40">US Denim Mills (Pvt) Limited</option>
            </select>
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group">
            <label for="">Claim Status</label>
            <select class="form-control" [(ngModel)]="userFilter.status">
              <option value='' >All</option>

              <option value="submitted">Submitted</option>
              <option value="approved">Approved</option>
              <option value="cancel">Objection Claim</option>
              <option value="settled">Settled</option>
              <option value="rejected">Rejected</option>
              <option value="CLOSED">Closed</option>
              <option value="OUTSTANDING">Outstanding</option>

            </select>
          </div>
        </div>

        <div class="col-md-3" *ngIf="policyclaim">
          <div class="form-group">
           <label for="">Policy</label>
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getClaims()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>
         </div>
       </div>

        <div class="col-md-3" *ngIf="policysamad">
          <div class="form-group">
           <label for="">Policy</label>
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getSamad()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>
         </div>
       </div>

     </div>

     <table class="table table-responsive-md text-center">
      <thead>
        <tr>
          <th>STATUS</th>
          <th>Name</th>
          <th>Patient Name</th>
          <th>Approved Amount</th>
          <th>Claimed Amount</th>
          <th>Company</th>
          <th>Submitted By</th>
          <th>Claim No</th>
          <!-- <th>Website URL</th> -->

        </tr>
      </thead>
      <tbody *ngIf="data1">

        <tr *ngFor="let x of data1 | filterBy: userFilter" (click)="openDeal(deletecontent, x)" >

          <td>
            <span class="text-success" *ngIf="x.status == 'submitted'">Submitted</span>
            <span class="text-primary" *ngIf="x.status == 'settled'">Settled</span>
            <span class="text-warning" *ngIf="x.status == 'rejected'">Rejected</span>
            <span class="text-danger" *ngIf="x.status == 'Approved'">Approved</span>
            <span class="text-danger" *ngIf="x.status == 'ojection claim'">Objection claim</span>

          </td>
          <td >
            <div style="text-align: left;">
              <img [src]="x.userPhoto || 'https://mbtskoudsalg.com/images/user-image-png.png'" class="img-sm" alt="" style="text-align: left;">
              {{x.member_name}}
            </div>
          </td>
          <td style="text-align: left;">{{x.patient_name}}</td>
          <td>{{x.approved_value}}</td>
          <td>{{x.claimed_value}}</td>
          <td>

            <span  class="text-success" *ngIf="x.company_id == '999'" >Airlink Communication</span>
            <span class="text-success" *ngIf="x.company_id == '637'">Ascertia (Pvt) Ltd</span>
            <span *ngIf="x.company_id == '1053'" class="text-success">Frontier Works Organization</span>
            <span *ngIf="x.company_id == '1174'" class="text-success">Ebryx (pvt) Ltd</span>
            <span  *ngIf="x.company_id == '274'" class="text-success">HY Enterprises (Pvt) Limited</span>
            <span *ngIf="x.company_id == '459'" class="text-success">Naimat Saleem trust NST (US GROUP)</span>
            <span *ngIf="x.company_id == '659'" class="text-success">Samad Rubber Works (Pvt) Ltd</span>
            <span *ngIf="x.company_id == '56'" class="text-success">Sundry Clients</span>
            <span *ngIf="x.company_id == '620'" class="text-success">TIMEXPERTS (PRIVATE) Limited</span>
            <span *ngIf="x.company_id == '39'" class="text-success">US Apparel & Textile (Pvt) Limited</span>
            <span *ngIf="x.company_id == '40'" class="text-success">US Denim Mills (Pvt) Limited</span>

          </td>

          <td>{{x.submitted_at || 'not-defined'}}

          </td>
          <td>{{x.claim_no}}</td>

        </tr>
       </tbody>
      </table>
    </div>
   </div>
  </div>
</div>
</div>
</section>
</code>```

.ts

```<code>getClaims(){

this.policyclaim = true;

if(this.userFilter.company_id){
this.url = 'url='+this.userFilter.company_id;

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

  if (this.from && this.to) {
    const fromDate = new Date(this.from.split(/\D/));
    const toDate = new Date(this.to.split(/\D/));
    this.data1.filter(obj => new Date(obj.date) > fromDate && new Date(obj.date) < toDate);
    console.log(this.data1);
  }

else
{
this.url = 'url/get_claims.php?offset=0&limit=50';

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_claims_amt.php?cstatus=OUTSTANDING').subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url/get_claims_amt.php?cstatus=CLOSED').subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url/insurance-api/get_company_policy.php?').subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

this.clientData = this.httpClient.get<any>(this.url).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

if(this.userFilter.policy_id){

let vv = this.data1.filter(v => v.policy_id === this.userFilter.policy_id);
console.log(vv);

this.httpClient.get<any>('http://url='+this.userFilter.policy_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url='+this.userFilter.policy_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_company_policy.php?company_id='+this.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

this.url = 'url/get_claims.php?';

this.clientData = this.httpClient.get<any>(this.url,
{
params: {
policy_id: this.userFilter.policy_id
 },

}).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

});

//const sum1 = vv.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = vv.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = vv.filter((obj) => obj.status === status).length;
//var countunsettled = vv.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

}
//else{

//const sum1 = this.data1.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = this.data1.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = this.data1.filter((obj) => obj.status === status).length;
//var countunsettled = this.data1.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

//}

});

}
</code>```

答: filter you array based on the user dates. prefer any date picker on the input for to and from to pick date objects and avoiding extra overhead. I prefer moment for date comparison and filtering. for faster data filtering also refer cross filter. It is way too fast than normal filtering despite of any length of array.

Title: Angular Filter by 2 dates

Body:
I need to add a Filter of the Date range. Mean I need to show only that data which user input from the date and to date. I have an array of data in which there is only one date is showing. But I want to filter it like this user input any 2 dates (From and To) And in the array I only that data show which are between input dates.

Claims Status

Claims Settled 23

Claims
(settled)

  {{statusunsettledcc}}

Claim Amount
(settled)

{{statusunsettledamount | number : fractionSize}}

Claims
(unsettled)

{{status2settledcc}}

Claim Amount
(unsettled)

{{status2settledamount | number : fractionSize}}

Claims

            Search Name

            <input type="text" class="form-control" [(ngModel)]="userFilter.member_name" placeholder="Search name" name="search">

            Search Claim No
            <input type="search"
            class="form-control" placeholder="Claim No" [(ngModel)]="userFilter.claim_no">

        <input type="date" class="form-control" [(ngModel)]="from"> //From date

        <input type="date" class="form-control" [(ngModel)]="to"> //To Date

            Company
            <select class="form-control" [(ngModel)]="userFilter.company_id" (change)="getClaims()">
              <option value='' >All</option>
              <option value="999">Airlink Communication</option>
              <option value="637">Ascertia (Pvt) Ltd</option>
              <option value="1053">Frontier Works Organization</option>
              <option value="1174">Ebryx (pvt) Ltd</option>
              <option value="274">HY Enterprises (Pvt) Limited</option>
              <option value="459">Naimat Saleem trust NST (US GROUP)</option>
              <option value="659">Samad Rubber Works (Pvt) Ltd</option>
              <option value="56">Sundry Clients</option>
              <option value="620">TIMEXPERTS (PRIVATE) Limited</option>
              <option value="39">US Apparel & Textile (Pvt) Limited</option>
              <option value="40">US Denim Mills (Pvt) Limited</option>
            </select>

            Claim Status
            <select class="form-control" [(ngModel)]="userFilter.status">
              <option value='' >All</option>

              <option value="submitted">Submitted</option>
              <option value="approved">Approved</option>
              <option value="cancel">Objection Claim</option>
              <option value="settled">Settled</option>
              <option value="rejected">Rejected</option>
              <option value="CLOSED">Closed</option>
              <option value="OUTSTANDING">Outstanding</option>

            </select>

           Policy
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getClaims()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>

           Policy
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getSamad()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>

          STATUS
          Name
          Patient Name
          Approved Amount
          Claimed Amount
          Company
          Submitted By
          Claim No

            Submitted
            Settled
            Rejected
            Approved
            Objection claim

              {{x.member_name}}

          {{x.patient_name}}
          {{x.approved_value}}
          {{x.claimed_value}}

            Airlink Communication
            Ascertia (Pvt) Ltd
            Frontier Works Organization
            Ebryx (pvt) Ltd
            HY Enterprises (Pvt) Limited
            Naimat Saleem trust NST (US GROUP)
            Samad Rubber Works (Pvt) Ltd
            Sundry Clients
            TIMEXPERTS (PRIVATE) Limited
            US Apparel & Textile (Pvt) Limited
            US Denim Mills (Pvt) Limited

          {{x.submitted_at || 'not-defined'}}

          {{x.claim_no}}

.ts

getClaims(){

this.policyclaim = true;

if(this.userFilter.company_id){
this.url = 'url='+this.userFilter.company_id;

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

  if (this.from && this.to) {
    const fromDate = new Date(this.from.split(/\D/));
    const toDate = new Date(this.to.split(/\D/));
    this.data1.filter(obj => new Date(obj.date) > fromDate && new Date(obj.date) < toDate);
    console.log(this.data1);
  }

else
{
this.url = 'url/get_claims.php?offset=0&limit=50';

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_claims_amt.php?cstatus=OUTSTANDING').subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url/get_claims_amt.php?cstatus=CLOSED').subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url/insurance-api/get_company_policy.php?').subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

this.clientData = this.httpClient.get<any>(this.url).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

if(this.userFilter.policy_id){

let vv = this.data1.filter(v => v.policy_id === this.userFilter.policy_id);
console.log(vv);

this.httpClient.get<any>('http://url='+this.userFilter.policy_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url='+this.userFilter.policy_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_company_policy.php?company_id='+this.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

this.url = 'url/get_claims.php?';

this.clientData = this.httpClient.get<any>(this.url,
{
params: {
policy_id: this.userFilter.policy_id
 },

}).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

});

//const sum1 = vv.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = vv.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = vv.filter((obj) => obj.status === status).length;
//var countunsettled = vv.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

}
//else{

//const sum1 = this.data1.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = this.data1.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = this.data1.filter((obj) => obj.status === status).length;
//var countunsettled = this.data1.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

//}

});

}


问:
How do I solve fusionauth php client error 'FusionAuthClient' not found?
when I follow https://github.com/FusionAuth/fusionauth-php-client

I can see error:

```<code>PHP Fatal error:  Uncaught Error: Class 'FusionAuthClient' not found ... on line 6
</code>```

My application looks like this:

```<code>  First application
  <?php
  require_once 'FusionAuthClient.php';

  $apiKey = "7W-yBfeXfniDhu8PR_h0dGkSsPDJlpUYuP9rP2xXd_4";
  $client = new FusionAuthClient($apiKey, "http://localhost:9011");
</code>```

line 6 is last.

composer says all is right

```<code>$ composer require fusionauth/fusionauth-client
Using version ^1.6 for fusionauth/fusionauth-client
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing fusionauth/fusionauth-client (1.6.1)
    Downloading: 100%

Writing lock file
Generating autoload files
</code>```

FusionAuthClient.php, ClientResponse.php and RESTClient.php are in the same directory as my test script.

Can you point me into the right direction what is cause of this problem?

答:
That looks the require_once function path is invalid

Do have you same bug when using  "require" and not "require_once"?

Body:
when I follow https://github.com/FusionAuth/fusionauth-php-client

I can see error:

PHP Fatal error:  Uncaught Error: Class 'FusionAuthClient' not found ... on line 6

My application looks like this:

  First application
  <?php
  require_once 'FusionAuthClient.php';

  $apiKey = "7W-yBfeXfniDhu8PR_h0dGkSsPDJlpUYuP9rP2xXd_4";
  $client = new FusionAuthClient($apiKey, "http://localhost:9011");

line 6 is last.

composer says all is right

$ composer require fusionauth/fusionauth-client
Using version ^1.6 for fusionauth/fusionauth-client
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing fusionauth/fusionauth-client (1.6.1)
    Downloading: 100%

Writing lock file
Generating autoload files

FusionAuthClient.php, ClientResponse.php and RESTClient.php are in the same directory as my test script.

Can you point me into the right direction what is cause of this problem?