问:
Date format changes when I call onselect event of bootstrap date picker
I used Bootstrap date picker with  data-date-format="mm/yyyy"

Here is my HTML code for date picker.

```<code><div class="input-group date" data-date-format="mm/yyyy"  data-provide="datepicker">
  <input id="acafimon" name="nperfimon" type="text" class="form-control">
  <div class="input-group-addon">
   <span class="glyphicon glyphicon-th"></span>
  </div>
</div>
</code>```

This Displayed only Months and Years in date picker when I select it.

Now I used datepicker() function and called onSelect event with jQuery

Here is that code

```<code>$("#acafimon").datepicker({
    onSelect: function() {
        alert("Date Selected");
    }
});
</code>```

It changed the date format mm/yyyy to mm/dd/yyyy format and included date when displaying.

What is way to fix this issue?

答:
Use this </p>

```<code>var date = $('#datepicker').datepicker({ dateFormat: 'mm/yyyy' }).val();
</code>```

<p>to change date format </p>

Body:
I used Bootstrap date picker with  data-date-format="mm/yyyy"

Here is my HTML code for date picker.

  <input id="acafimon" name="nperfimon" type="text" class="form-control">

This Displayed only Months and Years in date picker when I select it.

Now I used datepicker() function and called onSelect event with jQuery

Here is that code

$("#acafimon").datepicker({
    onSelect: function() {
        alert("Date Selected");
    }
});

It changed the date format mm/yyyy to mm/dd/yyyy format and included date when displaying.

What is way to fix this issue?

Body:
Use this

var date = $('#datepicker').datepicker({ dateFormat: 'mm/yyyy' }).val();

to change date format


来源: stackexchange

问:
Check if we can travel from source to destination
Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands. For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands. Each service connects two islands. The i-th service connects Island ai and Island bi.

Cat Snuke is on Island 1 now, and wants to go to Island N. However, it turned out that there is no direct boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Example:

```<code>N = 3
First boat services : 1 2
Second boat services: 2 3
</code>```

Output:
POSSIBLE

Explanation:
Using first boat, I can start from source point 1, and go to 2. Now using second boat I can go from 2 to 3, here 3 is my destination.

I am trying to understand what is the approach we need to follow to solve this problem?

I tried this basic approach, which will work for this test case, but I know that i am going in wrong way.

```<code>public static String check(List<Integer> boat1, List<Integer> boat2, int N) {
        Map<Integer, Integer> first = new HashMap<>();
        for (int i = 0; i < boat1.size() - 1; i++) {
            first.put(boat1.get(i), boat1.get(i + 1));
        }

        Map<Integer, Integer> second = new HashMap<>();
        for (int i = 0; i < boat2.size() - 1; i++) {
            second.put(boat2.get(i), boat2.get(i + 1));
        }

        if (first.get(1) != null) {
            int island = first.get(1);
            if (second.get(island) != null) {
                island = second.get(island);
                if (island == N) {
                    return "POSSIBLE";
                }
            }
        }
        return "Impossible";
    }
</code>```

Update:

Lets say boat 1 services are 1, 2, 3, 4 and boat 2 services are 3,5.
Trying with Josep answer now:

```<code>public static void main(String[] args) {
    GrafDirLlistes s = new GrafDirLlistes(5);
    s.afegirAresta(1, 2, 1);
    s.afegirAresta(2, 3, 1);
    s.afegirAresta(3, 4, 1);
    s.afegirAresta(3, 5, 1);
    s.dfs();
    System.out.println(s.existeixAresta(1, 5));

}
</code>```

I am expecting true for above program as we can travel from 1 to 5 like this 1->2->3->5, but the program is returning false.

答:
You may do it in a onepass style</p>

```<code>// all the "left" points of boats which ends in N
endingBoats = new Set // (e.g for boat [2,N] you store 2)

// all the "right" points of boats which start with 1
startingBoats = new Set // (e.g for boat [1, 3] your store 3)

for all boats:
  if boats does not start with 1 or end with N:
    continue

  // if boat starts with 1
  if boat[0] == 1:
    // check if there is a junction with a boat ending in N
    if endingBoats.has(boat[1]):
      return 'possible'
    // if not add the starting boat to candidates for junction
    startingBoats.add(boat[1])

  // if boat ends with N
  else if boat[1] == N:
    // check if there is a junction with a starting boat
    if startingBoats.has(boat[0]):
      return 'possible'
    // if not add the ending boat to candidates for junction
    endingBoats.add(boat[0])
return 'not possible'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands. For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands. Each service connects two islands. The i-th service connects Island ai and Island bi.

Cat Snuke is on Island 1 now, and wants to go to Island N. However, it turned out that there is no direct boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Example:

N = 3
First boat services : 1 2
Second boat services: 2 3

Output:
POSSIBLE

Explanation:
Using first boat, I can start from source point 1, and go to 2. Now using second boat I can go from 2 to 3, here 3 is my destination.

I am trying to understand what is the approach we need to follow to solve this problem?

I tried this basic approach, which will work for this test case, but I know that i am going in wrong way.

public static String check(List<Integer> boat1, List<Integer> boat2, int N) {
        Map<Integer, Integer> first = new HashMap<>();
        for (int i = 0; i < boat1.size() - 1; i++) {
            first.put(boat1.get(i), boat1.get(i + 1));
        }

        Map<Integer, Integer> second = new HashMap<>();
        for (int i = 0; i < boat2.size() - 1; i++) {
            second.put(boat2.get(i), boat2.get(i + 1));
        }

        if (first.get(1) != null) {
            int island = first.get(1);
            if (second.get(island) != null) {
                island = second.get(island);
                if (island == N) {
                    return "POSSIBLE";
                }
            }
        }
        return "Impossible";
    }

Update:

Lets say boat 1 services are 1, 2, 3, 4 and boat 2 services are 3,5.
Trying with Josep answer now:

public static void main(String[] args) {
    GrafDirLlistes s = new GrafDirLlistes(5);
    s.afegirAresta(1, 2, 1);
    s.afegirAresta(2, 3, 1);
    s.afegirAresta(3, 4, 1);
    s.afegirAresta(3, 5, 1);
    s.dfs();
    System.out.println(s.existeixAresta(1, 5));

}

I am expecting true for above program as we can travel from 1 to 5 like this 1->2->3->5, but the program is returning false.

Body:
You may do it in a onepass style

// all the "left" points of boats which ends in N
endingBoats = new Set // (e.g for boat [2,N] you store 2)

// all the "right" points of boats which start with 1
startingBoats = new Set // (e.g for boat [1, 3] your store 3)

for all boats:
  if boats does not start with 1 or end with N:
    continue

  // if boat starts with 1
  if boat[0] == 1:
    // check if there is a junction with a boat ending in N
    if endingBoats.has(boat[1]):
      return 'possible'
    // if not add the starting boat to candidates for junction
    startingBoats.add(boat[1])

  // if boat ends with N
  else if boat[1] == N:
    // check if there is a junction with a starting boat
    if startingBoats.has(boat[0]):
      return 'possible'
    // if not add the ending boat to candidates for junction
    endingBoats.add(boat[0])
return 'not possible'


问:
Question about lea instruction, IA32
If I have an IA32 instruction like the following:

```<code>lea 0x4(x1, x2, x3), %eax
</code>```

What do x1, x2, and x3 represent?
Thanks.

答:
If you mean "what is lea for," follow the link in Greg's comment.

If your question is about the syntax and are familiar with Intel syntax (but not AT&T syntax), x1 is the base, x2 is the index, and x3 is the scale (with 0x4 being the displacement). Thus,

```<code>lea 0x4(x1,x2,x3),%eax
</code>```

is equivalent to

```<code>lea eax,[x1+x3*x2+4]
</code>```

See this article on SourceForge for more.

ContentLicense: CC BY-SA 3.0

Title: Question about lea instruction, IA32

Body:
If I have an IA32 instruction like the following:

lea 0x4(x1, x2, x3), %eax

What do x1, x2, and x3 represent?
Thanks.

Body:
If you mean "what is lea for," follow the link in Greg's comment.

If your question is about the syntax and are familiar with Intel syntax (but not AT&T syntax), x1 is the base, x2 is the index, and x3 is the scale (with 0x4 being the displacement). Thus,

lea 0x4(x1,x2,x3),%eax

is equivalent to

lea eax,[x1+x3*x2+4]

See this article on SourceForge for more.


问:
Is there anything in c similar to Reflection API and annotations are in java.?
Recently, I've implemented an HTTP Server in c language. it serves static resources very well when requesting client request it to serve. Now I want it to serve dynamic resources like jsp in java (tomcat), means some piece of code could execute at server side and response should be sent. I've done this kind of things in java using reflection, annotations and using other core libraries but I've never done this in c before.

Can someone guide me to do this in c.Thanks in advance.

答:
While there are no equivalent facilities similar to Reflection API or Annotation in C, it is still possible to implement what you require, but it will need you to do some heavy lifting.

Mainly what I am getting is that you want to:

Figure out what the type of the resource is

Depending on the type, you want to execute it with some script and send its output.

For part 1 you could base it on the extension of the resource. You could use system MIME types, or you could create your own mapping like this:

```<code>struct Mapping {
   char *extension;
   char *command;
};

