问:
Can the *ngIf directive prevent that my adminpage is sent to the browsers of unauthorized users?
I know that a certain element or component will not be included in the DOM when the *ngIf directive is set to false. Say I have a component that shows the admin tools and it should only be accessible to authorized users (administrators). Does the ngIf directive set to false prevent the javascript that makes up this component from being sent to the browser of unauthorized users? I am asking this because I don't want anyone unauthorized to be able to see my admin page somehow (maybe by decompiling). So is it available for everyone? And if so, how difficult is it to extract that admin component from the javascript files?

Thanks you,

答:
You should put the admin page in an NgModule and put it on a lazy load path in the Route config. This way it will become a module and package file of its own, and will only be loaded if someone navigates to that page. You should add a route guard (CanLoad) to prevent unauthorised access.

If you really want to go all in, you should also prevent loading of that package file to people who are not logged on or do not have admin access directly from your server


来源: stackexchange

问:
How can i pass parameter to this method
This is the method:

```<code>getUsersList(ref List<RealBioSDKUser> userList,
             int groupId = -1,
             [DateTimeConstant(0), Optional] DateTime fromDate)
</code>```

When I pass the parameters like this :

```<code>List<RealBioSDKUser> tempUserList=new List<RealBioSDKUser>();
BioClient.getUsersList(ref tempUserList,0, "1900-01-01");
</code>```

is shows this error:

the best overloaded method match for collections.generic.list like this.

答:
Because "1900-01-01" is a string, not a DateTime.  Pass a DateTime object instead:

```<code>BioClient.getUsersList(ref tempUserList,0, new DateTime(1900, 1, 1));
</code>```

ContentLicense: CC BY-SA 3.0

Title: How can i pass parameter to this method

Body:
This is the method:

getUsersList(ref List<RealBioSDKUser> userList,
             int groupId = -1,
             [DateTimeConstant(0), Optional] DateTime fromDate)

When I pass the parameters like this :

List<RealBioSDKUser> tempUserList=new List<RealBioSDKUser>();
BioClient.getUsersList(ref tempUserList,0, "1900-01-01");

is shows this error:

the best overloaded method match for collections.generic.list like this.

Body:
Because "1900-01-01" is a string, not a DateTime.  Pass a DateTime object instead:

BioClient.getUsersList(ref tempUserList,0, new DateTime(1900, 1, 1));


问:
Centimeter to pixel
How do I convert centimeter to pixel in c# ?</p>

答:
```<code>int CentimeterToPixel(double Centimeter)
{
    double pixel = -1;
    using (Graphics g = this.CreateGraphics())
    {
        pixel = Centimeter * g.DpiY / 2.54d;
    }
    return (int)pixel;
}</code>```

Title: Centimeter to pixel

ContentLicense: CC BY-SA 2.5


问:
DB2 join optimization with subqueries (NLJOIN vs HSJOIN)
I'm trying to fix the performance of a query I use to count data. On one of the queries the optimizer of DB2 LUW chooses to do a nested loop join instead of an hash join.

The problematic query (Resulting in NLJOIN)

```<code>with
  source1 as (select COALESCE(CAST("LOGICAL_KEY" AS CHARACTER VARYING(4000)), ']#[') as LOGICAL_KEY from "SAMPLE"."SOURCE1"),
  source2 as (select COALESCE(CAST("LOGICAL_KEY" AS CHARACTER VARYING(4000)), ']#[') as LOGICAL_KEY from "SAMPLE"."SOURCE2")
select count(*) from (
  SELECT
    "a"."LOGICAL_KEY",
    "b"."LOGICAL_KEY"
  FROM
   source1 "a",
   source2 "b"
 WHERE
   "a"."LOGICAL_KEY" =
   "b"."LOGICAL_KEY"
);
</code>```

However when I create a table of the subqueries first, the optimizer performs an hash join.

The optimized Query (Resulting in HSJOIN)

```<code>CREATE TABLE "SAMPLE"."TMP_SOURCE1" ("LOGICAL_KEY" VARCHAR(4000 BYTE));
CREATE TABLE "SAMPLE"."TMP_SOURCE2" ("LOGICAL_KEY" VARCHAR(4000 BYTE));

insert into "SAMPLE"."TMP_SOURCE1" select COALESCE(CAST("LOGICAL_KEY" AS CHARACTER VARYING(4000)), ']#[') LOGICAL_KEY from "SAMPLE"."SOURCE1";
insert into "SAMPLE"."TMP_SOURCE2" select COALESCE(CAST("LOGICAL_KEY" AS CHARACTER VARYING(4000)), ']#[') LOGICAL_KEY from "SAMPLE"."SOURCE2";

select count(*) from (
  SELECT
    "a"."LOGICAL_KEY",
    "b"."LOGICAL_KEY"
  FROM
    (select * from "SAMPLE"."TMP_SOURCE1") "a",
    (select * from "SAMPLE"."TMP_SOURCE2") "b"
  WHERE
    "a"."LOGICAL_KEY" =
    "b"."LOGICAL_KEY"
);
</code>```

How come that DB2 chooses different paths for the same data? Is there any way to force the structure with a subquery to perform an hash join? Due to privilege restrictions I'm not able to create tables.

答: Fundamentally you are not comparing apples with apples. In your first scenario building tables a and b is being done as part of the query and the optimiser includes this work as part of its' whole join strategy. Since it has to build the tables in memory an NLjoin scanning them is not too much extra work. In the second scenario the optimiser considers a join between two existing tables with an equivalence predicate and finds that HSjoin is the way to go. </p>

Body:
I'm trying to fix the performance of a query I use to count data. On one of the queries the optimizer of DB2 LUW chooses to do a nested loop join instead of an hash join.

The problematic query (Resulting in NLJOIN)

with
  source1 as (select COALESCE(CAST("LOGICAL_KEY" AS CHARACTER VARYING(4000)), ']#[') as LOGICAL_KEY from "SAMPLE"."SOURCE1"),
  source2 as (select COALESCE(CAST("LOGICAL_KEY" AS CHARACTER VARYING(4000)), ']#[') as LOGICAL_KEY from "SAMPLE"."SOURCE2")
select count(*) from (
  SELECT
    "a"."LOGICAL_KEY",
    "b"."LOGICAL_KEY"
  FROM
   source1 "a",
   source2 "b"
 WHERE
   "a"."LOGICAL_KEY" =
   "b"."LOGICAL_KEY"
);

However when I create a table of the subqueries first, the optimizer performs an hash join.

The optimized Query (Resulting in HSJOIN)

CREATE TABLE "SAMPLE"."TMP_SOURCE1" ("LOGICAL_KEY" VARCHAR(4000 BYTE));
CREATE TABLE "SAMPLE"."TMP_SOURCE2" ("LOGICAL_KEY" VARCHAR(4000 BYTE));

insert into "SAMPLE"."TMP_SOURCE1" select COALESCE(CAST("LOGICAL_KEY" AS CHARACTER VARYING(4000)), ']#[') LOGICAL_KEY from "SAMPLE"."SOURCE1";
insert into "SAMPLE"."TMP_SOURCE2" select COALESCE(CAST("LOGICAL_KEY" AS CHARACTER VARYING(4000)), ']#[') LOGICAL_KEY from "SAMPLE"."SOURCE2";

select count(*) from (
  SELECT
    "a"."LOGICAL_KEY",
    "b"."LOGICAL_KEY"
  FROM
    (select * from "SAMPLE"."TMP_SOURCE1") "a",
    (select * from "SAMPLE"."TMP_SOURCE2") "b"
  WHERE
    "a"."LOGICAL_KEY" =
    "b"."LOGICAL_KEY"
);

How come that DB2 chooses different paths for the same data? Is there any way to force the structure with a subquery to perform an hash join? Due to privilege restrictions I'm not able to create tables.


问:
Eigen vectors in python giving seemingly random element-wise signs
I'm running the following code:

```<code>import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt

N = 100
t = 1

a1 = np.full((N-1,), -t)
a2 = np.full((N,), 2*t)
Hamiltonian = np.diag(a1, -1) +  np.diag(a2) + np.diag(a1, 1)

eval, evec = np.linalg.eig(Hamiltonian)
idx = eval.argsort()[::-1]
eval, evec = eval[idx], evec[:,idx]

wave2 = evec[2] / np.sum(abs(evec[2]))
prob2 = evec[2]**2 / np.sum(evec[2]**2)

_ = plt.plot(wave2)
_ = plt.plot(prob2)
plt.show()
</code>```

And the plot that comes out is this:

But I'd expect the blue line to be a sinoid as well. This has got me confused and I can't find what's causing the sudden sign changes. Plotting the function absolutely shows that the values associated with each x are fine, but the signs are screwed up.

Any ideas on what might cause this or how to solve it?