struct Mapping mapping[] = {
                            {"jsp", "<command to run jsp>"},
                            {"sh", "/bin/bash %1"}
};
</code>```

For part 2, when your server receives a request, it needs to extract the extension of the resource, and check in the mapping to see which entry matches the extension, obtain the command field and execute the command (after substituting arguments if any) using system() call.

Note that as an assignment this is a great way to learn a lot of things, but if you put this in production, it will be a huge security hole!

Body:
While there are no equivalent facilities similar to Reflection API or Annotation in C, it is still possible to implement what you require, but it will need you to do some heavy lifting.

Mainly what I am getting is that you want to:

Figure out what the type of the resource is

Depending on the type, you want to execute it with some script and send its output.

For part 1 you could base it on the extension of the resource. You could use system MIME types, or you could create your own mapping like this:

struct Mapping {
   char *extension;
   char *command;
};

struct Mapping mapping[] = {
                            {"jsp", "<command to run jsp>"},
                            {"sh", "/bin/bash %1"}
};

For part 2, when your server receives a request, it needs to extract the extension of the resource, and check in the mapping to see which entry matches the extension, obtain the command field and execute the command (after substituting arguments if any) using system() call.

Note that as an assignment this is a great way to learn a lot of things, but if you put this in production, it will be a huge security hole!


问:
How do you make every text display perfectly in the center of the image?
Look that every text is displayed below the picture. I would like every text to be displayed perfectly in the center of the picture.

Here is the code:
https://jsfiddle.net/Krzysiek_35/Ljybwz97/37/

body {
  left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3 {
    background-color: #191919;
    position: absolute;
    padding: 15px 40px 15px;
    font-size: 12px;
    color: #DDDDDD;
    font-family: Verdana;
    font-size: 12px;
    width: 400px;
}

.box3 > li {
    display: block;
}

.box3 > li span {
    display: inline-block;
    vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="box3">
    <li>
      <img src="pictures/contact/skype.png" width="34px" height="34px" />
      <span>Skype name</span>
    </li>
    <li>
      <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
      <span>Gadu-Gadu number</span>
    </li>
    <li>
      <img src="pictures/contact/email.png" width="34px" height="34px" />
      <span>Email address</span>
    </li>
  </div>
</body></code>```

How do you make every text display perfectly in the center of the image?

I will be very grateful for effective help.

答:
<pre class="lang-css prettyprint-override"><code>.box3 > li {
  display: flex;
  align-items: center;
}
</code>```

Body:
Look that every text is displayed below the picture. I would like every text to be displayed perfectly in the center of the picture.

Here is the code:
https://jsfiddle.net/Krzysiek_35/Ljybwz97/37/

body {
  left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3 {
    background-color: #191919;
    position: absolute;
    padding: 15px 40px 15px;
    font-size: 12px;
    color: #DDDDDD;
    font-family: Verdana;
    font-size: 12px;
    width: 400px;
}

.box3 > li {
    display: block;
}

.box3 > li span {
    display: inline-block;
    vertical-align: middle;
}

      Skype name

      Gadu-Gadu number

      Email address

How do you make every text display perfectly in the center of the image?

I will be very grateful for effective help.


问:
Recyclerview not scrolling inside Nested ScrollView
I have Recyclerview which is under Coordinatorlayout > NestedScrollview > ViewPager and ViewPager has 3 fragment, one has image gallery which is working with the help of Recyclerview. Whenever i tried to scroll up or down it doesn't scroll at all. I have already set photosRecycler.setNestedScrollingEnabled(false); and as soon as i remove this line i am getting scroll working only down side and when i tried to move back up it move up with parent Nestedscrollview.

My layout manager is also showing StaggeredGrid as Grid i need to get this kind of layout

Here is my parent layout for Nestedscrollview

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:background="?android:attr/colorBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways">

            <androidx.constraintlayout.widget.ConstraintLayout

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?android:colorBackground">

                <ImageView

                    android:layout_width="match_parent"
                    android:layout_height="500dp"
                    android:src="@color/custom_transparent_colorBlack"
                    android:scaleType="centerCrop"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="0.0"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    />

                <de.hdodenhof.circleimageview.CircleImageView

                    android:layout_width="128dp"
                    android:layout_height="128dp"
                    app:layout_constraintBottom_toBottomOf="@+id/coverPhoto"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="@+id/coverPhoto"
                    app:layout_constraintVertical_bias="0.44"
                    tools:srcCompat="@tools:sample/avatars" />

            </androidx.constraintlayout.widget.ConstraintLayout>
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>
    <androidx.core.widget.NestedScrollView
        android:id="@+id/up_NestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:overScrollMode="never"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"

        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            >
            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabItemes"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabGravity="fill"
                app:tabPaddingBottom="0dp"
                app:tabPaddingEnd="0dp"
                app:tabPaddingStart="0dp"
                app:tabPaddingTop="0dp"
                app:tabIndicatorHeight="0dp"
                app:tabMode="fixed"
                app:tabTextColor="@color/black"
                app:tabSelectedTextColor="@color/primary"
                app:tabIndicatorColor="@color/primary_light">

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="About" />

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Media" />

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Con" />
            </com.google.android.material.tabs.TabLayout>

            <androidx.viewpager.widget.ViewPager

                android:layout_below="@id/tabItemes"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </RelativeLayout>
    </androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Image Gallery Fragment

```<code>public class UserPhoto_fragment extends Fragment {
    public static final String TAG="### USER PHOTO ####";
    RecyclerView photosRecycler;
    fetchPhoto_Adapter adapter;
    StaggeredGridLayoutManager layoutManager;
    ArrayList<String> ImageList;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.userprofile_photos,container,false);
        setRetainInstance(true);
        photosRecycler=view.findViewById(R.id.userPhotos_recycler);
        layoutManager= new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        ImageList=new ArrayList<>();
        SpacesItemDecoration itemDecoration = new SpacesItemDecoration(16);
        photosRecycler.addItemDecoration(itemDecoration);
        photosRecycler.setLayoutManager(layoutManager);
        photosRecycler.setHasFixedSize(true);
        photosRecycler.setNestedScrollingEnabled(false);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: User Photo Fragment "+getView()+ ImageList.size() );
        if (ImageList.size()==0){
            new fetch_photo().execute();
        }
    }

    public class fetchPhoto_Adapter extends RecyclerView.Adapter<fetchPhoto_Adapter.ViewHolder>{

        @NonNull
        @Override
        public fetchPhoto_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            LayoutInflater inflater= (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflater.inflate(R.layout.userprofile_photogallery,viewGroup,false);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(fetchPhoto_Adapter.ViewHolder viewHolder, int i) {
            Glide.with(getActivity()).load(ImageList.get(i)).apply(new RequestOptions().centerCrop()).into(viewHolder.image);
        }

        @Override
        public int getItemCount() {
            if (ImageList!=null && ImageList.size()>0){
                return ImageList.size();
            }else {
                return 0;
            }
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            ImageView image;
            public ViewHolder(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.UserProfile_photoThumb);
            }
        }

    }

}
</code>```

Layout file for image gallery

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_marginTop="20dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/userPhotos_recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbars="vertical">

    </androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</code>```

I am facing 2 issue with this code

Recyclerview not working in nestedscrollview.

StaggeredGridLayoutManager is showing images like GridLayoutManager

Please help me to resolve these issue.Thanks

答:
Since it's viewPager that's directly inside your CoordinatorLayout and not your recyclerView, viewPager shoud have scrolling_layout_behaviour and not your recyclerview

```<code><androidx.viewpager.widget.ViewPager
   android:layout_below="@id/tabItemes"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</code>```

Set up your StaggeredGridLayoutManager like this

```<code>StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager); // set LayoutManager to RecyclerView
</code>```

In order for StaggeredGridLayout to work, you must not set your imageView scaletype to cropCenter and height of your cardView containing the imageView element should be set to wrap content and not fixed.

```<code><android.support.v7.widget.cardview
   android:layout_height="wrap_content"
   android:layout_width="match_parent"
   app:cardcornerradius="4dp"
   app:cardusecompatpadding="true">

  <linearlayout
    android:background="@color/colorPrimary"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical">

      <imageview
       android:adjustviewbounds="true"
       android:id="@+id/placePic"
       android:layout_height="match_parent"
       android:layout_width="match_parent"
       android:scaletype="fitXY" />

   </linearlayout>
</android.support.v7.widget.cardview>
</code>```

Body:
I have Recyclerview which is under Coordinatorlayout > NestedScrollview > ViewPager and ViewPager has 3 fragment, one has image gallery which is working with the help of Recyclerview. Whenever i tried to scroll up or down it doesn't scroll at all. I have already set photosRecycler.setNestedScrollingEnabled(false); and as soon as i remove this line i am getting scroll working only down side and when i tried to move back up it move up with parent Nestedscrollview.

My layout manager is also showing StaggeredGrid as Grid i need to get this kind of layout

Here is my parent layout for Nestedscrollview

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:background="?android:attr/colorBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways">

            <androidx.constraintlayout.widget.ConstraintLayout

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?android:colorBackground">

                <ImageView

                    android:layout_width="match_parent"
                    android:layout_height="500dp"
                    android:src="@color/custom_transparent_colorBlack"
                    android:scaleType="centerCrop"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="0.0"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    />

                <de.hdodenhof.circleimageview.CircleImageView

                    android:layout_width="128dp"
                    android:layout_height="128dp"
                    app:layout_constraintBottom_toBottomOf="@+id/coverPhoto"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="@+id/coverPhoto"
                    app:layout_constraintVertical_bias="0.44"
                    tools:srcCompat="@tools:sample/avatars" />

            </androidx.constraintlayout.widget.ConstraintLayout>
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>
    <androidx.core.widget.NestedScrollView
        android:id="@+id/up_NestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:overScrollMode="never"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"

        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            >
            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabItemes"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabGravity="fill"
                app:tabPaddingBottom="0dp"
                app:tabPaddingEnd="0dp"
                app:tabPaddingStart="0dp"
                app:tabPaddingTop="0dp"
                app:tabIndicatorHeight="0dp"
                app:tabMode="fixed"
                app:tabTextColor="@color/black"
                app:tabSelectedTextColor="@color/primary"
                app:tabIndicatorColor="@color/primary_light">

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="About" />

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Media" />

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Con" />
            </com.google.android.material.tabs.TabLayout>

            <androidx.viewpager.widget.ViewPager

                android:layout_below="@id/tabItemes"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </RelativeLayout>
    </androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Image Gallery Fragment

public class UserPhoto_fragment extends Fragment {
    public static final String TAG="### USER PHOTO ####";
    RecyclerView photosRecycler;
    fetchPhoto_Adapter adapter;
    StaggeredGridLayoutManager layoutManager;
    ArrayList<String> ImageList;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.userprofile_photos,container,false);
        setRetainInstance(true);
        photosRecycler=view.findViewById(R.id.userPhotos_recycler);
        layoutManager= new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        ImageList=new ArrayList<>();
        SpacesItemDecoration itemDecoration = new SpacesItemDecoration(16);
        photosRecycler.addItemDecoration(itemDecoration);
        photosRecycler.setLayoutManager(layoutManager);
        photosRecycler.setHasFixedSize(true);
        photosRecycler.setNestedScrollingEnabled(false);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: User Photo Fragment "+getView()+ ImageList.size() );
        if (ImageList.size()==0){
            new fetch_photo().execute();
        }
    }

    public class fetchPhoto_Adapter extends RecyclerView.Adapter<fetchPhoto_Adapter.ViewHolder>{

        @NonNull
        @Override
        public fetchPhoto_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            LayoutInflater inflater= (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflater.inflate(R.layout.userprofile_photogallery,viewGroup,false);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(fetchPhoto_Adapter.ViewHolder viewHolder, int i) {
            Glide.with(getActivity()).load(ImageList.get(i)).apply(new RequestOptions().centerCrop()).into(viewHolder.image);
        }

        @Override
        public int getItemCount() {
            if (ImageList!=null && ImageList.size()>0){
                return ImageList.size();
            }else {
                return 0;
            }
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            ImageView image;
            public ViewHolder(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.UserProfile_photoThumb);
            }
        }

    }

}

Layout file for image gallery

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_marginTop="20dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/userPhotos_recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbars="vertical">

    </androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>

I am facing 2 issue with this code

Recyclerview not working in nestedscrollview.

StaggeredGridLayoutManager is showing images like GridLayoutManager

Please help me to resolve these issue.Thanks

Body:
Since it's viewPager that's directly inside your CoordinatorLayout and not your recyclerView, viewPager shoud have scrolling_layout_behaviour and not your recyclerview

<androidx.viewpager.widget.ViewPager
   android:layout_below="@id/tabItemes"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   app:layout_behavior="@string/appbar_scrolling_view_behavior" />

Set up your StaggeredGridLayoutManager like this

StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager); // set LayoutManager to RecyclerView

In order for StaggeredGridLayout to work, you must not set your imageView scaletype to cropCenter and height of your cardView containing the imageView element should be set to wrap content and not fixed.

<android.support.v7.widget.cardview
   android:layout_height="wrap_content"
   android:layout_width="match_parent"
   app:cardcornerradius="4dp"
   app:cardusecompatpadding="true">

  <linearlayout
    android:background="@color/colorPrimary"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical">

      <imageview
       android:adjustviewbounds="true"
       android:id="@+id/placePic"
       android:layout_height="match_parent"
       android:layout_width="match_parent"
       android:scaletype="fitXY" />

   </linearlayout>
</android.support.v7.widget.cardview>


问:
How to check invisible checkbox in android studio
I have created a checkbox with text and set as invisible. Currently it is unchecked and I know the position of the checkbox as I have boxes above. I want the box to be checked and visible when I tap at the position ( invisible at the moment ).

I am not sure if this is possible or not as I could not find anything after hours of Googling.Sharing the codes below.

xml code

```<code>        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="5dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_diabetes"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:layout_gravity="center_vertical"
                android:fontFamily="@font/ubuntu_regular"
                android:layout_weight="0.2"
                android:text="@string/diabetes"
                android:textColor="@color/textColorAsh"
                android:textSize="16sp" />

            <CheckBox
                android:id="@+id/check_diabetes"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:theme="@style/checkBoxStyle"
                android:visibility="invisible" />
        </LinearLayout>
</code>```

Here is how I am try to make it visible programmatically. However it is not getting visible when I tap on the place where it is rendered.

```<code>       case R.id.check_diabetes:
            if (b == true) {
                tv_diabetes.setTextColor(getResources().getColor(R.color.textColorBlue));
                check_diabetes.setVisibility(View.VISIBLE);
                diabetes = "1";
            } else {...
</code>```

答:
You could try adding an onClickListener like this:</p>

```<code> check_diabetes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            check_diabetes.setVisibility(View.VISIBLE);
            check_diabetes.setChecked(true);
        }
    });
</code>```

Body:
I have created a checkbox with text and set as invisible. Currently it is unchecked and I know the position of the checkbox as I have boxes above. I want the box to be checked and visible when I tap at the position ( invisible at the moment ).

I am not sure if this is possible or not as I could not find anything after hours of Googling.Sharing the codes below.

xml code

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="5dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_diabetes"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:layout_gravity="center_vertical"
                android:fontFamily="@font/ubuntu_regular"
                android:layout_weight="0.2"
                android:text="@string/diabetes"
                android:textColor="@color/textColorAsh"
                android:textSize="16sp" />

            <CheckBox
                android:id="@+id/check_diabetes"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:theme="@style/checkBoxStyle"
                android:visibility="invisible" />
        </LinearLayout>