答:
I may be wrong, but aren't they all valid eigen vectors/values?  The sign shouldn't matter, as the definition of an eigen vector is:

In linear algebra, an eigenvector or characteristic vector of a linear transformation is a non-zero vector that only changes by an overall scale when that linear transformation is applied to it.

Just because the scale is negative doesn't mean it isn't valid.

See this post about Matlab's eig that has a similar problem

One way to fix this is to simply pick a sign for the start, and multiply everthing by -1 that doesn't fit that sign (or take abs of every element and multiply by your expected sign).  For your results this should work (nothing crosses 0).

Neither matlab nor numpy care about what you are trying to solve, its simple mathematics that dictates that both signed eigenvector/value combinations are valid, your values are sinusoidal, its just that there exists two sets of eigenvector/values that work (negative and positive)

Body:
I'm running the following code:

import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt

N = 100
t = 1

a1 = np.full((N-1,), -t)
a2 = np.full((N,), 2*t)
Hamiltonian = np.diag(a1, -1) +  np.diag(a2) + np.diag(a1, 1)

eval, evec = np.linalg.eig(Hamiltonian)
idx = eval.argsort()[::-1]
eval, evec = eval[idx], evec[:,idx]

wave2 = evec[2] / np.sum(abs(evec[2]))
prob2 = evec[2]**2 / np.sum(evec[2]**2)

_ = plt.plot(wave2)
_ = plt.plot(prob2)
plt.show()

And the plot that comes out is this:

But I'd expect the blue line to be a sinoid as well. This has got me confused and I can't find what's causing the sudden sign changes. Plotting the function absolutely shows that the values associated with each x are fine, but the signs are screwed up.

Any ideas on what might cause this or how to solve it?


问:
android constrain layout support different screen size
Dears am trying to use constrain layout with percentage to support different screen sizes its working fine if am only using pictures or button but when i add text its not appearing on small screen even though i add it as match parent with center gravity.
i added the xml code..
can you help me if i can use this method to support different screen sizes or i have to create different xml files.

EDIT I

The screen sizes is LDPI API 22 240 × 320: ldpi 22 Android 5.1 (Google APIs) and MDPI Small API 22 320 × 480: mdpi 22 Android 5.1 (Google APIs)

The Layout:

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/green_background"
tools:context="com.yaacoach.gymapp.StartExercise">

<android.support.constraint.Guideline
    android:id="@+id/guideline16"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.18" />

<android.support.constraint.Guideline
    android:id="@+id/guideline36"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.2" />

<android.support.constraint.Guideline
    android:id="@+id/guideline37"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.8" />

<android.support.constraint.Guideline
    android:id="@+id/guideline38"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.03" />

<android.support.constraint.Guideline
    android:id="@+id/guideline40"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.08" />

<android.support.constraint.Guideline
    android:id="@+id/guideline41"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.92" />

<android.support.constraint.Guideline
    android:id="@+id/guideline42"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.27" />

<Button
    android:id="@+id/btn_start"
    style="@style/Base.TextAppearance.AppCompat.Medium"
    android:gravity="center"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="start"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.833" />

<android.support.constraint.Guideline
    android:id="@+id/guideline43"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.93" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_startExercise_information"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline39"
    app:layout_constraintEnd_toStartOf="@+id/guideline41"
    app:layout_constraintStart_toStartOf="@+id/guideline40"
    app:layout_constraintTop_toTopOf="@+id/guideline42" />

<android.support.constraint.Guideline
    android:id="@+id/guideline39"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.86" />

<android.support.constraint.Guideline
    android:id="@+id/guideline45"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.25" />

<android.support.constraint.ConstraintLayout
    android:id="@+id/CL_stopWatch"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@drawable/stopwatchstyle"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    android:foregroundGravity="center"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38"
    app:layout_constraintVertical_bias="1.0">

</android.support.constraint.ConstraintLayout>

<Chronometer
    android:id="@+id/chronometer2"
    style="@android:style/TextAppearance.DeviceDefault.Medium"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:textColor="@color/btnbrainiac"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/guideline46"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38" />

<android.support.constraint.Guideline
    android:id="@+id/guideline46"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.11" />

<android.support.constraint.Guideline
    android:id="@+id/guideline47"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.4" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_start_exercise_weight_rep"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView2"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/Weight"
    app:layout_constraintBottom_toTopOf="@+id/guideline16"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView4"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/repetition"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline16" />

<Button
    android:id="@+id/btn_StartExercies_Pause"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="Button"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.0" />
</code>```

答:
I pasted the Layout in Android Studio and I see it rendering ok.
Note I replaced the colors and strings as I didn't have you resource files.

The image below is your layout for the LDPI display you mentioned.

Anyway here I leave you an alternative way you can reach the same layout with less guidelines and less constrained elements.

Layout:

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    >

    <android.support.constraint.Guideline
        android:id="@+id/glTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.03" />

    <android.support.constraint.Guideline
        android:id="@+id/glBottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.93" />

    <android.support.constraint.Guideline
        android:id="@+id/glLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.08" />

    <android.support.constraint.Guideline
        android:id="@+id/glRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.92" />

    <android.support.constraint.Guideline
        android:id="@+id/glChronoLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.2" />

    <android.support.constraint.Guideline
        android:id="@+id/glChronoRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.8" />

    <LinearLayout
        android:id="@+id/chronometerContainer"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"

        app:layout_constraintEnd_toStartOf="@+id/glChronoRight"
        app:layout_constraintStart_toStartOf="@+id/glChronoLeft"
        app:layout_constraintTop_toTopOf="@+id/glTop">
        <Chronometer
            android:id="@+id/chronometer2"
            style="@android:style/TextAppearance.DeviceDefault.Medium"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textColor="000000"
            android:textStyle="bold"
             />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="12">
            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="4"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:background="#FF0000">
                <TextView
                    android:id="@+id/textView2"
                    style="@android:style/TextAppearance.DeviceDefault.Small"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Weight" />
                <TextView
                    android:id="@+id/textView4"
                    style="@android:style/TextAppearance.DeviceDefault.Small"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Repet" />
            </LinearLayout>
            <android.support.v7.widget.RecyclerView
                android:id="@+id/rv_startExercise_information"
                android:layout_width="0dp"
                android:layout_weight="8"
                android:layout_height="match_parent"/>
        </LinearLayout>
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_start_exercise_weight_rep"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"

        app:layout_constraintStart_toEndOf="@+id/glLeft"
        app:layout_constraintBottom_toTopOf="@+id/btnContainer"
        app:layout_constraintEnd_toStartOf="@+id/glRight"
        app:layout_constraintTop_toBottomOf="@+id/chronometerContainer" />

    <LinearLayout
        android:id="@+id/btnContainer"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="12"

        app:layout_constraintStart_toStartOf="@id/glChronoLeft"
        app:layout_constraintEnd_toEndOf="@+id/glChronoRight"
        app:layout_constraintBottom_toTopOf="@+id/glBottom">

        <Button
            android:id="@+id/btn_start"
            style="@style/Base.TextAppearance.AppCompat.Medium"
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_weight="6"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:background="#FF0000"
            android:layout_margin="1px"
            android:text="start" />

        <Button
            android:id="@+id/btn_StartExercies_Pause"
            style="@style/Base.TextAppearance.AppCompat.Medium"
            android:layout_width="0dp"
            android:layout_weight="6"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:background="#FF0000"
            android:layout_margin="1px"
            android:text="Button"
             />

    </LinearLayout>

</android.support.constraint.ConstraintLayout>
</code>```

Body:
Dears am trying to use constrain layout with percentage to support different screen sizes its working fine if am only using pictures or button but when i add text its not appearing on small screen even though i add it as match parent with center gravity.
i added the xml code..
can you help me if i can use this method to support different screen sizes or i have to create different xml files.

EDIT I

The screen sizes is LDPI API 22 240 × 320: ldpi 22 Android 5.1 (Google APIs) and MDPI Small API 22 320 × 480: mdpi 22 Android 5.1 (Google APIs)

The Layout:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/green_background"
tools:context="com.yaacoach.gymapp.StartExercise">

<android.support.constraint.Guideline
    android:id="@+id/guideline16"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.18" />

<android.support.constraint.Guideline
    android:id="@+id/guideline36"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.2" />

<android.support.constraint.Guideline
    android:id="@+id/guideline37"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.8" />

<android.support.constraint.Guideline
    android:id="@+id/guideline38"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.03" />

<android.support.constraint.Guideline
    android:id="@+id/guideline40"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.08" />

<android.support.constraint.Guideline
    android:id="@+id/guideline41"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.92" />

<android.support.constraint.Guideline
    android:id="@+id/guideline42"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.27" />

<Button
    android:id="@+id/btn_start"
    style="@style/Base.TextAppearance.AppCompat.Medium"
    android:gravity="center"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="start"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.833" />