Here is how I am try to make it visible programmatically. However it is not getting visible when I tap on the place where it is rendered.

       case R.id.check_diabetes:
            if (b == true) {
                tv_diabetes.setTextColor(getResources().getColor(R.color.textColorBlue));
                check_diabetes.setVisibility(View.VISIBLE);
                diabetes = "1";
            } else {...

Body:
You could try adding an onClickListener like this:

 check_diabetes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            check_diabetes.setVisibility(View.VISIBLE);
            check_diabetes.setChecked(true);
        }
    });


问:
Restart loop when it ends

 let options = document.getElementsByClassName("option");
 console.log(options);
 var i = 1;

for (let i = 0; i < options.length; i++){
        options[i].classList.remove("active")
        setTimeout(function () {
            if(i!=0){
                console.log(options[i-1].classList.remove("active"))
            }
            console.log(options[i].classList.add("active"))

         }, i*3000)

}

function changeItem(item){
    item.classList.add("active")
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-pack: center;
            justify-content: center;
    -webkit-box-align: center;
            align-items: center;
    overflow: hidden;
    height: 100vh;
    font-family: 'Roboto', sans-serif;
  }
  body .credit {
    position: absolute;
    bottom: 20px;
    left: 20px;
    color: #000;
  }
  body .options {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-align: stretch;
            align-items: stretch;
    overflow: hidden;
    min-width: 600px;
    max-width: 900px;
    width: calc(100% - 100px);
    height: 400px;
  }
  @media screen and (max-width: 718px) {
    body .options {
      min-width: 520px;
    }
    body .options .option:nth-child(5) {
      display: none;
    }
  }
  @media screen and (max-width: 638px) {
    body .options {
      min-width: 440px;
    }
    body .options .option:nth-child(4) {
      display: none;
    }
  }
  @media screen and (max-width: 558px) {
    body .options {
      min-width: 360px;
    }
    body .options .option:nth-child(3) {
      display: none;
    }
  }
  @media screen and (max-width: 478px) {
    body .options {
      min-width: 280px;
    }
    body .options .option:nth-child(2) {
      display: none;
    }
  }
  body .options .option {
    position: relative;
    overflow: hidden;
    min-width: 60px;
    margin: 10px;
    background: var(--optionBackground, var(--defaultBackground, #E6E9ED));
    background-size: auto 120%;
    background-position: center;
    cursor: pointer;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option:nth-child(1) {
    --defaultBackground:#ED5565;
  }
  body .options .option:nth-child(2) {
    --defaultBackground:#FC6E51;
  }
  body .options .option:nth-child(3) {
    --defaultBackground:#FFCE54;
  }
  body .options .option:nth-child(4) {
    --defaultBackground:#2ECC71;
  }
  body .options .option:nth-child(5) {
    --defaultBackground:#5D9CEC;
  }
  body .options .option:nth-child(6) {
    --defaultBackground:#AC92EC;
  }
  body .options .option.active {
    -webkit-box-flex: 10000;
            flex-grow: 10000;
    -webkit-transform: scale(1);
            transform: scale(1);
    max-width: 600px;
    margin: 0px;
    border-radius: 40px;
    background-size: auto 100%;
    /*&:active {
       transform:scale(0.9);
    }*/
  }
  body .options .option.active .shadow {
    box-shadow: inset 0 -120px 120px -120px black, inset 0 -120px 120px -100px black;
  }
  body .options .option.active .label {
    bottom: 20px;
    left: 20px;
  }
  body .options .option.active .label .info > div {
    left: 0px;
    opacity: 1;
  }
  body .options .option:not(.active) {
    -webkit-box-flex: 1;
            flex-grow: 1;
    border-radius: 30px;
  }
  body .options .option:not(.active) .shadow {
    bottom: -40px;
    box-shadow: inset 0 -120px 0px -120px black, inset 0 -120px 0px -100px black;
  }
  body .options .option:not(.active) .label {
    bottom: 10px;
    left: 10px;
  }
  body .options .option:not(.active) .label .info > div {
    left: 20px;
    opacity: 0;
  }
  body .options .option .shadow {
    position: absolute;
    bottom: 0px;
    left: 0px;
    right: 0px;
    height: 120px;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option .label {
    display: -webkit-box;
    display: flex;
    position: absolute;
    right: 0px;
    height: 40px;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option .label .icon {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-pack: center;
            justify-content: center;
    -webkit-box-align: center;
            align-items: center;
    min-width: 40px;
    max-width: 40px;
    height: 40px;
    border-radius: 100%;
    background-color: white;
    color: var(--defaultBackground);
  }
  body .options .option .label .info {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
            flex-direction: column;
    -webkit-box-pack: center;
            justify-content: center;
    margin-left: 10px;
    color: white;
    white-space: pre;
  }
  body .options .option .label .info > div {
    position: relative;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95), opacity 0.5s ease-out;
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95), opacity 0.5s ease-out;
  }
  body .options .option .label .info .main {
    font-weight: bold;
    font-size: 1.2rem;
  }
  body .options .option .label .info .sub {
    -webkit-transition-delay: .1s;
            transition-delay: .1s;
  }
  </code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

Blonkisoaz

Omuke trughte a otufta

Oretemauw

Omuke trughte a otufta

Iteresuselle

Omuke trughte a otufta

Idiefe

Omuke trughte a otufta

Inatethi

Omuke trughte a otufta

     Photos from Victor of Valencia on tumblr

```

I took this animation from codepen , initially it executes on clicks only but I wanted to execute it after 3s. So I added a for loop.

I am changing classes of each element after 3000ms, what I want is when loops ends or reach last element it should restart from beginning. I tired setting i = 0 when i is last element of array, but it didn't work somehow.

Thanks in advance.

答:
you don't really need a cycle:</p>

```<code>var i = 0, n = options.length;

function loop() {
  window.setTimeout(function() {
    options[i].classList.remove("active");
    i++;
    if (i == n) {
      i = 0;
    }
    options[i].classList.add("active"));
    loop();
  }, 3000);
}

if (n > 0) {
  // if there is at least one element then activate the first one
  options[i].classList.add("active");
  if (n > 1) {
    // if there are several elements run loop
    loop();
  }
}
</code>```

Title: Restart loop when it ends

Body:
 let options = document.getElementsByClassName("option");
 console.log(options);
 var i = 1;

for (let i = 0; i < options.length; i++){
        options[i].classList.remove("active")
        setTimeout(function () {
            if(i!=0){
                console.log(options[i-1].classList.remove("active"))
            }
            console.log(options[i].classList.add("active"))

         }, i*3000)

}

function changeItem(item){
    item.classList.add("active")
}

body {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-pack: center;
            justify-content: center;
    -webkit-box-align: center;
            align-items: center;
    overflow: hidden;
    height: 100vh;
    font-family: 'Roboto', sans-serif;
  }
  body .credit {
    position: absolute;
    bottom: 20px;
    left: 20px;
    color: #000;
  }
  body .options {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-align: stretch;
            align-items: stretch;
    overflow: hidden;
    min-width: 600px;
    max-width: 900px;
    width: calc(100% - 100px);
    height: 400px;
  }
  @media screen and (max-width: 718px) {
    body .options {
      min-width: 520px;
    }
    body .options .option:nth-child(5) {
      display: none;
    }
  }
  @media screen and (max-width: 638px) {
    body .options {
      min-width: 440px;
    }
    body .options .option:nth-child(4) {
      display: none;
    }
  }
  @media screen and (max-width: 558px) {
    body .options {
      min-width: 360px;
    }
    body .options .option:nth-child(3) {
      display: none;
    }
  }
  @media screen and (max-width: 478px) {
    body .options {
      min-width: 280px;
    }
    body .options .option:nth-child(2) {
      display: none;
    }
  }
  body .options .option {
    position: relative;
    overflow: hidden;
    min-width: 60px;
    margin: 10px;
    background: var(--optionBackground, var(--defaultBackground, #E6E9ED));
    background-size: auto 120%;
    background-position: center;
    cursor: pointer;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option:nth-child(1) {
    --defaultBackground:#ED5565;
  }
  body .options .option:nth-child(2) {
    --defaultBackground:#FC6E51;
  }
  body .options .option:nth-child(3) {
    --defaultBackground:#FFCE54;
  }
  body .options .option:nth-child(4) {
    --defaultBackground:#2ECC71;
  }
  body .options .option:nth-child(5) {
    --defaultBackground:#5D9CEC;
  }
  body .options .option:nth-child(6) {
    --defaultBackground:#AC92EC;
  }
  body .options .option.active {
    -webkit-box-flex: 10000;
            flex-grow: 10000;
    -webkit-transform: scale(1);
            transform: scale(1);
    max-width: 600px;
    margin: 0px;
    border-radius: 40px;
    background-size: auto 100%;
    /*&:active {
       transform:scale(0.9);
    }*/
  }
  body .options .option.active .shadow {
    box-shadow: inset 0 -120px 120px -120px black, inset 0 -120px 120px -100px black;
  }
  body .options .option.active .label {
    bottom: 20px;
    left: 20px;
  }
  body .options .option.active .label .info > div {
    left: 0px;
    opacity: 1;
  }
  body .options .option:not(.active) {
    -webkit-box-flex: 1;
            flex-grow: 1;
    border-radius: 30px;
  }
  body .options .option:not(.active) .shadow {
    bottom: -40px;
    box-shadow: inset 0 -120px 0px -120px black, inset 0 -120px 0px -100px black;
  }
  body .options .option:not(.active) .label {
    bottom: 10px;
    left: 10px;
  }
  body .options .option:not(.active) .label .info > div {
    left: 20px;
    opacity: 0;
  }
  body .options .option .shadow {
    position: absolute;
    bottom: 0px;
    left: 0px;
    right: 0px;
    height: 120px;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option .label {
    display: -webkit-box;
    display: flex;
    position: absolute;
    right: 0px;
    height: 40px;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option .label .icon {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-pack: center;
            justify-content: center;
    -webkit-box-align: center;
            align-items: center;
    min-width: 40px;
    max-width: 40px;
    height: 40px;
    border-radius: 100%;
    background-color: white;
    color: var(--defaultBackground);
  }
  body .options .option .label .info {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
            flex-direction: column;
    -webkit-box-pack: center;
            justify-content: center;
    margin-left: 10px;
    color: white;
    white-space: pre;
  }
  body .options .option .label .info > div {
    position: relative;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95), opacity 0.5s ease-out;
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95), opacity 0.5s ease-out;
  }
  body .options .option .label .info .main {
    font-weight: bold;
    font-size: 1.2rem;
  }
  body .options .option .label .info .sub {
    -webkit-transition-delay: .1s;
            transition-delay: .1s;
  }

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

Blonkisoaz

Omuke trughte a otufta

Oretemauw

Omuke trughte a otufta

Iteresuselle

Omuke trughte a otufta

Idiefe

Omuke trughte a otufta

Inatethi

Omuke trughte a otufta

     Photos from Victor of Valencia on tumblr

I took this animation from codepen , initially it executes on clicks only but I wanted to execute it after 3s. So I added a for loop.

I am changing classes of each element after 3000ms, what I want is when loops ends or reach last element it should restart from beginning. I tired setting i = 0 when i is last element of array, but it didn't work somehow.

Thanks in advance.

Body:
you don't really need a cycle:

var i = 0, n = options.length;

function loop() {
  window.setTimeout(function() {
    options[i].classList.remove("active");
    i++;
    if (i == n) {
      i = 0;
    }
    options[i].classList.add("active"));
    loop();
  }, 3000);
}

if (n > 0) {
  // if there is at least one element then activate the first one
  options[i].classList.add("active");
  if (n > 1) {
    // if there are several elements run loop
    loop();
  }
}


答:
This is a hacky way to get what you want. In your layout file, set android:alpha="0", but set android:visibility="true" all the time.

And then in code

```<code>final CheckBox checkDiabetes= new CheckBox(R.id.check_diabetes);
            checkDiabetes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked)
                checkBox.setAlpha(1f);
            else
                checkBox.setAlpha(0f);
                }
            });
</code>```

Title: How to check invisible checkbox in android studio

Body:
This is a hacky way to get what you want. In your layout file, set android:alpha="0", but set android:visibility="true" all the time.

And then in code

final CheckBox checkDiabetes= new CheckBox(R.id.check_diabetes);
            checkDiabetes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked)
                checkBox.setAlpha(1f);
            else
                checkBox.setAlpha(0f);
                }
            });


问:
How to store result of simple python calculator in variable
I am a beginner to Python and have just started learning recently.

After learning about if, elif and else statements I decided to try and make a simple calculator.

Now, a few hours later I was wondering how I could improve it and make it more complex.

I am trying to store the result of the addition, subtraction, divison or multiplication of the first two numbers in a variable. After doing this I want to Re-create the calculator only I already have the first number.

I am also running into problems with my continue1 if statement, for some reason even if the user inputs "no" the script continues instead of displaying a message.

I'd really appreciate any help at all, Thank you!

Python code:

```<code>num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")

if operator == "/":
    print(num1 / num2)
elif operator == "+":
    print(num1 + num2)
elif operator == "-":
    print(num1 - num2)
elif operator == "*":
    print(num1 * num2)
else:
    print("FATAL ERROR")

num3 = num1 / num2
num3 = num1 - num2
num3 = num1 + num2
num3 = num1 * num2

continue1 =  input ("Would you like too continue? [Yes/No]")

if continue1 == "yes" or "Yes":
    operator1 = num4 = float(input("Please enter second number: "))
else:
    print("Fatal error")

input("please enter operator")

if operator == "/":
    print(num3 / num4)
elif operator == "+":
    print(num3 + num4)
elif operator == "-":
    print(num3 - num4)
elif operator == "*":
    print(num3 * num4)
else:
    print("Please press enter to close.")

input("Press Enter to Exit")
</code>```

答:
I recreated your code now it's working:</p>

```<code>def op(operator,num1,num2):
    global num3
    if operator == "/":
        num3 = num1 / num2
    elif operator == "+":
        num3 = num1 + num2
    elif operator == "-":
        num3 = num1 - num2
    elif operator == "*":
        num3 = num1 * num2
    else:
        print("FATAL ERROR")

num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")
op(operator,num1,num2)
print(num3)

continue1 =  input ("Would you like too continue? [Yes/No]").lower()

if continue1 in ["yes", "y"]:
    num4 = float(input("Please enter second number: "))
    operator = input("please enter operator")
    op(operator,num3,num4)
    print(num3)
else:
    print("Fatal error")