<android.support.constraint.Guideline
    android:id="@+id/guideline43"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.93" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_startExercise_information"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline39"
    app:layout_constraintEnd_toStartOf="@+id/guideline41"
    app:layout_constraintStart_toStartOf="@+id/guideline40"
    app:layout_constraintTop_toTopOf="@+id/guideline42" />

<android.support.constraint.Guideline
    android:id="@+id/guideline39"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.86" />

<android.support.constraint.Guideline
    android:id="@+id/guideline45"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.25" />

<android.support.constraint.ConstraintLayout
    android:id="@+id/CL_stopWatch"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@drawable/stopwatchstyle"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    android:foregroundGravity="center"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38"
    app:layout_constraintVertical_bias="1.0">

</android.support.constraint.ConstraintLayout>

<Chronometer
    android:id="@+id/chronometer2"
    style="@android:style/TextAppearance.DeviceDefault.Medium"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:textColor="@color/btnbrainiac"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/guideline46"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38" />

<android.support.constraint.Guideline
    android:id="@+id/guideline46"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.11" />

<android.support.constraint.Guideline
    android:id="@+id/guideline47"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.4" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_start_exercise_weight_rep"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView2"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/Weight"
    app:layout_constraintBottom_toTopOf="@+id/guideline16"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView4"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/repetition"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline16" />

<Button
    android:id="@+id/btn_StartExercies_Pause"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="Button"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.0" />

Body:
I pasted the Layout in Android Studio and I see it rendering ok.
Note I replaced the colors and strings as I didn't have you resource files.

The image below is your layout for the LDPI display you mentioned.

Anyway here I leave you an alternative way you can reach the same layout with less guidelines and less constrained elements.

Layout:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    >

    <android.support.constraint.Guideline
        android:id="@+id/glTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.03" />

    <android.support.constraint.Guideline
        android:id="@+id/glBottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.93" />

    <android.support.constraint.Guideline
        android:id="@+id/glLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.08" />

    <android.support.constraint.Guideline
        android:id="@+id/glRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.92" />

    <android.support.constraint.Guideline
        android:id="@+id/glChronoLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.2" />

    <android.support.constraint.Guideline
        android:id="@+id/glChronoRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.8" />

    <LinearLayout
        android:id="@+id/chronometerContainer"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"

        app:layout_constraintEnd_toStartOf="@+id/glChronoRight"
        app:layout_constraintStart_toStartOf="@+id/glChronoLeft"
        app:layout_constraintTop_toTopOf="@+id/glTop">
        <Chronometer
            android:id="@+id/chronometer2"
            style="@android:style/TextAppearance.DeviceDefault.Medium"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textColor="000000"
            android:textStyle="bold"
             />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="12">
            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="4"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:background="#FF0000">
                <TextView
                    android:id="@+id/textView2"
                    style="@android:style/TextAppearance.DeviceDefault.Small"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Weight" />
                <TextView
                    android:id="@+id/textView4"
                    style="@android:style/TextAppearance.DeviceDefault.Small"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Repet" />
            </LinearLayout>
            <android.support.v7.widget.RecyclerView
                android:id="@+id/rv_startExercise_information"
                android:layout_width="0dp"
                android:layout_weight="8"
                android:layout_height="match_parent"/>
        </LinearLayout>
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_start_exercise_weight_rep"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"

        app:layout_constraintStart_toEndOf="@+id/glLeft"
        app:layout_constraintBottom_toTopOf="@+id/btnContainer"
        app:layout_constraintEnd_toStartOf="@+id/glRight"
        app:layout_constraintTop_toBottomOf="@+id/chronometerContainer" />

    <LinearLayout
        android:id="@+id/btnContainer"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="12"

        app:layout_constraintStart_toStartOf="@id/glChronoLeft"
        app:layout_constraintEnd_toEndOf="@+id/glChronoRight"
        app:layout_constraintBottom_toTopOf="@+id/glBottom">

        <Button
            android:id="@+id/btn_start"
            style="@style/Base.TextAppearance.AppCompat.Medium"
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_weight="6"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:background="#FF0000"
            android:layout_margin="1px"
            android:text="start" />

        <Button
            android:id="@+id/btn_StartExercies_Pause"
            style="@style/Base.TextAppearance.AppCompat.Medium"
            android:layout_width="0dp"
            android:layout_weight="6"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:background="#FF0000"
            android:layout_margin="1px"
            android:text="Button"
             />

    </LinearLayout>

</android.support.constraint.ConstraintLayout>


问:
Manipulate CSS of class that is to be added after DOM load
I have a news scroller which is created by appending lis from an array to a ul element. I am making it scroll via the following function:

```<code>$newsItem = $('.news-item');

function newsScroll() {
  $newsItem.eq(currentNewsItem).fadeIn(1000);
  setTimeout(function() {
    $newsItem.eq(currentNewsItem).addClass('move-left');
  }, 2000);
}
</code>```

It adds .move-left class to li where .move-left has CSS rules:

```<code>.move-left {
  -webkit-transition: 5s;
  -moz-transition: 5s;
  -ms-transition: 5s;
  -o-transition: 5s;
  transition: 5s;
  left: -400px;
}
</code>```

The problem is that all the news items are not the same length; some of them exceed the 400px. Thus moving them 400px left, doesn't scroll them out of the display of the scroller.

So I have used the following code to determine the width of the longest of these elements, but I am unsure how to affix this to the class .move-left, or how to alter a class that is not a part of the DOM.

```<code>var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
  return $(this).outerWidth(true);
}).get());
</code>```

Any suggestions?

答:
Partially based on the suggestion of @HimanshuUpadhyay, I altered the style of the body tag via the attr function, including a CSS var like so:

```<code>$('body').attr('style',"--amtLeft:"+moveLeftAmt);
</code>```

which I then referenced in the stylesheet:

```<code>.move-left {
  -webkit-transition: 5s;
  -moz-transition: 5s;
  -ms-transition: 5s;
  -o-transition: 5s;
  transition: 5s;
  left: var(--amtLeft) !important;
}
</code>```

Works like a charm!

I should note that

```<code>var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
  return $(this).outerWidth(true);
}).get());
</code>```

simply returns a number, so to use it in this way I had to declare another variable that adds the "px" to the end.

Body:
I have a news scroller which is created by appending lis from an array to a ul element. I am making it scroll via the following function:

$newsItem = $('.news-item');

function newsScroll() {
  $newsItem.eq(currentNewsItem).fadeIn(1000);
  setTimeout(function() {
    $newsItem.eq(currentNewsItem).addClass('move-left');
  }, 2000);
}

It adds .move-left class to li where .move-left has CSS rules:

.move-left {
  -webkit-transition: 5s;
  -moz-transition: 5s;
  -ms-transition: 5s;
  -o-transition: 5s;
  transition: 5s;
  left: -400px;
}

The problem is that all the news items are not the same length; some of them exceed the 400px. Thus moving them 400px left, doesn't scroll them out of the display of the scroller.

So I have used the following code to determine the width of the longest of these elements, but I am unsure how to affix this to the class .move-left, or how to alter a class that is not a part of the DOM.

var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
  return $(this).outerWidth(true);
}).get());

Any suggestions?

Body:
Partially based on the suggestion of @HimanshuUpadhyay, I altered the style of the body tag via the attr function, including a CSS var like so:

$('body').attr('style',"--amtLeft:"+moveLeftAmt);

which I then referenced in the stylesheet:

.move-left {
  -webkit-transition: 5s;
  -moz-transition: 5s;
  -ms-transition: 5s;
  -o-transition: 5s;
  transition: 5s;
  left: var(--amtLeft) !important;
}

Works like a charm!

I should note that

var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
  return $(this).outerWidth(true);
}).get());

simply returns a number, so to use it in this way I had to declare another variable that adds the "px" to the end.


问:
Extracting JSON-data from CSV file
I'm trying to extract a JSON data which is a column in a CSV file. So far I've come to the point where I've extracted the column in the right format, but the formatting is only correct when the variable type is factor. But I can't convert a factor to a json-file using the jsonlite package.

```<code>[1] {"id":509746197991998767,"visibility":{"percentage":100,"time":149797,"visible1":true,"visible2":false,"visible3":false,"activetab":true},"interaction":{"mouseovercount":1,"mouseovertime":1426,"videoplaytime":0,"engagementtime":0,"expandtime":0,"exposuretime":35192}}
</code>```

Another approach is to use stringsAsFactors = F when importing, but I'm struggling in getting the formatting right, where each entry looks like this:

```<code>[1] "{\"id\":509746197991998767,\"visibility\":{\"percentage\":100,\"time\":149797,\"visible1\":true,\"visible2\":false,\"visible3\":false,\"activetab\":true},\"interaction\":{\"mouseovercount\":1,\"mouseovertime\":1426,\"videoplaytime\":0,\"engagementtime\":0,\"expandtime\":0,\"exposuretime\":35192}}"
</code>```