input("Press Enter to Exit")
</code>```

Body:
I am a beginner to Python and have just started learning recently.

After learning about if, elif and else statements I decided to try and make a simple calculator.

Now, a few hours later I was wondering how I could improve it and make it more complex.

I am trying to store the result of the addition, subtraction, divison or multiplication of the first two numbers in a variable. After doing this I want to Re-create the calculator only I already have the first number.

I am also running into problems with my continue1 if statement, for some reason even if the user inputs "no" the script continues instead of displaying a message.

I'd really appreciate any help at all, Thank you!

Python code:

num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")

if operator == "/":
    print(num1 / num2)
elif operator == "+":
    print(num1 + num2)
elif operator == "-":
    print(num1 - num2)
elif operator == "*":
    print(num1 * num2)
else:
    print("FATAL ERROR")

num3 = num1 / num2
num3 = num1 - num2
num3 = num1 + num2
num3 = num1 * num2

continue1 =  input ("Would you like too continue? [Yes/No]")

if continue1 == "yes" or "Yes":
    operator1 = num4 = float(input("Please enter second number: "))
else:
    print("Fatal error")

input("please enter operator")

if operator == "/":
    print(num3 / num4)
elif operator == "+":
    print(num3 + num4)
elif operator == "-":
    print(num3 - num4)
elif operator == "*":
    print(num3 * num4)
else:
    print("Please press enter to close.")

input("Press Enter to Exit")

Body:
I recreated your code now it's working:

def op(operator,num1,num2):
    global num3
    if operator == "/":
        num3 = num1 / num2
    elif operator == "+":
        num3 = num1 + num2
    elif operator == "-":
        num3 = num1 - num2
    elif operator == "*":
        num3 = num1 * num2
    else:
        print("FATAL ERROR")

num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")
op(operator,num1,num2)
print(num3)

continue1 =  input ("Would you like too continue? [Yes/No]").lower()

if continue1 in ["yes", "y"]:
    num4 = float(input("Please enter second number: "))
    operator = input("please enter operator")
    op(operator,num3,num4)
    print(num3)
else:
    print("Fatal error")

input("Press Enter to Exit")


问:
Hyperlink click should open the document in Default program
I have a hyperlink in my html document as

```<code><a href="file://c:/directory/file.txt">click</a>
</code>```

When I click on the hyperlink, the specified file opens in the browser itself.

Is it possible to open that file in notepad or sublime text or any text editor which is the default program for the file type (txt in this case). Can I do it programmatically in javascript or jquery. Is there any way to do it?

Note: This is just a stand alone application. I have developed a plugin which searches for patterns, that I have given as input, in all the files in a given source directory and print out all the file names in that directory which contains that pattern. Its printed to a output report html file. I just want to link the file path name to the default editor, so that he can edit it and save. No issue of security. Can it be done?

If not, is there any other way to accomplish this task? I can generate the output report in any format. Pls help.

答:
I was looking for something similar and found a solution. Maybe someone will find it useful.
If you only want to do this on your own computer, it works.</p>

Body:
I have a hyperlink in my html document as

click

When I click on the hyperlink, the specified file opens in the browser itself.

Is it possible to open that file in notepad or sublime text or any text editor which is the default program for the file type (txt in this case). Can I do it programmatically in javascript or jquery. Is there any way to do it?

Note: This is just a stand alone application. I have developed a plugin which searches for patterns, that I have given as input, in all the files in a given source directory and print out all the file names in that directory which contains that pattern. Its printed to a output report html file. I just want to link the file path name to the default editor, so that he can edit it and save. No issue of security. Can it be done?

If not, is there any other way to accomplish this task? I can generate the output report in any format. Pls help.


问:
Is C# a high level language?
Is C# a high level language? I see it as more like medium level, but I am still unsure about this. Would you consider it as high level as some of the popular scripting languages?

Or does it accommodate more than one level?

答:
From what I have read from various sources, C# is considered a 3GL language.  A higher level language 4GL would look more like natural language and a 5GL language is about constraints based programming (artificial intelligence) where you define the constraints of a problem but leave it up to the computer to solve it.

If you judge the C# language by itself (not considering the .Net framework), it is not a huge departure from other C based languages so in that sense the 3GL definition fits.

Here is a link to wikipedia for reference:

http://en.wikipedia.org/wiki/Third-generation_programming_language

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Is C# a high level language?

OwnerDisplayName: Brian


问:
First Item in Grouped List without using Lambda's?
Assume I have an object with "id" and "name".  My list is these items:

```<code>id = 1, name = "Bob"
id = 2, name = "Bob"
id = 3, name = "Chris"
id = 4, name = "Chris"
id = 5, name = "Paul"
</code>```

How can I get a subset of that list that would return me items 1, 3 and 5 (i.e. the first occurrence of a name) but specifically without Lambda's.

I think this is the Lambda solution

items.GroupBy(item => item.UniqueIdentifier).Distinct().Select(item => item.First()).ToList();

but I am specifically forbidden to use Lambda's on this solution (no, this isn't at school...this is in an actual work environment)

EDIT

I just realized that I can probably do this in my LINQ statement that gets me this list with this code.

```<code>(from t in this.ObjectContext.MYTABLE
    group t by t.UniqueIdentifier into theGroup
    select theGroup.First()).ToList();
</code>```

Would that work?

答:
This solution works perfectly:  </p>

```<code>(from t in this.ObjectContext.MYTABLE
group t by t.UniqueIdentifier into theGroup
select theGroup.First()).ToList();
</code>```

Body:
Assume I have an object with "id" and "name".  My list is these items:

id = 1, name = "Bob"
id = 2, name = "Bob"
id = 3, name = "Chris"
id = 4, name = "Chris"
id = 5, name = "Paul"

How can I get a subset of that list that would return me items 1, 3 and 5 (i.e. the first occurrence of a name) but specifically without Lambda's.

I think this is the Lambda solution

items.GroupBy(item => item.UniqueIdentifier).Distinct().Select(item => item.First()).ToList();

but I am specifically forbidden to use Lambda's on this solution (no, this isn't at school...this is in an actual work environment)

EDIT

I just realized that I can probably do this in my LINQ statement that gets me this list with this code.

(from t in this.ObjectContext.MYTABLE
    group t by t.UniqueIdentifier into theGroup
    select theGroup.First()).ToList();

Would that work?

Body:
This solution works perfectly:

(from t in this.ObjectContext.MYTABLE
group t by t.UniqueIdentifier into theGroup
select theGroup.First()).ToList();


问:
SinonJS stub is not working inside .on scope
```<code>it('POST /direct/bulk', function () {
    const file = getFile('notif-direct-bulk.csv')
    sinon.stub(notificationService.constructor.prototype, 'validateNotification').resolves(true)
    sinon.stub(notificationService.constructor.prototype, 'createInAppNotification').resolves(true)
    sinon.stub(fileService.constructor.prototype, 'storeFile').resolves(file.path)
    sinon.stub(fileService.constructor.prototype, 'deleteFile').returns(true)

    notificationService.validateNotification() // it's a stub
     .then((valid) => {
       return fileService.storeFile() // it's a stub
     })
     .then((storedFilePath) => {
       const reader = new require('line-by-line')(storedFilePath)
       console.log(notificationService.createInAppNotification()) // it's still a stub
       console.log(fileService.deleteFile()) // it's still a stub
       reader
        .on('line', (line) => {
          // inside this scope the stubs are not working
          notificationService.createInAppNotification() // calling the original method, not a stub
        })
        .on('end', () => {
          // inside this scope the stubs are not working
          fileService.deleteFile() // calling the original method, not a stub
        })
     })
})
</code>```

Why all stub is not working inside the .on scope function?

I'm wondering why it's happening? is the .on scopes are different with the sinonjs scope?

答:
Interesting, all stubs should work as expected.

I do not know your implementation, but I can give you this example base on your test code. I assume several classes (notificationService, fileService) to simplify and satisfy test.

Highlight:

I initiate reader based on npm line-by-line example.

on reader end, I make sure that all stubs get called.

I implement mocha asynchronous code using done.

const sinon = require('sinon');
const { expect } = require('chai');
const LineByLinereader = require('line-by-line');

// Example class to show that real method not get called.
const notificationService = {
  validateNotification() {
    console.log('Real validateNotification get called');
    // Return the opposite value based on your test (true).
    return new Promise((r) => r(false));
  },
  createInAppNotification() {
    console.log('Real createInAppNotification get called');
    // Return the opposite value based on your test (true).
    return new Promise((r) => r(false));
  },
};

// Example class to show that real method not get called.
const fileService = {
  storeFile() {
    console.log('Real storeFile get called');
    // Return the opposite value based on your test (string not empty).
    return new Promise((r) => r(''));
  },
  deleteFile() {
    console.log('Real deleteFile get called');
    // Return the opposite value based on your test (true).
    return false;
  },
};

function getFile() {
  // Return real dummy file path.
  return {
    path: './test.txt',
  };
}

// Mocha asynchronous code using done.
it('POST /direct/bulk', (done) => {
  const file = getFile('notif-direct-bulk.csv');
  const stubValidateNotification = sinon.stub(notificationService, 'validateNotification');
  stubValidateNotification.resolves(true);
  const stubCreateInAppNotification = sinon.stub(notificationService, 'createInAppNotification');
  stubCreateInAppNotification.resolves(true);
  const stubStoreFile = sinon.stub(fileService, 'storeFile');
  stubStoreFile.resolves(file.path);
  const stubDeleteFile = sinon.stub(fileService, 'deleteFile');
  stubDeleteFile.returns(true);

  notificationService.validateNotification() // it's a stub
    .then(() => fileService.storeFile()) // it's a stub
    .then((storedFilePath) => {
      // Expect the result is correct with file above.
      expect(storedFilePath).to.equal(file.path);
      // Initiate synchronous processing of lines.
      const reader = new LineByLinereader(storedFilePath);
      console.log(notificationService.createInAppNotification()); // it's still a stub
      console.log(fileService.deleteFile()); // it's still a stub
      reader
        .on('line', async () => {
          // inside this scope the stubs are not working
          const result = await notificationService.createInAppNotification(); // calling the original method, not a stub
          expect(result).to.equal(true);
        })
        .on('end', () => {
          // inside this scope the stubs are not working
          const result = fileService.deleteFile(); // calling the original method, not a stub
          expect(result).to.equal(true);

          // Expect all stub get called once.
          expect(stubValidateNotification.calledOnce).to.equal(true);
          expect(stubCreateInAppNotification.calledOnce).to.equal(true);
          expect(stubStoreFile.calledOnce).to.equal(true);
          // You expect this stub to get called twice.
          expect(stubDeleteFile.calledTwice).to.equal(true);

          // Finish the test.
          done();
        });
    });
});

```