Am I missing something obvious here? I simply just want to exract the JSON files that sits inside a CSV file.

Heres a small example of the CSV file:

```<code>"","CookieID","UnloadVars"
"1",-8857188784608690176,"{""id"":509746197991998767,""visibility"":{""percentage"":100,""time"":149797,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":1,""mouseovertime"":1426,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":35192}}"
"2",-1695626857458244096,"{""id"":2917654329769114342,""visibility"":{""percentage"":46,""time"":0,""visible1"":false,""visible2"":false,""visible3"":false,""activetab"":true}}"
"3",437299165071669184,"{""id"":2252707957388071809,""visibility"":{""percentage"":99,""time"":10168,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":542},""clicks"":[{""x"":105,""y"":449}]}"
"4",292660729552227520,""
"5",7036383942916227072,"{""id"":2299674593327687292,""visibility"":{""percentage"":76,""time"":1145,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":74},""clicks"":[{""x"":197,""y"":135},{""x"":197,""y"":135}]}"
</code>```

Regards,

Frederik.

答:
I used readr::read_csv to read in your sample data set.

```<code>> df <- readr::read_csv('~/sample.csv')
Parsed with column specification:
cols(
  CookieID = col_double(),
  UnloadVars = col_character()
)
</code>```

As you can see the UnloadVars are read in as characters and not factors. If I now examine the first value in the UnloadVars columns I see the following which matches what you get,

```<code>> df$UnloadVars[1]
[1] "{\"id\":509746197991998767,\"visibility\":{\"percentage\":100,\"time\":149797,\"visible1\":true,\"visible2\":false,\"visible3\":false,\"activetab\":true},\"interaction\":{\"mouseovercount\":1,\"mouseovertime\":1426,\"videoplaytime\":0,\"engagementtime\":0,\"expandtime\":0,\"exposuretime\":35192}}"
</code>```

Now, I use jsonlite::fromJSON,

```<code>> j <- jsonlite::fromJSON(df$UnloadVars[1])
> j
$id
[1] 5.097462e+17

$visibility
$visibility$percentage
[1] 100

$visibility$time
[1] 149797

$visibility$visible1
[1] TRUE

$visibility$visible2
[1] FALSE

$visibility$visible3
[1] FALSE

$visibility$activetab
[1] TRUE

$interaction
$interaction$mouseovercount
[1] 1

$interaction$mouseovertime
[1] 1426

$interaction$videoplaytime
[1] 0

$interaction$engagementtime
[1] 0

$interaction$expandtime
[1] 0

$interaction$exposuretime
[1] 35192
</code>```

Which I believe is what you need since JSONs are parsed as lists in R.

Title: Extracting JSON-data from CSV file

Body:
I'm trying to extract a JSON data which is a column in a CSV file. So far I've come to the point where I've extracted the column in the right format, but the formatting is only correct when the variable type is factor. But I can't convert a factor to a json-file using the jsonlite package.

[1] {"id":509746197991998767,"visibility":{"percentage":100,"time":149797,"visible1":true,"visible2":false,"visible3":false,"activetab":true},"interaction":{"mouseovercount":1,"mouseovertime":1426,"videoplaytime":0,"engagementtime":0,"expandtime":0,"exposuretime":35192}}

Another approach is to use stringsAsFactors = F when importing, but I'm struggling in getting the formatting right, where each entry looks like this:

[1] "{\"id\":509746197991998767,\"visibility\":{\"percentage\":100,\"time\":149797,\"visible1\":true,\"visible2\":false,\"visible3\":false,\"activetab\":true},\"interaction\":{\"mouseovercount\":1,\"mouseovertime\":1426,\"videoplaytime\":0,\"engagementtime\":0,\"expandtime\":0,\"exposuretime\":35192}}"

Am I missing something obvious here? I simply just want to exract the JSON files that sits inside a CSV file.

Heres a small example of the CSV file:

"","CookieID","UnloadVars"
"1",-8857188784608690176,"{""id"":509746197991998767,""visibility"":{""percentage"":100,""time"":149797,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":1,""mouseovertime"":1426,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":35192}}"
"2",-1695626857458244096,"{""id"":2917654329769114342,""visibility"":{""percentage"":46,""time"":0,""visible1"":false,""visible2"":false,""visible3"":false,""activetab"":true}}"
"3",437299165071669184,"{""id"":2252707957388071809,""visibility"":{""percentage"":99,""time"":10168,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":542},""clicks"":[{""x"":105,""y"":449}]}"
"4",292660729552227520,""
"5",7036383942916227072,"{""id"":2299674593327687292,""visibility"":{""percentage"":76,""time"":1145,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":74},""clicks"":[{""x"":197,""y"":135},{""x"":197,""y"":135}]}"

Regards,

Frederik.

Body:
I used readr::read_csv to read in your sample data set.

> df <- readr::read_csv('~/sample.csv')
Parsed with column specification:
cols(
  CookieID = col_double(),
  UnloadVars = col_character()
)

As you can see the UnloadVars are read in as characters and not factors. If I now examine the first value in the UnloadVars columns I see the following which matches what you get,

> df$UnloadVars[1]
[1] "{\"id\":509746197991998767,\"visibility\":{\"percentage\":100,\"time\":149797,\"visible1\":true,\"visible2\":false,\"visible3\":false,\"activetab\":true},\"interaction\":{\"mouseovercount\":1,\"mouseovertime\":1426,\"videoplaytime\":0,\"engagementtime\":0,\"expandtime\":0,\"exposuretime\":35192}}"

Now, I use jsonlite::fromJSON,

> j <- jsonlite::fromJSON(df$UnloadVars[1])
> j
$id
[1] 5.097462e+17

$visibility
$visibility$percentage
[1] 100

$visibility$time
[1] 149797

$visibility$visible1
[1] TRUE

$visibility$visible2
[1] FALSE

$visibility$visible3
[1] FALSE

$visibility$activetab
[1] TRUE

$interaction
$interaction$mouseovercount
[1] 1

$interaction$mouseovertime
[1] 1426

$interaction$videoplaytime
[1] 0

$interaction$engagementtime
[1] 0

$interaction$expandtime
[1] 0

$interaction$exposuretime
[1] 35192

Which I believe is what you need since JSONs are parsed as lists in R.


问:
com.sun.xml.internal.ws.client does not exist
I'm trying to catch ClientTransportException and my program fails on compilation stage with the following exception

```<code>[ERROR]\workspace\rates\java\service\bundle1\src\main\java\com\connector\ws\TestClass1.java:[72,70] package com.sun.xml.internal.ws.client does not exist
</code>```

As I know this package is from rt.jar and exist in jre

If I add @SuppressWarnings("restriction") it compiles from Eclipse Maven Plugin, but not from IntelliJ Idea(via maven) or command line neither.

When I remove @SuppressWarnings Eclipse show the following warning

```<code>Access restriction: The type ClientTransportException is not accessible due to restriction on required library C:\Program Files\Java\jre6\lib\rt.jar
</code>```

I've found similar question but it's answer isn't clear enough for me cause I can this class in rt.jar and my IntelliJ Idea can see it either.

Can someone explain such behavior and possible solution for it?

答:
You should not use com.sun.* packages.
We could solve the problem by using our own class instead:

```<code>/**
 * Copy of com.sun.xml.internal.ws.client.BindingProviderProperties since we're
 * not allowed to use com.sun.* packages..
 */
public final class BindingProviderProperties {
    public static final java.lang.String CONNECT_TIMEOUT = "com.sun.xml.internal.ws.connect.timeout";
    public static final java.lang.String REQUEST_TIMEOUT = "com.sun.xml.internal.ws.request.timeout";
}
</code>```

Body:
I'm trying to catch ClientTransportException and my program fails on compilation stage with the following exception

[ERROR]\workspace\rates\java\service\bundle1\src\main\java\com\connector\ws\TestClass1.java:[72,70] package com.sun.xml.internal.ws.client does not exist

As I know this package is from rt.jar and exist in jre

If I add @SuppressWarnings("restriction") it compiles from Eclipse Maven Plugin, but not from IntelliJ Idea(via maven) or command line neither.

When I remove @SuppressWarnings Eclipse show the following warning

Access restriction: The type ClientTransportException is not accessible due to restriction on required library C:\Program Files\Java\jre6\lib\rt.jar

I've found similar question but it's answer isn't clear enough for me cause I can this class in rt.jar and my IntelliJ Idea can see it either.

Can someone explain such behavior and possible solution for it?

Body:
You should not use com.sun.* packages.
We could solve the problem by using our own class instead:

/**
 * Copy of com.sun.xml.internal.ws.client.BindingProviderProperties since we're
 * not allowed to use com.sun.* packages..
 */
public final class BindingProviderProperties {
    public static final java.lang.String CONNECT_TIMEOUT = "com.sun.xml.internal.ws.connect.timeout";
    public static final java.lang.String REQUEST_TIMEOUT = "com.sun.xml.internal.ws.request.timeout";
}


问:
React Router 4 <Link> tag updates URL but component is not being rendered to the page
I'm trying to set up login functionality for my react app. Once the user lands on the Login page it has a button on the bottom saying "Sign up". When I click on that link it updates the URL properly and says "/register" in the URL but the Register Component is not rendering. In more traditional routing I would set up a route config that would dictate where all the routes go but from my understanding react router 4 is moving away from that. From reading the docs and some examples I figured simply putting
    Route path="/register" component={Register}
would be enough to tell the Link tag what component to render but that does not seem to be the case. I am using "react-router": "^4.2.0"

Login.js

```<code>import React from 'react';
import LoginForm from '../components/LoginForm';

const Login = () => (
  <div>
    <LoginForm></LoginForm>
  </div>
);

export default Login;
</code>```

LoginForm.js

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { Link, Route } from 'react-router-dom';
import Register from "../pages/Register";

class LoginForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: ''
    }
  }

  onSubmit(e) {
    e.preventDefault();

    this.setState({
      error: 'Something went wrong.'
    })
  }

  render() {
    return (
      <form>
        { this.state.error ? <p>{this.state.error}</p> : undefined }
        <TextField type="email" name="email" hintText="Email" fullWidth={true} />
        <TextField type="password" name="password" hintText="Password" fullWidth={true} />
        <RaisedButton label="Login" primary={true} style={buttonStyles} onClick={this.onSubmit.bind(this)} />
        <p style={text}>No account?<Link to="/register"> Sign up</Link></p>

        <Route path="/register" component={Register}></Route>
      </form>
    )
  }
}

export default LoginForm;
</code>```

Register.js

```<code>import React from 'react';
import RegisterForm from '../components/RegisterForm';

const Register = () => (
    <div>
        <RegisterForm></RegisterForm>
    </div>
);

export default Register;
</code>```

RegisterForm.js

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { Link } from 'react-router-dom';

class RegisterForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: ''
        }
    }

    onSubmit(e) {
        e.preventDefault();

        this.setState({
            error: 'Something went wrong.'
        })
    }

    render() {
        return (
            <form>
                { this.state.error ? <p>{this.state.error}</p> : undefined }
                <TextField type="name" name="name" hintText="Name" fullWidth={true} />
                <TextField type="email" name="email" hintText="Email" fullWidth={true} />
                <TextField type="password" name="password" hintText="Password" fullWidth={true} />
                <RaisedButton label="Register" primary={true} onClick={this.onSubmit.bind(this)} />
            </form>
        )
    }
}

export default RegisterForm;
</code>```

答:
You should specified register path in your router like <Route path="/register" component={YourComponent} />

```<code><Switch>
   <Route exact path="/" component={Root} />
   <Route path="/register" component={Register} />
</Switch>
</code>```

Body:
I'm trying to set up login functionality for my react app. Once the user lands on the Login page it has a button on the bottom saying "Sign up". When I click on that link it updates the URL properly and says "/register" in the URL but the Register Component is not rendering. In more traditional routing I would set up a route config that would dictate where all the routes go but from my understanding react router 4 is moving away from that. From reading the docs and some examples I figured simply putting
    Route path="/register" component={Register}
would be enough to tell the Link tag what component to render but that does not seem to be the case. I am using "react-router": "^4.2.0"

Login.js

import React from 'react';
import LoginForm from '../components/LoginForm';

const Login = () => (

    <LoginForm></LoginForm>

);

export default Login;

LoginForm.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { Link, Route } from 'react-router-dom';
import Register from "../pages/Register";

class LoginForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: ''
    }
  }

  onSubmit(e) {
    e.preventDefault();

    this.setState({
      error: 'Something went wrong.'
    })
  }

  render() {
    return (
      <form>
        { this.state.error ?
{this.state.error}
 : undefined }
        <TextField type="email" name="email" hintText="Email" fullWidth={true} />
        <TextField type="password" name="password" hintText="Password" fullWidth={true} />
        <RaisedButton label="Login" primary={true} style={buttonStyles} onClick={this.onSubmit.bind(this)} />

No account?<Link to="/register"> Sign up</Link>

        <Route path="/register" component={Register}></Route>
      </form>
    )
  }
}

export default LoginForm;

Register.js

import React from 'react';
import RegisterForm from '../components/RegisterForm';

const Register = () => (

        <RegisterForm></RegisterForm>

);

export default Register;

RegisterForm.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { Link } from 'react-router-dom';

class RegisterForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: ''
        }
    }

    onSubmit(e) {
        e.preventDefault();

        this.setState({
            error: 'Something went wrong.'
        })
    }

    render() {
        return (
            <form>
                { this.state.error ?
{this.state.error}
 : undefined }
                <TextField type="name" name="name" hintText="Name" fullWidth={true} />
                <TextField type="email" name="email" hintText="Email" fullWidth={true} />
                <TextField type="password" name="password" hintText="Password" fullWidth={true} />
                <RaisedButton label="Register" primary={true} onClick={this.onSubmit.bind(this)} />
            </form>
        )
    }
}

export default RegisterForm;

Body:
You should specified register path in your router like <Route path="/register" component={YourComponent} />

<Switch>
   <Route exact path="/" component={Root} />
   <Route path="/register" component={Register} />
</Switch>


问:
With pure JavaScript, is there an easy way to attach an event listener to a class?
I'm looking for the JavaScript equivalent of

```<code>$(".class-name").on(eventName, eventHandler);
</code>```

first I tried

```<code>document.querySelectorAll(".class-name").addEventListener(eventName, eventHandler);
</code>```

but it didn't work. Is there an easy way to do it in JavaScript?

------Update------

Many answers suggested a loop, but originally I was looking for a solution with a single listener to save memory (suppose I had 1000 items in that class).
However, one answer reminded me: does the jQuery version also create 1000 listeners in the memory?

答:
You could loop over document.getElementsByClassName('this-is-the-class-you-are-searching-for') like

```<code>document.getElementsByClassName('selector-class').forEach(function (e) {
  e.addEventListener('click', function (event) {
    console.log('Oh dang, you just clicked!');
  });
});
</code>```

As Alex M. pointed out, the NodeList.forEach is not supported by some browsers such as InternetExplorer. So, you could use a different syntax (for) or use a transpiler like babel to ensure the wide support of your code! The polyfill from MDN is also very small.

Body:
I'm looking for the JavaScript equivalent of

$(".class-name").on(eventName, eventHandler);

first I tried

document.querySelectorAll(".class-name").addEventListener(eventName, eventHandler);

but it didn't work. Is there an easy way to do it in JavaScript?

------Update------

Many answers suggested a loop, but originally I was looking for a solution with a single listener to save memory (suppose I had 1000 items in that class).
However, one answer reminded me: does the jQuery version also create 1000 listeners in the memory?

Body:
You could loop over document.getElementsByClassName('this-is-the-class-you-are-searching-for') like

document.getElementsByClassName('selector-class').forEach(function (e) {
  e.addEventListener('click', function (event) {
    console.log('Oh dang, you just clicked!');
  });
});

As Alex M. pointed out, the NodeList.forEach is not supported by some browsers such as InternetExplorer. So, you could use a different syntax (for) or use a transpiler like babel to ensure the wide support of your code! The polyfill from MDN is also very small.


问:
UITableView willDisplay cell is drawing all cells before I scroll down
I'm trying to implement infinite scrolling in UITableView by checking the indexpath at "willDisplay cell", however once the table is loaded with data, the "willDisplay cell" func seems to be drawing all cells before I scroll down although the mobile screen can only fit one or two cells at a time.

```<code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        print(indexPath.row)
}
</code>```

Output without scrolling down:

```<code>0
1
2
3
4
5
</code>```

When I scroll down the "willDisplay cell" func works properly and it prints the indexpath.row one at a time.

What could be the problem here?

Here's a look at the full code:

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        postsTableview.delegate = self
        postsTableview.dataSource = self
        let nibName = UINib(nibName: "postTableViewCell", bundle:nil)
        postsTableview.register(nibName, forCellReuseIdentifier: "postTableViewCell")

        loadPosts()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postTableViewCell", for: indexPath) as! postTableViewCell
        return cell
    }

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        print(indexPath.row)
}
</code>```

I have tried setting the tableview cell height fixed with large value that exceeds the screen height but I still have the same problem

```<code>func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 1000.0;
    }