<p>When I run it, no real method get called.</p>

```$ npx mocha stackoverflow.js

Promise { true }
true
  ✓ POST /direct/bulk

  1 passing (35ms)

$
```

Hope this helps.

Body:
it('POST /direct/bulk', function () {
    const file = getFile('notif-direct-bulk.csv')
    sinon.stub(notificationService.constructor.prototype, 'validateNotification').resolves(true)
    sinon.stub(notificationService.constructor.prototype, 'createInAppNotification').resolves(true)
    sinon.stub(fileService.constructor.prototype, 'storeFile').resolves(file.path)
    sinon.stub(fileService.constructor.prototype, 'deleteFile').returns(true)

    notificationService.validateNotification() // it's a stub
     .then((valid) => {
       return fileService.storeFile() // it's a stub
     })
     .then((storedFilePath) => {
       const reader = new require('line-by-line')(storedFilePath)
       console.log(notificationService.createInAppNotification()) // it's still a stub
       console.log(fileService.deleteFile()) // it's still a stub
       reader
        .on('line', (line) => {
          // inside this scope the stubs are not working
          notificationService.createInAppNotification() // calling the original method, not a stub
        })
        .on('end', () => {
          // inside this scope the stubs are not working
          fileService.deleteFile() // calling the original method, not a stub
        })
     })
})

Why all stub is not working inside the .on scope function?

I'm wondering why it's happening? is the .on scopes are different with the sinonjs scope?

Body:
Interesting, all stubs should work as expected.

I do not know your implementation, but I can give you this example base on your test code. I assume several classes (notificationService, fileService) to simplify and satisfy test.

Highlight:

I initiate reader based on npm line-by-line example.

on reader end, I make sure that all stubs get called.

I implement mocha asynchronous code using done.

const sinon = require('sinon');
const { expect } = require('chai');
const LineByLinereader = require('line-by-line');

// Example class to show that real method not get called.
const notificationService = {
  validateNotification() {
    console.log('Real validateNotification get called');
    // Return the opposite value based on your test (true).
    return new Promise((r) => r(false));
  },
  createInAppNotification() {
    console.log('Real createInAppNotification get called');
    // Return the opposite value based on your test (true).
    return new Promise((r) => r(false));
  },
};

// Example class to show that real method not get called.
const fileService = {
  storeFile() {
    console.log('Real storeFile get called');
    // Return the opposite value based on your test (string not empty).
    return new Promise((r) => r(''));
  },
  deleteFile() {
    console.log('Real deleteFile get called');
    // Return the opposite value based on your test (true).
    return false;
  },
};

function getFile() {
  // Return real dummy file path.
  return {
    path: './test.txt',
  };
}

// Mocha asynchronous code using done.
it('POST /direct/bulk', (done) => {
  const file = getFile('notif-direct-bulk.csv');
  const stubValidateNotification = sinon.stub(notificationService, 'validateNotification');
  stubValidateNotification.resolves(true);
  const stubCreateInAppNotification = sinon.stub(notificationService, 'createInAppNotification');
  stubCreateInAppNotification.resolves(true);
  const stubStoreFile = sinon.stub(fileService, 'storeFile');
  stubStoreFile.resolves(file.path);
  const stubDeleteFile = sinon.stub(fileService, 'deleteFile');
  stubDeleteFile.returns(true);

  notificationService.validateNotification() // it's a stub
    .then(() => fileService.storeFile()) // it's a stub
    .then((storedFilePath) => {
      // Expect the result is correct with file above.
      expect(storedFilePath).to.equal(file.path);
      // Initiate synchronous processing of lines.
      const reader = new LineByLinereader(storedFilePath);
      console.log(notificationService.createInAppNotification()); // it's still a stub
      console.log(fileService.deleteFile()); // it's still a stub
      reader
        .on('line', async () => {
          // inside this scope the stubs are not working
          const result = await notificationService.createInAppNotification(); // calling the original method, not a stub
          expect(result).to.equal(true);
        })
        .on('end', () => {
          // inside this scope the stubs are not working
          const result = fileService.deleteFile(); // calling the original method, not a stub
          expect(result).to.equal(true);

          // Expect all stub get called once.
          expect(stubValidateNotification.calledOnce).to.equal(true);
          expect(stubCreateInAppNotification.calledOnce).to.equal(true);
          expect(stubStoreFile.calledOnce).to.equal(true);
          // You expect this stub to get called twice.
          expect(stubDeleteFile.calledTwice).to.equal(true);

          // Finish the test.
          done();
        });
    });
});

When I run it, no real method get called.

$ npx mocha stackoverflow.js

Promise { true }
true
  ✓ POST /direct/bulk

  1 passing (35ms)

$

Hope this helps.


问:
How can I put multiple statements in one line?
I know a little bit of comprehensions in Python, but they seem very hard to 'read'. The way I see it, a comprehension might accomplish the same as the following code:

```<code>for i in range(10): if i == 9: print('i equals 9')
</code>```

This code is much easier to read than how comprehensions currently work, but I've noticed you can’t have two :s in one line. This brings me to:

Is there a way I can get the following example into one line?

```<code>try:
    if sam[0] != 'harry':
        print('hello',  sam)
except:
    pass
</code>```

Something like this would be great:

```<code>try: if sam[0] != 'harry': print('hellp',  sam)
except:pass
</code>```

But again I encounter the conflicting :s.

I'd also love to know if there's a way to run try (or something like it) without except. It seems entirely pointless that I need to put except:pass in there. It’s a wasted line.

答:
For a python -c oriented solution, and provided you use Bash shell, yes you can have a simple one-line syntax like in this example:

Suppose you would like to do something like this (very similar to your sample, including except: pass instruction):

```<code>python -c  "from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n" OUTPUT_VARIABLE __numpy_path
</code>```

This will not work and produce this error:

  File "<string>", line 1
    from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n
                                                                                ^
SyntaxError: unexpected character after line continuation character `
```
<p>This is because the competition between Bash and Python <em>interpretation</em> of <code>\n</code> escape sequences. To solve the problem one can use the <code>$'string'</code> Bash syntax to force <code>\n</code> Bash interpretation <em>before</em> the Python one.</p>
<p>To make the example more challenging, I added a typical Python <code>end=..\n..</code> specification in the Python print call: at the end you will be able to get <em>both</em> <code>\n</code> interpretations from Bash and Python working together, each on its piece of text of concern. So that finally the proper solution is like this:</p>
```python -c  $'from __future__ import print_function\ntry:\n import numpy;\n print( numpy.get_include(), end="\\n" )\n print( "Hello" )\nexcept:pass\n' OUTPUT_VARIABLE __numpy_path
```
<p>That leads to the proper clean output without an error:</p>
<pre class="lang-none prettyprint-override"><code>/Softs/anaconda/lib/python3.7/site-packages/numpy/core/include
Hello
</code>```

Note: this should work as well with exec-oriented solutions, because the problem is still the same (Bash and Python interpreters competition).

Note 2: one could work around the problem by replacing some \n by some ; but it will not work anytime (depending on Python constructs), while my solution allows to always "one-line" any piece of classic multi-line Python program.

Note 3: of course, when one-lining, one has always to take care of Python spaces and indentation, because in fact we are not strictly "one-lining" here, but doing a proper mixed-management of \n escape sequence between bash and Python. This is how we can deal with any piece of classic multi-line Python program. The solution sample illustrates this as well.

Body:
I know a little bit of comprehensions in Python, but they seem very hard to 'read'. The way I see it, a comprehension might accomplish the same as the following code:

for i in range(10): if i == 9: print('i equals 9')

This code is much easier to read than how comprehensions currently work, but I've noticed you can’t have two :s in one line. This brings me to:

Is there a way I can get the following example into one line?

try:
    if sam[0] != 'harry':
        print('hello',  sam)
except:
    pass

Something like this would be great:

try: if sam[0] != 'harry': print('hellp',  sam)
except:pass

But again I encounter the conflicting :s.

I'd also love to know if there's a way to run try (or something like it) without except. It seems entirely pointless that I need to put except:pass in there. It’s a wasted line.

Body:
For a python -c oriented solution, and provided you use Bash shell, yes you can have a simple one-line syntax like in this example:

Suppose you would like to do something like this (very similar to your sample, including except: pass instruction):

python -c  "from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n" OUTPUT_VARIABLE __numpy_path

This will not work and produce this error:

  File "<string>", line 1
    from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n
                                                                                ^
SyntaxError: unexpected character after line continuation character `