</code>```

答:
It turned out that I needed to set an estimated row height. I'm coming from Android background and this sounds silly to me but it worked out.</p>

```<code>postsTableview.estimatedRowHeight = 400
postsTableview.rowHeight = UITableViewAutomaticDimension
</code>```

Body:
I'm trying to implement infinite scrolling in UITableView by checking the indexpath at "willDisplay cell", however once the table is loaded with data, the "willDisplay cell" func seems to be drawing all cells before I scroll down although the mobile screen can only fit one or two cells at a time.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        print(indexPath.row)
}

Output without scrolling down:

0
1
2
3
4
5

When I scroll down the "willDisplay cell" func works properly and it prints the indexpath.row one at a time.

What could be the problem here?

Here's a look at the full code:

override func viewDidLoad() {
        super.viewDidLoad()
        postsTableview.delegate = self
        postsTableview.dataSource = self
        let nibName = UINib(nibName: "postTableViewCell", bundle:nil)
        postsTableview.register(nibName, forCellReuseIdentifier: "postTableViewCell")

        loadPosts()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postTableViewCell", for: indexPath) as! postTableViewCell
        return cell
    }

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        print(indexPath.row)
}

I have tried setting the tableview cell height fixed with large value that exceeds the screen height but I still have the same problem

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 1000.0;
    }

Body:
It turned out that I needed to set an estimated row height. I'm coming from Android background and this sounds silly to me but it worked out.

postsTableview.estimatedRowHeight = 400
postsTableview.rowHeight = UITableViewAutomaticDimension


问:
Axios PUT request doesn't work
axios.put method doesn't work while axios.post works.

This is working example for post request. (example)

```<code>let response = await axios.post(`${ROOT_URL}/urls/url/`, {
    post_id,
    password,
    content
  }, { headers });
  console.log(response.status) // 201.
</code>```

I just copied and pasted the valid post request, and modified some fields and method for put request. But it returns 400 error on server side.

```<code>let response = await axios.put(`${ROOT_URL}/profile/update/`, {
    title,
    gender
  }, { headers }); <- Server prints 400 HTTP error.
</code>```

I tested with Postman and I confirmed that it works with put method. I have to think that my syntax for axios.put is wrong but I'm not sure how it can be different with the post method.

If you see axios's official doc page, it looks almost identical. Axios documentation link

And axios version is 0.16.2 : "axios": "^0.16.2",

答:
400 is bad request not 405 method not allowed.

I'd check what your posting is correct.

Is this a valid object?

```<code>{
    title,
    gender
}
</code>```

Example:

```<code>axios.put('/api/something', {
    foo: bar
})
    .then(function (response) {
        // do something...
    }.bind(this))
    .catch(function (error) {
        console.log(error)
    });
</code>```

Title: Axios PUT request doesn't work

Body:
axios.put method doesn't work while axios.post works.

This is working example for post request. (example)

let response = await axios.post(`${ROOT_URL}/urls/url/`, {
    post_id,
    password,
    content
  }, { headers });
  console.log(response.status) // 201.

I just copied and pasted the valid post request, and modified some fields and method for put request. But it returns 400 error on server side.

let response = await axios.put(`${ROOT_URL}/profile/update/`, {
    title,
    gender
  }, { headers }); <- Server prints 400 HTTP error.

I tested with Postman and I confirmed that it works with put method. I have to think that my syntax for axios.put is wrong but I'm not sure how it can be different with the post method.

If you see axios's official doc page, it looks almost identical. Axios documentation link

And axios version is 0.16.2 : "axios": "^0.16.2",

Body:
400 is bad request not 405 method not allowed.

I'd check what your posting is correct.

Is this a valid object?

{
    title,
    gender
}

Example:

axios.put('/api/something', {
    foo: bar
})
    .then(function (response) {
        // do something...
    }.bind(this))
    .catch(function (error) {
        console.log(error)
    });


答:
Here's the equivalent (this will also work for future nodes)

```<code>document.addEventListener("click", function(e) {
  var el = e.target;
  if (el.classList.contains("class-name")) {
    // handle event e for element el
  }
});
</code>```

Edit: while the same is possible in jQuery, this way is actually superior to the example from the Question. This listener will also catch clicks on elements that didn't exist when the listener was added.

Title: With pure JavaScript, is there an easy way to attach an event listener to a class?

Body:
Here's the equivalent (this will also work for future nodes)

document.addEventListener("click", function(e) {
  var el = e.target;
  if (el.classList.contains("class-name")) {
    // handle event e for element el
  }
});

Edit: while the same is possible in jQuery, this way is actually superior to the example from the Question. This listener will also catch clicks on elements that didn't exist when the listener was added.


问:
How to open (not save) a blob generated with jspdf with Cordova for Android?
I´m having issues trying to open a PDF file blob generated with jspdf using cordova. I found that there is a lot of 'security' measures on Android that make incredibly difficult to open from a saved file, more for me because I´m noob with cross platforms apps, so I need to find a way to open the blob without saving.

I tried but the console shows me: "Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided."

This is my function to generate the pdf blob:

```<code>   function createPDF(){
      console.log("generating pdf...");
      var doc = new jsPDF();

      doc.text(20, 20, 'Document title');

      doc.setFont("courier");
      doc.setFontType("normal");
      doc.text(20, 30, 'test first line');
      doc.text(20, 50, 'test second line');

      var blobPDF = doc.output();

      var blobUrl = URL.createObjectURL(blobPDF);  <--- THE ERROR APPEARS HERE
      window.open(blobUrl,'_system','location=yes');
    }
</code>```

What I need is open the file so Android gives me the optional apps to open (Adobe reader, etc).

How can I make this code work for Android? I tried a lot of examples but always there's some kind of  problem.

Just in case I'm using Intel XDK (ver 3522) and I included the File, File-Transfer, InAppBrowser, FileOpener2 plugins.

答:
Try this, works for me :</p>

```<code>var blobPDF =  new Blob([ doc.output() ], { type : 'application/pdf'});
var blobUrl = URL.createObjectURL(blobPDF);  //<--- THE ERROR APPEARS HERE

window.open(blobUrl);  // will open a new tab

//window.open(blobUrl,'_system','location=yes'); will open a new window
</code>```

Body:
I´m having issues trying to open a PDF file blob generated with jspdf using cordova. I found that there is a lot of 'security' measures on Android that make incredibly difficult to open from a saved file, more for me because I´m noob with cross platforms apps, so I need to find a way to open the blob without saving.

I tried but the console shows me: "Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided."

This is my function to generate the pdf blob:

   function createPDF(){
      console.log("generating pdf...");
      var doc = new jsPDF();

      doc.text(20, 20, 'Document title');

      doc.setFont("courier");
      doc.setFontType("normal");
      doc.text(20, 30, 'test first line');
      doc.text(20, 50, 'test second line');

      var blobPDF = doc.output();

      var blobUrl = URL.createObjectURL(blobPDF);  <--- THE ERROR APPEARS HERE
      window.open(blobUrl,'_system','location=yes');
    }

What I need is open the file so Android gives me the optional apps to open (Adobe reader, etc).

How can I make this code work for Android? I tried a lot of examples but always there's some kind of  problem.

Just in case I'm using Intel XDK (ver 3522) and I included the File, File-Transfer, InAppBrowser, FileOpener2 plugins.

Body:
Try this, works for me :

var blobPDF =  new Blob([ doc.output() ], { type : 'application/pdf'});
var blobUrl = URL.createObjectURL(blobPDF);  //<--- THE ERROR APPEARS HERE

window.open(blobUrl);  // will open a new tab

//window.open(blobUrl,'_system','location=yes'); will open a new window


问:
Tags disappeared from tagcloud in highcharts while using deriveFontSize method
I will be working on highcharts wordcloud. Sometimes it behaves unexpectedly. So i will be giving fontsize for each tags using deriveFontSize method. Here the code goes.

```<code>Highcharts.seriesTypes.wordcloud.prototype.deriveFontSize = function(relativeWeight) {
  var maxFontSize = 55;
  // Will return a fontSize based on maxFontSize.
  var rWeight = Math.floor(maxFontSize * relativeWeight);
  var size = rWeight < 1 ? 1 : rWeight;
  return size;
};
</code>```

so the maxFontSize i given is 55. When i am executing the code again and again in the fiddle some of the tags are disappearing. The code is working correctly when the Highcharts.seriesTypes.wordcloud.prototype.deriveFontSize method is not included. So please help me to solve. Fiddle link here

答:
It seems that outsidePlayingField doesn't work perfectly - I commented it out in intersectionTesting function and the plot looks fine (all points are visible):

```<code>while (
  (
    intersectsAnyWord(point, placed) //||
    //outsidePlayingField(element, field)
  ) && delta !== false
) {
  (...)
</code>```

Live demo: http://jsfiddle.net/kkulig/qmtwspyn/

API reference about changing core functions: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts

Body:
I will be working on highcharts wordcloud. Sometimes it behaves unexpectedly. So i will be giving fontsize for each tags using deriveFontSize method. Here the code goes.

Highcharts.seriesTypes.wordcloud.prototype.deriveFontSize = function(relativeWeight) {
  var maxFontSize = 55;
  // Will return a fontSize based on maxFontSize.
  var rWeight = Math.floor(maxFontSize * relativeWeight);
  var size = rWeight < 1 ? 1 : rWeight;
  return size;
};

so the maxFontSize i given is 55. When i am executing the code again and again in the fiddle some of the tags are disappearing. The code is working correctly when the Highcharts.seriesTypes.wordcloud.prototype.deriveFontSize method is not included. So please help me to solve. Fiddle link here

Body:
It seems that outsidePlayingField doesn't work perfectly - I commented it out in intersectionTesting function and the plot looks fine (all points are visible):

while (
  (
    intersectsAnyWord(point, placed) //||
    //outsidePlayingField(element, field)
  ) && delta !== false
) {
  (...)

Live demo: http://jsfiddle.net/kkulig/qmtwspyn/

API reference about changing core functions: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts


问:
Xampp access denied error
I am facing this error every time I create a database in CLI interface of mysql:

I am using Xampp

答:
A simple and 100% working solution for this problem is:

Install Xampp outside the C: Folder and it will definitely work for you, without any permission problems ever.

But remember to provide xampp-control.exe administrative privileges always to terminate any port problems.

Title: Xampp access denied error


问:
RequireJS - define function is not returning dependencies correctly
I'm using RequireJS and when I define a new module using the function "define" I see the dependencies were resolved but the objects are not the modules I defined.

All the modules are defined in AMD format, setting a name, array of dependencies and a function. The exportation is done by return an object.

The dependencies resolved by "define" have these properties: exports, id, packaged, and uri. If I then call require function the dependencies are set correctly.

UPDATE: I created a test example with the described issue

HTML:

```<code><!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Test</title>
    <script src="/Scripts/require.js" data-main="../Scripts/main"></script>
    <script src="/Scripts/module.js"></script>
</head>
<body>
    <div>
    </div>
</body>
</html>
</code>```

main.js:

```<code>require(["module"], function (module) {
    module.test();
});
</code>```

module.js:

```<code>define([], function () {

    function test() {
        return "a";
    }

    return {
        test: test
    };
});
</code>```

Console:
Uncaught TypeError: module.test is not a function

This happens because module is not resolved to the real module but to an object with properties:

-config { arguments: null, caller: null, length: 0, name: "config" }

-exports { id: "@r5", uri: "../Scripts/@r5.js" }

Setting a module name in the define function has the same result.

NOTE: in the example there was an issue detected by @Louis. A module cannot be named "module". This helped me fixed the example but didn't fix my real issue. Below I describe the solution.

SOLUTION:

My issue was related to a library called Ace (HTML editor). This is the link that helped me solve it: https://github.com/josdejong/jsoneditor/issues/173

答:
With the edit you made, it is now possible to diagnose the issue. Do not name any module you write with the name module, and the problem will go away.

The name module is one of three reserved module names: module, require and exports. You should never name any of your own modules with these names.

When you ask RequireJS to load module, it is not loading your module. Instead, it simply returns an internal structure which is meant to provide information about the current module. It has fields like id, which gives the current module id (i.e. the module name) and url which gives the URL from which the module was loaded, and so on and so forth.

Body:
I'm using RequireJS and when I define a new module using the function "define" I see the dependencies were resolved but the objects are not the modules I defined.

All the modules are defined in AMD format, setting a name, array of dependencies and a function. The exportation is done by return an object.

The dependencies resolved by "define" have these properties: exports, id, packaged, and uri. If I then call require function the dependencies are set correctly.

UPDATE: I created a test example with the described issue

HTML:

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Test</title>

main.js:

require(["module"], function (module) {
    module.test();
});

module.js:

define([], function () {

    function test() {
        return "a";
    }

    return {
        test: test
    };
});

Console:
Uncaught TypeError: module.test is not a function

This happens because module is not resolved to the real module but to an object with properties:

-config { arguments: null, caller: null, length: 0, name: "config" }

-exports { id: "@r5", uri: "../Scripts/@r5.js" }

Setting a module name in the define function has the same result.

NOTE: in the example there was an issue detected by @Louis. A module cannot be named "module". This helped me fixed the example but didn't fix my real issue. Below I describe the solution.

SOLUTION:

My issue was related to a library called Ace (HTML editor). This is the link that helped me solve it: https://github.com/josdejong/jsoneditor/issues/173


问:
transform json to key/value file in bash
I have a JSON which looks like this:

```<code>{
    "lorem": "ipsum",
    "dolor": "sid",
    "data": {
        "key1": "value1",
        "key2": "value2"
    }
}
</code>```

and I want an output which is ini like where I only need the content of 'data' (which is always flat, no branches). The output should look like this:

```<code>key1=value1
key2=value2
</code>```

I can use jq (just don't get it running) but have to use a bash script for it. Can anyone help?

答:
jq solution:

```<code>jq -r '.data | to_entries[] | "\(.key)=\(.value)"' input.json
</code>```

The output:

```<code>key1=value1
key2=value2
</code>```

Body:
I have a JSON which looks like this:

{
    "lorem": "ipsum",
    "dolor": "sid",
    "data": {
        "key1": "value1",
        "key2": "value2"
    }
}

and I want an output which is ini like where I only need the content of 'data' (which is always flat, no branches). The output should look like this:

key1=value1
key2=value2

I can use jq (just don't get it running) but have to use a bash script for it. Can anyone help?

Body:
jq solution:

jq -r '.data | to_entries[] | "\(.key)=\(.value)"' input.json

The output:

key1=value1
key2=value2


问:
Override helpers in Laravel 5 with PHPUnit
I have been following the advices provided here to override my route, creating my very own helpers.php and loading it in the bootstrap. It works fine in the browser but not so much in PHPUnit:

```<code>PHP Fatal error:  Cannot redeclare route() (previously declared in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:707) in /var/www/app/Http/helpers.php on line 25
</code>```

It seems that PHPUnit is calling the vendor autoload instead of the bootstrap set in phpunit.xml and I don't know how to override that.

This is the call stack I get when throwing an Exception inside Laravel's helpers.php

```<code>#0 /var/www/vendor/composer/autoload_real.php(66): require()
#1 /var/www/vendor/composer/autoload_real.php(56): composerRequirefaa86f5c74caea0c3ebf4fa6247e01ed('f0906e6318348a7...', '/var/www/vendor...')
#2 /var/www/vendor/autoload.php(7): ComposerAutoloaderInitfaa86f5c74caea0c3ebf4fa6247e01ed::getLoader()
#3 /var/www/vendor/phpunit/phpunit/phpunit(51): require('/var/www/vendor...')
#4 {main}
  thrown in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 699
</code>```

Only elements I have not control on.

EDIT

I have made some edits in my composer.json, to load my helpers. It now generates vendor/composer/autoload_files.php:

```<code><?php

// autoload_files.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    // ...

    'f0906e6318348a765ffb6eb24e0d0938' => $vendorDir . '/laravel/framework/src/Illuminate/Foundation/helpers.php',
    '58571171fd5812e6e447dce228f52f4d' => $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php',
    '224ac75459a4044275cfdffe33336135' => $baseDir . '/app/Http/helpers.php',
);
</code>```

Basically, this could fix my problem if I had a way to inject my helpers before Laravel's.

I really love debugging this thing and hear this little song in my head "What a nice idea to have those neat static helpers", it's grooooovy.

答:
If you read the edit of the question you will understand that injecting the file in the autoload does not work.

https://packagist.org/packages/funkjedi/composer-include-files is here to solve this.

First run:

```<code>composer require funkjedi/composer-include-files
</code>```

Then update your composer.json extra field:

```<code>"extra": {
    "include_files": [
        "app/Http/helpers.php"
    ]
}
</code>```

Body:
I have been following the advices provided here to override my route, creating my very own helpers.php and loading it in the bootstrap. It works fine in the browser but not so much in PHPUnit:

PHP Fatal error:  Cannot redeclare route() (previously declared in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:707) in /var/www/app/Http/helpers.php on line 25

It seems that PHPUnit is calling the vendor autoload instead of the bootstrap set in phpunit.xml and I don't know how to override that.

This is the call stack I get when throwing an Exception inside Laravel's helpers.php

#0 /var/www/vendor/composer/autoload_real.php(66): require()
#1 /var/www/vendor/composer/autoload_real.php(56): composerRequirefaa86f5c74caea0c3ebf4fa6247e01ed('f0906e6318348a7...', '/var/www/vendor...')
#2 /var/www/vendor/autoload.php(7): ComposerAutoloaderInitfaa86f5c74caea0c3ebf4fa6247e01ed::getLoader()
#3 /var/www/vendor/phpunit/phpunit/phpunit(51): require('/var/www/vendor...')
#4 {main}
  thrown in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 699

Only elements I have not control on.

EDIT

I have made some edits in my composer.json, to load my helpers. It now generates vendor/composer/autoload_files.php:

<?php

// autoload_files.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    // ...

    'f0906e6318348a765ffb6eb24e0d0938' => $vendorDir . '/laravel/framework/src/Illuminate/Foundation/helpers.php',
    '58571171fd5812e6e447dce228f52f4d' => $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php',
    '224ac75459a4044275cfdffe33336135' => $baseDir . '/app/Http/helpers.php',
);

Basically, this could fix my problem if I had a way to inject my helpers before Laravel's.

I really love debugging this thing and hear this little song in my head "What a nice idea to have those neat static helpers", it's grooooovy.

Body:
If you read the edit of the question you will understand that injecting the file in the autoload does not work.

https://packagist.org/packages/funkjedi/composer-include-files is here to solve this.

First run:

composer require funkjedi/composer-include-files

Then update your composer.json extra field:

"extra": {
    "include_files": [
        "app/Http/helpers.php"
    ]
}


问:
How to increase the height of navigation bar in Xcode?
I'm working on a app, in which I need to keep a navigation bar.
when I write any title on the bar, the time and the title kinda get very close to each other. I wanted to increase the height of the bar, so it can get some breathing room.</p>

答: Apple proposes not to resize navigationBar itself, but remove shadow from bar and add custom view under your navigationBar. This can work for most cases. Check Apple's samples.

ContentLicense: CC BY-SA 4.0


问:
How and where to use Transformations.switchMap?
In recent Android Architecture Components library released by Google, we have two static functions in the Transformations class. While the map function is straight forward and easily understandable, I am finding it hard to properly understand the switchMap function.

The official documentation of switchMap can be found here.

Can somebody explain how and where to use the switchMap function with a practical example?

答:
In the map() function

```<code>LiveData userLiveData = ...;
LiveData userName = Transformations.map(userLiveData, user -> {
     return user.firstName + " " + user.lastName; // Returns String
});
</code>```

everytime the value of userLiveData changes, userName will be updated too. Notice that we are returning a String.

In the switchMap() function:

```<code>MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
    repository.getUserById(id)); // Returns LiveData