This is because the competition between Bash and Python interpretation of \n escape sequences. To solve the problem one can use the $'string' Bash syntax to force \n Bash interpretation before the Python one.

To make the example more challenging, I added a typical Python end=..\n.. specification in the Python print call: at the end you will be able to get both \n interpretations from Bash and Python working together, each on its piece of text of concern. So that finally the proper solution is like this:

python -c  $'from __future__ import print_function\ntry:\n import numpy;\n print( numpy.get_include(), end="\\n" )\n print( "Hello" )\nexcept:pass\n' OUTPUT_VARIABLE __numpy_path

That leads to the proper clean output without an error:

/Softs/anaconda/lib/python3.7/site-packages/numpy/core/include
Hello

Note: this should work as well with exec-oriented solutions, because the problem is still the same (Bash and Python interpreters competition).

Note 2: one could work around the problem by replacing some \n by some ; but it will not work anytime (depending on Python constructs), while my solution allows to always "one-line" any piece of classic multi-line Python program.

Note 3: of course, when one-lining, one has always to take care of Python spaces and indentation, because in fact we are not strictly "one-lining" here, but doing a proper mixed-management of \n escape sequence between bash and Python. This is how we can deal with any piece of classic multi-line Python program. The solution sample illustrates this as well.


问:
Javascript execution failed on elements which were added later through Javascript
In a project currently I'm working on, There are many items for which a dialog has to be opened. For each new dialog, data inside changes and that I have done using Javascript. Now If I add any elements like say a checkbox to the dialog from Javascript, The material js is not working on it. So I Checked a similar issue and got an answer, which I have implemented and still doesn't work.
In this snippet I have made a similar situation. An Add Button is used to add to the dialog and when Dialog opens the checkbox doesn't behave as it was in dialog during page load. To show this I have added a Checkbox before itself, not from Javascript. After adding Checkbox from Javascript the old existing checkbox also doesn't work.

Please help me, it'll be of great help.

function resetJs(path) {
  var scripts = document.getElementsByTagName('script'),
    newScript = document.createElement("script");

  newScript.src = path + "?timestamp=" + Math.round(new Date().getTime() / 1000);

  for (var i = 0; i < scripts.length; ++i) {
    var srcUrl = scripts[i].getAttribute('src');
    if (srcUrl && srcUrl.indexOf(path) > -1) {
      scripts[i].parentNode.replaceChild(newScript, scripts[i]);
    }
  }
}
var dialog = document.querySelector('dialog');

var addData = document.querySelector('#add');
addData.addEventListener('click', function() {
  var data = document.querySelector('#dialogContent');
  data.innerHTML += '<input type="checkbox" id="checkbox-1" class="mdl-checkbox__input" checked>Checkbox From JS';

});

var showDialogButton = document.querySelector('#show-dialog');
if (!dialog.showModal) {
  dialogPolyfill.registerDialog(dialog);
}
showDialogButton.addEventListener('click', function() {

  dialog.showModal();
  resetJs('https://code.getmdl.io/1.3.0/material.min.js');
});
dialog.querySelector('.close').addEventListener('click', function() {
  dialog.close();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css" rel="stylesheet"/>
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<button id="show-dialog" type="button" class="mdl-button">Show Dialog</button>
<button id="add" type="button" class="mdl-button">Add</button>
<dialog class="mdl-dialog">
  <h4 class="mdl-dialog__title">Allow data collection?</h4>
  <div class="mdl-dialog__content" id="dialogContent">
    <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="checkbox-1"><input type="checkbox" id="checkbox-1" class="mdl-checkbox__input" checked><span class="mdl-checkbox__label">Checkbox Added Before</span></label>
    <p>
      Allowing us to collect data will let us get you the information you want faster.
    </p>
  </div>
  <div class="mdl-dialog__actions">
    <button type="button" class="mdl-button">Agree</button>
    <button type="button" class="mdl-button close">Disagree</button>
  </div>
</dialog></code>```

答:
From the docs of mdl here

Material Design Lite will automatically register and render all elements marked with MDL classes upon page load. However in the case where you are creating DOM elements dynamically you need to register new elements using the upgradeElement function.

So, what you can do is in your addData function;

```<code>var addData = document.querySelector("#add");
  addData.addEventListener("click", function() {
    var data = document.querySelector("#dialogContent");
    var label = document.createElement("label");
    label.className = "mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect";
    label.innerHTML =
      '<input type="checkbox" id="checkbox-1" class="mdl-checkbox__input" checked><span class="mdl-checkbox__label">Checkbox From JS</span>';
    label.htmlFor = "checkbox-1";
    componentHandler.upgradeElement(label);
    data.appendChild(label);
  });

</code>```

You need to use componentHandler.upgradeElement to upgrade your dynamically created element into material element and then append the child to data.

Please take a look at this codesandbox

Body:
In a project currently I'm working on, There are many items for which a dialog has to be opened. For each new dialog, data inside changes and that I have done using Javascript. Now If I add any elements like say a checkbox to the dialog from Javascript, The material js is not working on it. So I Checked a similar issue and got an answer, which I have implemented and still doesn't work.
In this snippet I have made a similar situation. An Add Button is used to add to the dialog and when Dialog opens the checkbox doesn't behave as it was in dialog during page load. To show this I have added a Checkbox before itself, not from Javascript. After adding Checkbox from Javascript the old existing checkbox also doesn't work.

Please help me, it'll be of great help.

function resetJs(path) {
  var scripts = document.getElementsByTagName('script'),
    newScript = document.createElement("script");

  newScript.src = path + "?timestamp=" + Math.round(new Date().getTime() / 1000);

  for (var i = 0; i < scripts.length; ++i) {
    var srcUrl = scripts[i].getAttribute('src');
    if (srcUrl && srcUrl.indexOf(path) > -1) {
      scripts[i].parentNode.replaceChild(newScript, scripts[i]);
    }
  }
}
var dialog = document.querySelector('dialog');

var addData = document.querySelector('#add');
addData.addEventListener('click', function() {
  var data = document.querySelector('#dialogContent');
  data.innerHTML += '<input type="checkbox" id="checkbox-1" class="mdl-checkbox__input" checked>Checkbox From JS';

});

var showDialogButton = document.querySelector('#show-dialog');
if (!dialog.showModal) {
  dialogPolyfill.registerDialog(dialog);
}
showDialogButton.addEventListener('click', function() {

  dialog.showModal();
  resetJs('https://code.getmdl.io/1.3.0/material.min.js');
});
dialog.querySelector('.close').addEventListener('click', function() {
  dialog.close();
});

<link href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css" rel="stylesheet"/>

<button id="show-dialog" type="button" class="mdl-button">Show Dialog</button>
<button id="add" type="button" class="mdl-button">Add</button>
<dialog class="mdl-dialog">

Allow data collection?

    <input type="checkbox" id="checkbox-1" class="mdl-checkbox__input" checked>Checkbox Added Before

      Allowing us to collect data will let us get you the information you want faster.

    <button type="button" class="mdl-button">Agree</button>
    <button type="button" class="mdl-button close">Disagree</button>

</dialog>

Body:
From the docs of mdl here

Material Design Lite will automatically register and render all elements marked with MDL classes upon page load. However in the case where you are creating DOM elements dynamically you need to register new elements using the upgradeElement function.

So, what you can do is in your addData function;

var addData = document.querySelector("#add");
  addData.addEventListener("click", function() {
    var data = document.querySelector("#dialogContent");
    var label = document.createElement("label");
    label.className = "mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect";
    label.innerHTML =
      '<input type="checkbox" id="checkbox-1" class="mdl-checkbox__input" checked><span class="mdl-checkbox__label">Checkbox From JS</span>';
    label.htmlFor = "checkbox-1";
    componentHandler.upgradeElement(label);
    data.appendChild(label);
  });

You need to use componentHandler.upgradeElement to upgrade your dynamically created element into material element and then append the child to data.

Please take a look at this codesandbox