void setUserId(String userId) {
     this.userIdLiveData.setValue(userId);
}
</code>```

everytime the value of userIdLiveData changes, repository.getUserById(id) will be called, just like the map function. But repository.getUserById(id) returns a LiveData. So everytime that the value of the LiveData returned by repository.getUserById(id) changes, the value of userLiveData will change too. So the value of userLiveData will depend on changes of userIdLiveData and changes of the value of repository.getUserById(id).

Practical example of switchMap(): imagine you have a user profile with a follow button and a next profile button which sets another profile info. Next profile button will call setUserId() with another id so userLiveData will change and UI will change. Follow button will call the DAO to add one follower more to that user, so the user will have 301 followers instead of 300. userLiveData will have this update that comes from the repository, which comes from the DAO.

Body:
In the map() function

LiveData userLiveData = ...;
LiveData userName = Transformations.map(userLiveData, user -> {
     return user.firstName + " " + user.lastName; // Returns String
});

everytime the value of userLiveData changes, userName will be updated too. Notice that we are returning a String.

In the switchMap() function:

MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
    repository.getUserById(id)); // Returns LiveData

void setUserId(String userId) {
     this.userIdLiveData.setValue(userId);
}

everytime the value of userIdLiveData changes, repository.getUserById(id) will be called, just like the map function. But repository.getUserById(id) returns a LiveData. So everytime that the value of the LiveData returned by repository.getUserById(id) changes, the value of userLiveData will change too. So the value of userLiveData will depend on changes of userIdLiveData and changes of the value of repository.getUserById(id).

Practical example of switchMap(): imagine you have a user profile with a follow button and a next profile button which sets another profile info. Next profile button will call setUserId() with another id so userLiveData will change and UI will change. Follow button will call the DAO to add one follower more to that user, so the user will have 301 followers instead of 300. userLiveData will have this update that comes from the repository, which comes from the DAO.


问:
git Code from both branches showing
I'm using VS2017 to manage a git project. I cloned my dev (root) branch into a feature branch (let's call it f1) then decided to put that on hold to work on something else. I created another feature branch (f2) from dev and started working on it. Then I noticed something strange. Methods from the f1 branch were showing up in my f2 branch. I switched back over to the f1 branch and while it appeared the UI updated, I'm still seeing code from f2 and f1. How the heck did I break the isolation of the git branches?

I'm using VS2017 to switch between branches. Not sure if that makes a difference. I'm also fairly new to git, so I hope I'm just doing something wrong. Our company architect has seen this issue twice now with two different devs and she's an experienced git user with no idea how it happened.

答:
Changes to files that have been put in the staging area remain in the workspace when you switch to other branches.

So if you have run git add on a file and switch to a new branch, your change will still show up in Visual Studio.

Title: git Code from both branches showing


问:
Buttons outside the onCreate
Always in my apps I added buttons in void onCreate, but now I'm trying to do app with more buttons (about 10). I would like to all buttons active on start app.
In my opinion it is too much buttons to add in this onCreate and app will be starting to long.

I tried to put this:

```<code>myButton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View view) {
        myMethod();
    }
})
</code>```

out of onCreate

but AndroidStudio underlines setOnClickListener and view

I don't have ideas, how and where can i add button out of onCreate.

答:
The best way to do this is:

add implements View.OnClickListener to

```<code>    public class MainActivity extends AppCompatActivity implements View.OnClickListener {

// declare variables
private Button mBtn1;
private Button mBtn2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);

    // make an instance to the btns
    mBtn1 = findViewById(R.id.btn1);
    mBtn2 = findViewById(R.id.btn2);

    // set onClickListener
    mBtn1.setOnClickListener(this); // with "this" you are passing the view
    mBtn2.setOnClickListener(this);
}

// implement onClick
@Override
public void onClick(View view) {
    // check which btn was clicked by id
    switch (view.getId()) {
        case R.id.btn1:
            btn1Clicked();
            break;
        case R.id.btn2:
            btn2Clicked();
            break;
    }
}

private void btn1Clicked() {
    // your code btn1 clicked
}

private void btn2Clicked() {
    // your code btn2 clicked
}
</code>```

Hope this helped. Cheers!

Title: Buttons outside the onCreate

Body:
Always in my apps I added buttons in void onCreate, but now I'm trying to do app with more buttons (about 10). I would like to all buttons active on start app.
In my opinion it is too much buttons to add in this onCreate and app will be starting to long.

I tried to put this:

myButton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View view) {
        myMethod();
    }
})

out of onCreate

but AndroidStudio underlines setOnClickListener and view

I don't have ideas, how and where can i add button out of onCreate.

Body:
The best way to do this is:

add implements View.OnClickListener to

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {

// declare variables
private Button mBtn1;
private Button mBtn2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);

    // make an instance to the btns
    mBtn1 = findViewById(R.id.btn1);
    mBtn2 = findViewById(R.id.btn2);

    // set onClickListener
    mBtn1.setOnClickListener(this); // with "this" you are passing the view
    mBtn2.setOnClickListener(this);
}

// implement onClick
@Override
public void onClick(View view) {
    // check which btn was clicked by id
    switch (view.getId()) {
        case R.id.btn1:
            btn1Clicked();
            break;
        case R.id.btn2:
            btn2Clicked();
            break;
    }
}

private void btn1Clicked() {
    // your code btn1 clicked
}

private void btn2Clicked() {
    // your code btn2 clicked
}

Hope this helped. Cheers!


问:
Reading GitLab GL_REPOSITORY environment variable
I'm creating a server side hook (pre-receive) on GitLab 9.5. I need to know what repo is updated by push command.

The command echo $GL_REPOSITORY is executed by hook, but returns blank/empty on output. My hook was edited in a shell script.

These are my questions:
How can I read this environment variable?
Is there some configuration needed on the GitLab server?

Thanks.

答:
If the script does not able get anything from echo $GL_REPOSITORY, that means that that variable is not present in the environment anymore. To add it, Please add this in the ~/.bashrc file.

```<code>export $GL_REPOSITORY=<Value Here>
</code>```

And now make that to system by using source ~/.bashrc. Now you can be able to get that variable in your script.

Body:
If the script does not able get anything from echo $GL_REPOSITORY, that means that that variable is not present in the environment anymore. To add it, Please add this in the ~/.bashrc file.

export $GL_REPOSITORY=<Value Here>

And now make that to system by using source ~/.bashrc. Now you can be able to get that variable in your script.