问:
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

答:
You need NestedScrollableHost to scroll in RecyclerView

Works for me with following layout tree

activity.xml

```<code><androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.MainActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/vp_views"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

fragment.xml

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:constraint="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        ...

        <com.anatoli.thebattleofcards.fabric.NestedScrollableHost
            android:id="@+id/rv_items_host"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            constraint:layout_constraintEnd_toEndOf="parent"
            constraint:layout_constraintStart_toStartOf="parent"
            constraint:layout_constraintTop_toTopOf="parent">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rv_items"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"      <!-- change orientation if needs -->
                android:paddingStart="@dimen/layout_padding_small"
                android:paddingEnd="@dimen/layout_padding_small"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />

        </com.anatoli.thebattleofcards.fabric.NestedScrollableHost>

        ...

    </androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>
</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:
You need NestedScrollableHost to scroll in RecyclerView

Works for me with following layout tree

activity.xml

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.MainActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/vp_views"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" />

</androidx.constraintlayout.widget.ConstraintLayout>

fragment.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:constraint="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        ...

        <com.anatoli.thebattleofcards.fabric.NestedScrollableHost
            android:id="@+id/rv_items_host"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            constraint:layout_constraintEnd_toEndOf="parent"
            constraint:layout_constraintStart_toStartOf="parent"
            constraint:layout_constraintTop_toTopOf="parent">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rv_items"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"      <!-- change orientation if needs -->
                android:paddingStart="@dimen/layout_padding_small"
                android:paddingEnd="@dimen/layout_padding_small"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />

        </com.anatoli.thebattleofcards.fabric.NestedScrollableHost>

        ...

    </androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>


来源: stackexchange

问:
Codewars strip comments problem randomly working/not-working for 'attempt' tests
I am currently on the 4kyu problem on Codewars, where given a string and a list of characters, your function is supposed to remove the characters in the string and any other characters that follow, up to the end of the line. I came up with a solution that I think should work. Since I need to remove every character in the string after the special character is found, I split the string by '\n' since that marks the end of the line.
Then I proceeded to write the function that checks all the substrings:

```<code>def solution(string,markers):
  str_arr = string.split('\n')
  print(str_arr)
  new_str = []

  for substring in str_arr:
    count = 0
    for mark in markers:
        if mark in substring:
            count +=1
    if count == 0:
        new_str.append(substring)
    for char in substring:
        if char in markers:
            sbstr = substring[:substring.index(char)-1]
            new_str.append(sbstr.strip())
            if str_arr.index(substring) == len(str_arr)-1:
                break
            print(new_str)

    solution = '\n'.join(new_str)
    return solution
</code>```

I first check if the substring even has the marker in it and if not, I add it to the new list. This solution works for most of the tests provided by Codewars, but for some reason, there are tests which this function just won't solve. One of them is:

Testing for solution("! apples bananas bananas apples -\nwatermelons '\npears cherries oranges ^ apples\ncherries watermelons strawberries bananas strawberries", ['@', ',', '=', '-', "'", '!'])

, where my output is:

It should work with random inputs too: '! apples bananas bananas apples\n! apples bananas bananas apples\nwatermelons\npears cherries oranges ^ apples\ncherries watermelons strawberries bananas strawberries' should equal '\nwatermelons\npears cherries oranges ^ apples\ncherries watermelons strawberries bananas strawberries'

Currently, I don't know how to tackle these issues, especially since the function works perfectly well for around 40/48 cases. Thanks for any suggestions on how I could improve my code.

答:
First up, you're supposed to remove only the trailing spaces.
Use rstrip for that. strip will remove whitspaces from both ends.

Next, you should join the final strings.

I'll leave the code for reference:

def solution(string, markers):
    ss = string.split('\n')
    for i in range(len(ss)):
        s = ss[i]
        for marker in markers:
            index = s.find(marker)
            if index >= 0:
                s = s[:index].rstrip()
        ss[i] = s
    return '\n'.join(ss)
```

ContentLicense: CC BY-SA 4.0

Body:
I am currently on the 4kyu problem on Codewars, where given a string and a list of characters, your function is supposed to remove the characters in the string and any other characters that follow, up to the end of the line. I came up with a solution that I think should work. Since I need to remove every character in the string after the special character is found, I split the string by '\n' since that marks the end of the line.
Then I proceeded to write the function that checks all the substrings:

def solution(string,markers):
  str_arr = string.split('\n')
  print(str_arr)
  new_str = []

  for substring in str_arr:
    count = 0
    for mark in markers:
        if mark in substring:
            count +=1
    if count == 0:
        new_str.append(substring)
    for char in substring:
        if char in markers:
            sbstr = substring[:substring.index(char)-1]
            new_str.append(sbstr.strip())
            if str_arr.index(substring) == len(str_arr)-1:
                break
            print(new_str)

    solution = '\n'.join(new_str)
    return solution

I first check if the substring even has the marker in it and if not, I add it to the new list. This solution works for most of the tests provided by Codewars, but for some reason, there are tests which this function just won't solve. One of them is:

Testing for solution("! apples bananas bananas apples -\nwatermelons '\npears cherries oranges ^ apples\ncherries watermelons strawberries bananas strawberries", ['@', ',', '=', '-', "'", '!'])

, where my output is:

It should work with random inputs too: '! apples bananas bananas apples\n! apples bananas bananas apples\nwatermelons\npears cherries oranges ^ apples\ncherries watermelons strawberries bananas strawberries' should equal '\nwatermelons\npears cherries oranges ^ apples\ncherries watermelons strawberries bananas strawberries'

Currently, I don't know how to tackle these issues, especially since the function works perfectly well for around 40/48 cases. Thanks for any suggestions on how I could improve my code.


问:
the character moves immediately when the scene starts
the character, when starting the scene moves immediately, we need him to move left or right by pressing the buttons, help solve the problem
I add a screenshot of the code that is on the character and a screenshot of the code that is on the buttons

答:
In Update -which works every frame- your code checks if position is equal to smth and if not adds velocity to gameobject.

If you want this to occur when pressing buttons it's better to use Input.getkeydown event.

fore example:

```<code>void Update()
{
    if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        run = 1f;
    }else
    if (Input.GetKeyDown(KeyCode.LeftArrow))
    {
        run = -1f;
    }
    else
    {
        run = 0f;
    }
     rb.velocity = new Vector2(run, transform.position.y);
}
</code>```

Body:
In Update -which works every frame- your code checks if position is equal to smth and if not adds velocity to gameobject.

If you want this to occur when pressing buttons it's better to use Input.getkeydown event.

fore example:

void Update()
{
    if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        run = 1f;
    }else
    if (Input.GetKeyDown(KeyCode.LeftArrow))
    {
        run = -1f;
    }
    else
    {
        run = 0f;
    }
     rb.velocity = new Vector2(run, transform.position.y);
}


问:
React conditional rendering only partially happening
I have a react component that is displaying the results of an array as a Badge (from Bootstrap React library). In the condition, I'm checking if the length of array is greater than zero and rendering the results using a map function. I wanted to add additional text to also display on the condition but for some reason it is not displaying the h1 tag yet the badges are being displayed. Why isn't it displaying the h1 tag??

```<code>render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>
      <div>
       {arr.length > 0 && <h1>Additional Text</h1> &&
        arr.map((item) =>
        <Badge key={item.toString()} pill variant='primary'>
          {item}
        </Badge>
       }
     </div>
    </Card.Body>
   </Card>
);
</code>```

答:
This is because arr.length > 0 &&
Additional Text
 evaluates to true and you see the tags.

A cleaner approach would be to do something like this (just a suggestion, there are many other possible and equally correct ways):

```<code>const getPills = (items) => {
    const pills = [<h1>Additional Text</h1>];
    items.forEach(item => {
        pills.push(
            <Badge key={item.toString()} pill variant='primary'>
                {item}
            </Badge>
        );
    })
    return pills;
};

render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>
      <div>
       {arr.length ? getPills(arr) : ''}
     </div>
    </Card.Body>
   </Card>
);
</code>```

Body:
I have a react component that is displaying the results of an array as a Badge (from Bootstrap React library). In the condition, I'm checking if the length of array is greater than zero and rendering the results using a map function. I wanted to add additional text to also display on the condition but for some reason it is not displaying the h1 tag yet the badges are being displayed. Why isn't it displaying the h1 tag??

render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>

       {arr.length > 0 &&
Additional Text
 &&
        arr.map((item) =>
        <Badge key={item.toString()} pill variant='primary'>
          {item}
        </Badge>
       }

    </Card.Body>
   </Card>
);

Body:
This is because arr.length > 0 && <h1>Additional Text</h1> evaluates to true and you see the tags.

A cleaner approach would be to do something like this (just a suggestion, there are many other possible and equally correct ways):

const getPills = (items) => {
    const pills = [<h1>Additional Text</h1>];
    items.forEach(item => {
        pills.push(
            <Badge key={item.toString()} pill variant='primary'>
                {item}
            </Badge>
        );
    })
    return pills;
};

render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>
      <div>
       {arr.length ? getPills(arr) : ''}
     </div>
    </Card.Body>
   </Card>
);


问:
Get Full Range Text to String
I'm writing a script that looks through my outgoing emails and searches for frequent stylistic errors I make. It locates them using regex and then highlights them yellow. Code:

```<code>Public Sub highlightBadForm()

    Dim oWordDoc As Object
    Dim oMatches As Object
    Dim oRange As Range
    Dim strText As String
    Dim lngFindFrom As Long
    Dim varMtch As Variant

    Set oWordDoc = Application.ActiveInspector.WordEditor
    strText = LCase(oWordDoc.Range.Text)

    lngFindFrom = InStr(strText, "from: ")
    If lngFindFrom > 0 Then
        strText = Left(strText, lngFindFrom - 1)
    End If

    Set oMatches = extractMatches(strText, getBadStrs)
    If Not oMatches Is Nothing Then
        For Each varMtch In oMatches
                Set oRange = oWordDoc.Range(varMtch.firstindex, varMtch.firstindex + varMtch.Length)
                oRange.HighlightColorIndex = wdYellow
        Next varMtch
    End If

    Set oRange = Nothing
    Set oWordDoc = Nothing
    Set oMatches = Nothing
End Sub
</code>```

extractMatches is a private function implementing VBA's RegEx engine. getBadStrs returns the regular expression containing the errors.

It all works unless I've embedded hyperlinks in my email. If so, oWordDoc.Range.Text returns only the anchor text of the links, not the links (and any other characters Word pads the hyperlinks with - I don't know what they might be). As a result, varMtch.firstindex is correct for strText but not oRange so the text it highlights is offset by several characters.

I tried to assemble the full oRange text by looping through the hyperlinks in oRange and adding the link text to the string assuming it would be included in oRange. Something like:

```<code>Dim lngEndLnk as Long
Set oRange = oWordDoc.Range

For Each varMtch In oRange.Hyperlinks
    strText = strText & oWordDoc.Range(lngEndLnk, varMtch.Range.Start)
    strText = strText & varMtch.TextToDisplay & varMtch.Name
    lngEndLnk = varMtch.Range.End
Next varMtch

If lngEndLnk = 0 Then
    strText = oRange.text
Else
    strText = strText & oWordDoc.Range(lngEndLnk, oWordDoc.Range.End)
End If
</code>```

That reduced the offset, but there still is one. Also, if I were to include a linked image in the email, the .Anchor property of varMtch fails so I'd have to come up with another workaround.

Is there a more straightforward way to get a String containing all the characters of the Range object so the regex indices line up?

答:
I ended up with a similar solution to @slightly snarky. I don't know that it's better so I won't mark it as the solution. Happy for comments on pros and cons, in case there's a clear winner I'm just not seeing.

Personally, I like looping the character collection and probably should use it in my code, this works. I find using the position array to highlight matches much less intuitive than constructing a string from the range. For my purposes padding the string with # in place of the zero-length characters in oWordDoc.Range works, but I also know it won't work for everybody.

```<code>Public Sub highlightBadForm()

    Dim oWordDoc As Object
    Dim oMatches As Object
    Dim oRange As Range
    Dim strText As String
    Dim lngFindFrom As Long, lngC As Long, lngPrevLen As Long
    Dim varMtch As Variant

    Set oWordDoc = Application.ActiveInspector.WordEditor

    For lngC = 0 To oWordDoc.Range.End - 1
        strText = strText & oWordDoc.Range(lngC, lngC + 1)
        If Len(strText) = lngPrevLen Then
            strText = strText & "#"
        End If
        lngPrevLen = lngPrevLen + 1
    Next lngC
    strText = LCase(strText)

    lngFindFrom = InStr(strText, "from: ")
    If lngFindFrom > 0 Then
        strText = Left(strText, lngFindFrom - 1)
    End If

    Set oMatches = extractMatches(strText, getBadStrs)
    If Not oMatches Is Nothing Then
        For Each varMtch In oMatches
                Set oRange = oWordDoc.Range(varMtch.FirstIndex, varMtch.FirstIndex + varMtch.Length)
                oRange.HighlightColorIndex = wdYellow
        Next varMtch
    End If

    Set oRange = Nothing
    Set oWordDoc = Nothing
    Set oMatches = Nothing
End Sub
</code>```

Title: Get Full Range Text to String

Body:
I'm writing a script that looks through my outgoing emails and searches for frequent stylistic errors I make. It locates them using regex and then highlights them yellow. Code:

Public Sub highlightBadForm()

    Dim oWordDoc As Object
    Dim oMatches As Object
    Dim oRange As Range
    Dim strText As String
    Dim lngFindFrom As Long
    Dim varMtch As Variant

    Set oWordDoc = Application.ActiveInspector.WordEditor
    strText = LCase(oWordDoc.Range.Text)

    lngFindFrom = InStr(strText, "from: ")
    If lngFindFrom > 0 Then
        strText = Left(strText, lngFindFrom - 1)
    End If

    Set oMatches = extractMatches(strText, getBadStrs)
    If Not oMatches Is Nothing Then
        For Each varMtch In oMatches
                Set oRange = oWordDoc.Range(varMtch.firstindex, varMtch.firstindex + varMtch.Length)
                oRange.HighlightColorIndex = wdYellow
        Next varMtch
    End If

    Set oRange = Nothing
    Set oWordDoc = Nothing
    Set oMatches = Nothing
End Sub

extractMatches is a private function implementing VBA's RegEx engine. getBadStrs returns the regular expression containing the errors.

It all works unless I've embedded hyperlinks in my email. If so, oWordDoc.Range.Text returns only the anchor text of the links, not the links (and any other characters Word pads the hyperlinks with - I don't know what they might be). As a result, varMtch.firstindex is correct for strText but not oRange so the text it highlights is offset by several characters.

I tried to assemble the full oRange text by looping through the hyperlinks in oRange and adding the link text to the string assuming it would be included in oRange. Something like:

Dim lngEndLnk as Long
Set oRange = oWordDoc.Range

For Each varMtch In oRange.Hyperlinks
    strText = strText & oWordDoc.Range(lngEndLnk, varMtch.Range.Start)
    strText = strText & varMtch.TextToDisplay & varMtch.Name
    lngEndLnk = varMtch.Range.End
Next varMtch

If lngEndLnk = 0 Then
    strText = oRange.text
Else
    strText = strText & oWordDoc.Range(lngEndLnk, oWordDoc.Range.End)
End If

That reduced the offset, but there still is one. Also, if I were to include a linked image in the email, the .Anchor property of varMtch fails so I'd have to come up with another workaround.

Is there a more straightforward way to get a String containing all the characters of the Range object so the regex indices line up?

Body:
I ended up with a similar solution to @slightly snarky. I don't know that it's better so I won't mark it as the solution. Happy for comments on pros and cons, in case there's a clear winner I'm just not seeing.

Personally, I like looping the character collection and probably should use it in my code, this works. I find using the position array to highlight matches much less intuitive than constructing a string from the range. For my purposes padding the string with # in place of the zero-length characters in oWordDoc.Range works, but I also know it won't work for everybody.

Public Sub highlightBadForm()

    Dim oWordDoc As Object
    Dim oMatches As Object
    Dim oRange As Range
    Dim strText As String
    Dim lngFindFrom As Long, lngC As Long, lngPrevLen As Long
    Dim varMtch As Variant

    Set oWordDoc = Application.ActiveInspector.WordEditor

    For lngC = 0 To oWordDoc.Range.End - 1
        strText = strText & oWordDoc.Range(lngC, lngC + 1)
        If Len(strText) = lngPrevLen Then
            strText = strText & "#"
        End If
        lngPrevLen = lngPrevLen + 1
    Next lngC
    strText = LCase(strText)

    lngFindFrom = InStr(strText, "from: ")
    If lngFindFrom > 0 Then
        strText = Left(strText, lngFindFrom - 1)
    End If

    Set oMatches = extractMatches(strText, getBadStrs)
    If Not oMatches Is Nothing Then
        For Each varMtch In oMatches
                Set oRange = oWordDoc.Range(varMtch.FirstIndex, varMtch.FirstIndex + varMtch.Length)
                oRange.HighlightColorIndex = wdYellow
        Next varMtch
    End If

    Set oRange = Nothing
    Set oWordDoc = Nothing
    Set oMatches = Nothing
End Sub


答:
Try wrapping your content in a div as you are having the same condition, so no need to duplicate condition, like this:</p>

```<code>render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>
       {arr.length > 0 && (
       <div>
        <h1>Additional Text</h1>
        {arr.map((item) =>
          <Badge key={item.toString()} pill variant='primary'>
            {item}
          </Badge>
        }
       </div>)
    </Card.Body>
   </Card>
);
</code>```

Title: React conditional rendering only partially happening

Body:
Try wrapping your content in a div as you are having the same condition, so no need to duplicate condition, like this:

render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>
       {arr.length > 0 && (
       <div>
        <h1>Additional Text</h1>
        {arr.map((item) =>
          <Badge key={item.toString()} pill variant='primary'>
            {item}
          </Badge>
        }
       </div>)
    </Card.Body>
   </Card>
);


答:
because && checks its preceding condition or statement to be truthy

```<code> render() {
 const arr = this.state.items;
 return(
  <Card>
   <Card.Body>
    <div>
   {arr.length > 0 && <> <h1>Additional Text</h1>
    arr.map((item) =>
    <Badge key={item.toString()} pill variant='primary'>
      {item}
    </Badge>
    </>
   }
  </div>
 </Card.Body>
 </Card>
);
</code>```

Body:
because && checks its preceding condition or statement to be truthy

 render() {
 const arr = this.state.items;
 return(
  <Card>
   <Card.Body>
    <div>
   {arr.length > 0 && <> <h1>Additional Text</h1>
    arr.map((item) =>
    <Badge key={item.toString()} pill variant='primary'>
      {item}
    </Badge>
    </>
   }
  </div>
 </Card.Body>
 </Card>
);


问:
how to make a html element go fullscreen and automatically rotate to landscape in mobile browsers?
Calling requestFullscreen() method on video element does the job. Video goes fullscreen and also rotates to landscape in mobile browsers.

However calling this method on div element which is parent to my video element makes it fullscreen but does not rotate it to landscape when in portrait mode.

How can i rotate the whole div element to landscape?

答:
Have you styled your containing DIV to look differently in different orientation and when it is full screen? I'm guessing that is what you are missing.

Take a look at styling items for :fullscreen and media queries.

https://tympanus.net/codrops/css_reference/fullscreen/

https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries


问:
react-native-keyboard-aware-scroll-view : Page scrolls down when I start typing
Until typing everything is ok. However after starting typing page scrolls down(shifting). I am not able to solve this whatever i do...

```<code><ImageBackground
          source={bgSrc}
          style={styles.background}
          resizeMode="cover">

         <StatusBar hidden={true} />

          <KeyboardAwareScrollView
            showsVerticalScrollIndicator={false}
            enableOnAndroid
          >

            {screenToShow}

          </KeyboardAwareScrollView>

</ImageBackground>

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: height,
    backgroundColor: '#555',
  },
  background: {
    flex: 1,
    width: null,
    height: null,
    justifyContent: 'center',
    alignItems: 'center'
  }
});
</code>```

before typing, it's looking perfect

After typing in the password field page moves down as u see:

after typing, it scroll down

答:
I have seen your question on github as well, and its been a long time since that is in open state there.

I have the above problem resolved using KeyboardAvoidingView from react-native

import {KeyboardAvoidingView} from 'react-native'

I have replaced KeyboardAwareScrollView with KeyboardAvoidingView and this is working as needed.

Here is an app link that does this. You can download and see it's login page.

Body:
Until typing everything is ok. However after starting typing page scrolls down(shifting). I am not able to solve this whatever i do...

<ImageBackground
          source={bgSrc}
          style={styles.background}
          resizeMode="cover">

         <StatusBar hidden={true} />

          <KeyboardAwareScrollView
            showsVerticalScrollIndicator={false}
            enableOnAndroid
          >

            {screenToShow}

          </KeyboardAwareScrollView>

</ImageBackground>

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: height,
    backgroundColor: '#555',
  },
  background: {
    flex: 1,
    width: null,
    height: null,
    justifyContent: 'center',
    alignItems: 'center'
  }
});

before typing, it's looking perfect

After typing in the password field page moves down as u see:

after typing, it scroll down


问:
SQL Alchemy NameError: name
 is not defined
I wasn't sure what to call this, feel free to edit my post title.

Before I begin, I googled and looked here, but this didn't seem to help me.

My code:

```<code>import pyodbc
import pandas as pd
import numpy as np
import os
import sqlalchemy as sal
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import Table, Column, Integer, Numeric, String, ForeignKey, Boolean
##
from datetime import datetime
from sqlalchemy import DateTime
from sqlalchemy import PrimaryKeyConstraint, UniqueConstraint, CheckConstraint
from sqlalchemy import Index
from sqlalchemy import ForeignKeyConstraint
from sqlalchemy import insert
from sqlalchemy.sql import select
from sqlalchemy.sql import func
from sqlalchemy import cast
from sqlalchemy import and_, or_, not_
from sqlalchemy import update, delete
from sqlalchemy import text
##
import urllib

#############################################################
server = 'fake_server'
database = '_Testing_Only'
driver = 'SQL+SERVER+NATIVE+CLIENT+11.0'
trusted_connection='yes'

database_connection =  'mssql+pyodbc://fake_server/' + database + '?trusted_connection=' + trusted_connection + '&driver=' + driver

engine = sal.create_engine(database_connection)
connection=engine.connect()
metadata = MetaData()
print(engine.table_names())
</code>```

Here is the result of my print statement:

```<code>['cookies', 'line_items', 'orders', 'testing_sym_keys', 'users']
</code>```

I then tried to run this code:

```<code>s = select([cookies])
</code>```

I got the following error message:

```<code>Traceback (most recent call last):
  File "<pyshell#167>", line 1, in <module>
    s = select([cookies])
NameError: name 'cookies' is not defined
</code>```

The table clearly exists, why am I getting the error message?

答:
The issue is that you are not binding tables in the engine variable to a variable in your Python code.

Trying running a native SQL query of the form:

```<code>engine = create_engine(database_connection)
metadata = MetaData(engine)
metadata.reflect()

with engine.begin() as conn:
    conn.execute("select * from cookies")
</code>```

Other solution, if you want to use select method you can try this:

```<code>engine = create_engine(database_connection)
meta = MetaData(engine).reflect()
table = meta.tables['cookies']

# select * from 'cookies'
select_cookies = select([table])
</code>```

Title: SQL Alchemy NameError: name <table> is not defined

Body:
I wasn't sure what to call this, feel free to edit my post title.

Before I begin, I googled and looked here, but this didn't seem to help me.

My code:

import pyodbc
import pandas as pd
import numpy as np
import os
import sqlalchemy as sal
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import Table, Column, Integer, Numeric, String, ForeignKey, Boolean
##
from datetime import datetime
from sqlalchemy import DateTime
from sqlalchemy import PrimaryKeyConstraint, UniqueConstraint, CheckConstraint
from sqlalchemy import Index
from sqlalchemy import ForeignKeyConstraint
from sqlalchemy import insert
from sqlalchemy.sql import select
from sqlalchemy.sql import func
from sqlalchemy import cast
from sqlalchemy import and_, or_, not_
from sqlalchemy import update, delete
from sqlalchemy import text
##
import urllib

#############################################################
server = 'fake_server'
database = '_Testing_Only'
driver = 'SQL+SERVER+NATIVE+CLIENT+11.0'
trusted_connection='yes'

database_connection =  'mssql+pyodbc://fake_server/' + database + '?trusted_connection=' + trusted_connection + '&driver=' + driver

engine = sal.create_engine(database_connection)
connection=engine.connect()
metadata = MetaData()
print(engine.table_names())

Here is the result of my print statement:

['cookies', 'line_items', 'orders', 'testing_sym_keys', 'users']

I then tried to run this code:

s = select([cookies])

I got the following error message:

Traceback (most recent call last):
  File "<pyshell#167>", line 1, in <module>
    s = select([cookies])
NameError: name 'cookies' is not defined

The table clearly exists, why am I getting the error message?

Body:
The issue is that you are not binding tables in the engine variable to a variable in your Python code.

Trying running a native SQL query of the form:

engine = create_engine(database_connection)
metadata = MetaData(engine)
metadata.reflect()

with engine.begin() as conn:
    conn.execute("select * from cookies")

Other solution, if you want to use select method you can try this:

engine = create_engine(database_connection)
meta = MetaData(engine).reflect()
table = meta.tables['cookies']

# select * from 'cookies'
select_cookies = select([table])


问:
Caching variables in function with Jupyter
I have two cells. In the first one I set a variable and call a function,  and the second one contains the function definition which makes use of this variable.

When I refresh first cell, the output is always the same despite the value of variable changing. Only when I rerun the cell with the function definition does the output changes

```<code>In[]:  window=241
       window_t=count_frame_indeces2()
       window_t

Out[]: 241

In[]:  def count_frame_indeces2(window_f=window):
           return window_f
</code>```

Even if I change window to 22, output after rerunning this cell the output is still 241. How to avoid caching variable in this function?

答:
The default parameters of the functions get evaluated only at function definition time. So, when you run your second cell, window_f gets its default value from the current value of window.

When you ran your second cell for the first time, the value of window was apparently 241, so that's what the default value of window_f became.

Then, you change the value of window and call the function without parameter, so the default value (241) gets used.

When you ran the second cell a second time, you defined the function again, and it got the new value of window for its default parameter.

Either pass the parameter:

```<code>window_t=count_frame_indeces2(window)
</code>```

Or make the function use the current value of window if no parameter was passed with:

```<code>def count_frame_indeces2(window_f=None):
    if window_f is None:
        window_f = window

    return window_f
</code>```

Body:
I have two cells. In the first one I set a variable and call a function,  and the second one contains the function definition which makes use of this variable.

When I refresh first cell, the output is always the same despite the value of variable changing. Only when I rerun the cell with the function definition does the output changes

In[]:  window=241
       window_t=count_frame_indeces2()
       window_t

Out[]: 241

In[]:  def count_frame_indeces2(window_f=window):
           return window_f

Even if I change window to 22, output after rerunning this cell the output is still 241. How to avoid caching variable in this function?

Body:
The default parameters of the functions get evaluated only at function definition time. So, when you run your second cell, window_f gets its default value from the current value of window.

When you ran your second cell for the first time, the value of window was apparently 241, so that's what the default value of window_f became.

Then, you change the value of window and call the function without parameter, so the default value (241) gets used.

When you ran the second cell a second time, you defined the function again, and it got the new value of window for its default parameter.

Either pass the parameter:

window_t=count_frame_indeces2(window)

Or make the function use the current value of window if no parameter was passed with:

def count_frame_indeces2(window_f=None):
    if window_f is None:
        window_f = window

    return window_f


问:
Why async function in node js hides all data instead of specifed?
```<code>userSchema.methods.toJSON = async function(){
    const user = this
    const userObject = user.toObject()
    delete userObject.password
    delete userObject.tokens
    return userObject
}
</code>```

but when I use normal function it works all good

```<code>userSchema.methods.toJSON = async function(){
    const user = this
    const userObject = user.toObject()
    delete userObject.password
    delete userObject.tokens
    return userObject
}
</code>```

I am confused about the cause.
I would be grateful to know about it!

答:
this is because when you define a function like you did:

```<code>userSchema.methods.toJSON = function(){
  const user = this
  const userObject = user.toObject()
  delete userObject.password
  delete userObject.tokens
  return userObject
}

//..and then call

userSchema.methods.toJSON();

</code>```

and call the function, the result you expect is userObject. However, if you add the async syntax to the function the return of the function will be a Promise object with the userObject as the resolve of the Promise object.

So if you want to get the userObject:

```<code>userSchema.methods.toJSON = async function(){
  const user = this
  const userObject = user.toObject()
  delete userObject.password
  delete userObject.tokens
  return userObject
}

// And if you want to access your user object, you do this...

userSchema.methods.toJSON().then(function(userObject) {
  //...work with user object here
  console.log(userObject);
  //...
});
</code>```

check this out for more https://www.positronx.io/angular-8-es-6-typescript-promises-examples/

Body:
userSchema.methods.toJSON = async function(){
    const user = this
    const userObject = user.toObject()
    delete userObject.password
    delete userObject.tokens
    return userObject
}

but when I use normal function it works all good

userSchema.methods.toJSON = async function(){
    const user = this
    const userObject = user.toObject()
    delete userObject.password
    delete userObject.tokens
    return userObject
}

I am confused about the cause.
I would be grateful to know about it!

Body:
this is because when you define a function like you did:

userSchema.methods.toJSON = function(){
  const user = this
  const userObject = user.toObject()
  delete userObject.password
  delete userObject.tokens
  return userObject
}

//..and then call

userSchema.methods.toJSON();

and call the function, the result you expect is userObject. However, if you add the async syntax to the function the return of the function will be a Promise object with the userObject as the resolve of the Promise object.

So if you want to get the userObject:

userSchema.methods.toJSON = async function(){
  const user = this
  const userObject = user.toObject()
  delete userObject.password
  delete userObject.tokens
  return userObject
}

// And if you want to access your user object, you do this...

userSchema.methods.toJSON().then(function(userObject) {
  //...work with user object here
  console.log(userObject);
  //...
});

check this out for more https://www.positronx.io/angular-8-es-6-typescript-promises-examples/


问:
ERROR: dump failed because no AndroidManifest.xml found
When I try to upload an application to Android Play store I get the following error:

```<code>ERROR: dump failed because no AndroidManifest.xml found
</code>```

Steps that I took:

new HDD, install clean jre, jdk

download Android eclipse bundle - latest version today

make a new project, sample. simple hello world

sign it with the wizard, create a certificate etc.

try to upload it on the market...=ERROR!

I tried many combinations, different eclipse versions. Even to sign it manually. It doesn't work.
If I try to run aapt dump badging I get the same error.

答:
Just delete app.apk file from: /build/app/outputs/apk/app.apk.
Visual Studio will create a new correct app.apk file.

Body:
When I try to upload an application to Android Play store I get the following error:

ERROR: dump failed because no AndroidManifest.xml found

Steps that I took:

new HDD, install clean jre, jdk

download Android eclipse bundle - latest version today

make a new project, sample. simple hello world

sign it with the wizard, create a certificate etc.

try to upload it on the market...=ERROR!

I tried many combinations, different eclipse versions. Even to sign it manually. It doesn't work.
If I try to run aapt dump badging I get the same error.


问:
How to print in the first input?
When i run this code.

```<code>
number = int(input())
collect = [] #collect number from input
for i in range(number):
  x = int(input())
  collect.append(x)
print(collect)
for j in [ele for ind, ele in enumerate(collect,1) if ele not in collect[ind:]]:
    count = 0
    for ele in collect:
        if j == el:
            count += 1
        else:
            pass
    if count != 0:
        print("{} : {} Items".format(ind, count))
    else:
        print("{} : {} Item".format(j, count))
</code>```

```<code>**input:**  5
             2
             1
             2
             1
             2

**output:**

5

2
1
2
1
2

[2, 1, 2, 1, 2]

1 : 2 Items

2 : 3 Items
</code>```

I would like to show

output:

```<code>5

2
1
2
1
2

[2, 1, 2, 1, 2]

2 : 3 Items
1 : 2 Items

</code>```

How to do it

答:
```<code>number = int(input())
print()
collect = [] #collect number from input
for i in range(number):
  x = int(input("\n"))
  collect.append(x)
print("\n\n" + str(collect))
y = [ele for ind, ele in enumerate(collect,1) if ele not in collect[ind:]]
y.reverse()
for j in y:
    count = 0
    for ele in collect:
        if j == el:
            count += 1
        else:
            pass
    if count != 0:
        print("\n{} : {} Items".format(ind, count))
    else:
        print("\n{} : {} Item".format(j, count))
</code>```

Title: How to print in the first input?

Body:
When i run this code.

number = int(input())
collect = [] #collect number from input
for i in range(number):
  x = int(input())
  collect.append(x)
print(collect)
for j in [ele for ind, ele in enumerate(collect,1) if ele not in collect[ind:]]:
    count = 0
    for ele in collect:
        if j == el:
            count += 1
        else:
            pass
    if count != 0:
        print("{} : {} Items".format(ind, count))
    else:
        print("{} : {} Item".format(j, count))

**input:**  5
             2
             1
             2
             1
             2

**output:**

5

2
1
2
1
2

[2, 1, 2, 1, 2]

1 : 2 Items

2 : 3 Items

I would like to show

output:

5

2
1
2
1
2

[2, 1, 2, 1, 2]

2 : 3 Items
1 : 2 Items

How to do it


问:
Why the return value of my function is undefined?
guys, I'm just starting in the coding world. Now I'm learning JavaScript, so I have a problem, I have a function that is going to ask the user for the name.

Then I want to create another function using the name for ask for an integer, so when I try to call the return values from the first function is giving me undefined.

This is my code:

```<code>function getUsername() {
    var f1CustomerName;

    f1CustomerName = prompt("Please enter your name", "Type Here");
    // window.alert("f1CustomerName is: " + f1CustomerName );

    if ( f1CustomerName == null ) {
        return;
    } else if( f1CustomerName == "Type Here" || f1CustomerName == "" ) {
        return;
    } else {
        //window.alert("Hello " + f1CustomerName + "!");
        return f1CustomerName;
    }
}

var nameUser = getUsername();

// ...

function getinteger(nameUser) {
    var integer=prompt(nameUser + " Please enter an integer");
    window.alert("Hello this is your integer: " + integer + "!");
}

getinteger();
</code>```

答:
In your version of the function you did not return anything. The following should work:

function getUsername()
  {
     var f1CustomerName = prompt("Please enter your name", "Type Here");
     if( f1CustomerName == null || f1CustomerName == "Type Here") return "";
     else return f1CustomerName;
 }
 console.log(getUsername());```
</div>
</div>
</p>

<p>Here is an even shorter version of the same. As you only have one variable in your function it makes sense to shorten its name too (to <code>nam</code>). You can even
directly use the return value of the <code>getUsername()</code> function directly as a function argument in your <code>getinteger()</code> function call.</p>

<p>(But since you have <code>nameUser</code> in your <code>getinteger()</code> function's parameter list you can <em>not</em> access the global variable <code>userName</code> from within that function.)  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getUsername(){
  var nam = prompt("Please enter your name", "Type Here");
  return nam == null||nam=="Type Here" ? "" : nam ;
}
function getinteger(nameUser) {
    var integer=prompt(nameUser + " Please enter an integer");
    window.alert("Hello "+nameUser+", this is your integer: " + integer + "!");
}

getinteger(getUsername());</code>```

Body:
guys, I'm just starting in the coding world. Now I'm learning JavaScript, so I have a problem, I have a function that is going to ask the user for the name.

Then I want to create another function using the name for ask for an integer, so when I try to call the return values from the first function is giving me undefined.

This is my code:

function getUsername() {
    var f1CustomerName;

    f1CustomerName = prompt("Please enter your name", "Type Here");
    // window.alert("f1CustomerName is: " + f1CustomerName );

    if ( f1CustomerName == null ) {
        return;
    } else if( f1CustomerName == "Type Here" || f1CustomerName == "" ) {
        return;
    } else {
        //window.alert("Hello " + f1CustomerName + "!");
        return f1CustomerName;
    }
}

var nameUser = getUsername();

// ...

function getinteger(nameUser) {
    var integer=prompt(nameUser + " Please enter an integer");
    window.alert("Hello this is your integer: " + integer + "!");
}

getinteger();

Body:
In your version of the function you did not return anything. The following should work:

function getUsername()
  {
     var f1CustomerName = prompt("Please enter your name", "Type Here");
     if( f1CustomerName == null || f1CustomerName == "Type Here") return "";
     else return f1CustomerName;
 }
 console.log(getUsername());

Here is an even shorter version of the same. As you only have one variable in your function it makes sense to shorten its name too (to nam). You can even
directly use the return value of the getUsername() function directly as a function argument in your getinteger() function call.

(But since you have nameUser in your getinteger() function's parameter list you can not access the global variable userName from within that function.)

function getUsername(){
  var nam = prompt("Please enter your name", "Type Here");
  return nam == null||nam=="Type Here" ? "" : nam ;
}
function getinteger(nameUser) {
    var integer=prompt(nameUser + " Please enter an integer");
    window.alert("Hello "+nameUser+", this is your integer: " + integer + "!");
}

getinteger(getUsername());


问:
Change for-loop to while loop
How to change the  for-loop to a while loop?

```<code>for (i = 0; i < arr.length; i++) {
            if (arr[i] == k) {
                found = true;
                break;
            }

        }
</code>```

Code:

```<code>import java.util.Scanner;

class Algorithmus {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Geben sie den gesuchten Wert ein: ");
        int k = s.nextInt();
        System.out.println("Geben sie die Länge des Arrays ein: ");
        int n = s.nextInt();
        int arr[] = new int[n];
        int i = 0;
        System.out.println("Geben sie die Werte ein:");
        for(i = 0;i<n;i++){
            arr[i] = s.nextInt();
        }
        boolean found = false;
        for (i = 0; i < arr.length; i++) {
            if (arr[i] == k) {
                found = true;
                break;
            }

        }
        if (found==true) {
            System.out.println((i+1));
        } else {
            System.out.println((arr.length + 1));
        }
    }
}
</code>```

The structure should be:

```<code>BEGIN
Input: k1, ..., kn, k;
found := FALSE;
WHILE NOT found AND „not all elements were viewed“ DO
„take the next element ki“;
found := (ki = k)
END (* WHILE *);
IF found THEN
Output: i
ELSE
OUtput: n + 1
END (* IF *)
END
</code>```

答:
try this code</p>

```<code>import java.util.Scanner;

public class Algorithmus  {
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in);
            System.out.println("Geben sie den gesuchten Wert ein: ");
            int k = s.nextInt();
            System.out.println("Geben sie die Länge des Arrays ein: ");
            int n = s.nextInt();
            int arr[] = new int[n];
            int i = 0;
            System.out.println("Geben sie die Werte ein:");
            for(i = 0;i<n;i++){
                arr[i] = s.nextInt();
            }
            boolean found = false;
            i=0;
            while (i < arr.length) {

                if (arr[i] == k) {
                    found = true;
                    break;
                }
            i++;

            }

            if (found==true) {
                System.out.println((i+1));
            } else {
                System.out.println((arr.length + 1));
            }
        }
    }
</code>```

Title: Change for-loop to while loop

Body:
How to change the  for-loop to a while loop?

for (i = 0; i < arr.length; i++) {
            if (arr[i] == k) {
                found = true;
                break;
            }

        }

Code:

import java.util.Scanner;

class Algorithmus {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Geben sie den gesuchten Wert ein: ");
        int k = s.nextInt();
        System.out.println("Geben sie die Länge des Arrays ein: ");
        int n = s.nextInt();
        int arr[] = new int[n];
        int i = 0;
        System.out.println("Geben sie die Werte ein:");
        for(i = 0;i<n;i++){
            arr[i] = s.nextInt();
        }
        boolean found = false;
        for (i = 0; i < arr.length; i++) {
            if (arr[i] == k) {
                found = true;
                break;
            }

        }
        if (found==true) {
            System.out.println((i+1));
        } else {
            System.out.println((arr.length + 1));
        }
    }
}

The structure should be:

BEGIN
Input: k1, ..., kn, k;
found := FALSE;
WHILE NOT found AND „not all elements were viewed“ DO
„take the next element ki“;
found := (ki = k)
END (* WHILE *);
IF found THEN
Output: i
ELSE
OUtput: n + 1
END (* IF *)
END

Body:
try this code

import java.util.Scanner;

public class Algorithmus  {
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in);
            System.out.println("Geben sie den gesuchten Wert ein: ");
            int k = s.nextInt();
            System.out.println("Geben sie die Länge des Arrays ein: ");
            int n = s.nextInt();
            int arr[] = new int[n];
            int i = 0;
            System.out.println("Geben sie die Werte ein:");
            for(i = 0;i<n;i++){
                arr[i] = s.nextInt();
            }
            boolean found = false;
            i=0;
            while (i < arr.length) {

                if (arr[i] == k) {
                    found = true;
                    break;
                }
            i++;

            }

            if (found==true) {
                System.out.println((i+1));
            } else {
                System.out.println((arr.length + 1));
            }
        }
    }


问:
Having Side Effect of Component State Multiplying after each Route Change
I'm making a SPA Web Application for practice purpose but having trouble with React Rendering..My App usually has only two working routes Home & Upload. Home Route Fetches data from an API & displays it in the Body Component..With Upload I can upload products to the Database...Everything works fine except the Home Page...

When I come back to Home from another route the previous state remains same but for some reason the state gets multiplied & evrything just gets doubled I mean the fetched data gets doubled..Please help me....

My App's Body Component where Fetched data is displayed

```<code>//Importing Redux Action Creators
import {getProducts, deleteProduct} from "../Features/actions/productActions"
const Body = ({getProducts, deleteProduct, productState})=>{
    const {products, loading, error} = productState; //Destructuring redux State

     //Fetching data using redux actions inside useEffect hook
    useEffect(()=>{
    getProducts()
    },[getProducts])

    //Providing the payload as id for Redux Actions
    const deleteProducts = (id)=>{
        deleteProduct(id)
    }

    return (
        <div className="display-flex width-full flex-wrap justify-content-center">
            //Some Loading Logic for displaying data
            {!loading && !error && products?products.map(product=>(
                product.data?product.data.map(d=>(
                  //This is the component which displays the fetched data as bootstarp card
                    <BodyDiv
                        key={uuid.v4()}
                        imgSrc={d.imgSrc}
                        title={d.title}
                        details={d.details}
                        description={d.description}
                        onClick={()=>deleteProducts(d._id)}
                    />
                )):product.map(d=>(
                    <BodyDiv
                    key={uuid.v4()}
                    imgSrc={d.imgSrc}
                    title={d.title}
                    details={d.details}
                    description={d.description}
                    onClick={()=>deleteProducts(d._id)}
                />
                ))
            ))
            : loading&&!error
            ? <div className="vertical-center-strict horizontal-center-strict">Loading.......</div>
            : <div className="vertical-center-strict horizontal-center-strict">No Internet!</div>
        }
        </div>
    )
}
//The layout for displaying fetched data
const BodyDiv = (props)=>{
    return(
        <div className="container-div width-full card tiny-padding align-self-start">
        <img title={props.title} className="img-responsive hover-filter" src={props.imgSrc}/>
        <h2 className="text-align-center">{props.title}</h2>
        <h5>{props.details}</h5>
        <p className="text-align-justify">{props.description}</p>
        <button
        className="btn btn-danger"
        onClick={props.onClick}
        >Delete</button>
        </div>
    )
}
//mapping & dispatching state to props from redux
const mapStateToProps = (state)=>({
    productState: state.productState
})
//React-Redux Connect to connect the component with Store
const conn = connect(mapStateToProps, {getProducts, deleteProduct})(Body)

export default conn;
</code>```

My Redux State's Action Creators & Reducer

//Using redux-thunk for asynchronus middleware
export const getProducts = (payload)=>(dispatch)=>{
   return fetch("/api/products") //URL
    .then(res=>{
        dispatch({
            type:FETCHING_PRODUCTS //While fetching data
        })
        if(!res.ok){
            dispatch({
                type: ERROR_GET_PRODUCTS //If fetch fails then executes
            })
        }
    return res.json();
    })
    .then(json=>{
        if(json)dispatch({
        type: FETCHED_PRODUCTS,
        payload: json //Fetched json data as payload
    })
})
    .catch(err=>{
        console.log("Error!! failed to fetch data: "+ err)
    })
}

//Reducer Function

//initial state
const initialState = {
  products: [], //this the state where Fetched data gets injected...
  loading: true,
  error: false,
};

const productReducer = (state = initialState, action) => {
  switch (action.type) {
    case FETCHING_PRODUCTS:
      return {
        ...state,
        loading: true,
      };
    case FETCHED_PRODUCTS:
      return {
        ...state,
        products: state.products.concat(action.payload), //I don't know but I doubt here is the problem
        loading: false,
        error: false,
      };
    case ERROR_GET_PRODUCTS:
      return {
        ...state,
        loading: false,
      };
    default:
      return state;
  }
};

export default productReducer;
```

I believe that something is wrong with the useEffect() hook or Reducer Function..Some people would say that I should try using products state as useEffect dependencie but that makes the situation worse...Please guys help me!!! I have been trying to fix this since 1 day...Thanks!!

答:
Yes problems seems to be where you think it is

```<code> return {
        ...state,
         // the problem is here, you are adding products when in reality you just be just replacing them
        products: state.products.concat(action.payload), //I don't know but I doubt here is the problem
        loading: false,
        error: false,
      };
</code>```

replace this to

```<code>return {
        ...state,
        products: action.payload
        loading: false,
        error: false,
      };
</code>```

Body:
I'm making a SPA Web Application for practice purpose but having trouble with React Rendering..My App usually has only two working routes Home & Upload. Home Route Fetches data from an API & displays it in the Body Component..With Upload I can upload products to the Database...Everything works fine except the Home Page...

When I come back to Home from another route the previous state remains same but for some reason the state gets multiplied & evrything just gets doubled I mean the fetched data gets doubled..Please help me....

My App's Body Component where Fetched data is displayed

//Importing Redux Action Creators
import {getProducts, deleteProduct} from "../Features/actions/productActions"
const Body = ({getProducts, deleteProduct, productState})=>{
    const {products, loading, error} = productState; //Destructuring redux State

     //Fetching data using redux actions inside useEffect hook
    useEffect(()=>{
    getProducts()
    },[getProducts])

    //Providing the payload as id for Redux Actions
    const deleteProducts = (id)=>{
        deleteProduct(id)
    }

    return (

            //Some Loading Logic for displaying data
            {!loading && !error && products?products.map(product=>(
                product.data?product.data.map(d=>(
                  //This is the component which displays the fetched data as bootstarp card
                    <BodyDiv
                        key={uuid.v4()}
                        imgSrc={d.imgSrc}
                        title={d.title}
                        details={d.details}
                        description={d.description}
                        onClick={()=>deleteProducts(d._id)}
                    />
                )):product.map(d=>(
                    <BodyDiv
                    key={uuid.v4()}
                    imgSrc={d.imgSrc}
                    title={d.title}
                    details={d.details}
                    description={d.description}
                    onClick={()=>deleteProducts(d._id)}
                />
                ))
            ))
            : loading&&!error
            ?
Loading.......

            :
No Internet!

        }

    )
}
//The layout for displaying fetched data
const BodyDiv = (props)=>{
    return(

{props.title}

{props.details}

{props.description}

        <button
        className="btn btn-danger"
        onClick={props.onClick}
        >Delete</button>

    )
}
//mapping & dispatching state to props from redux
const mapStateToProps = (state)=>({
    productState: state.productState
})
//React-Redux Connect to connect the component with Store
const conn = connect(mapStateToProps, {getProducts, deleteProduct})(Body)

export default conn;

My Redux State's Action Creators & Reducer

//Using redux-thunk for asynchronus middleware
export const getProducts = (payload)=>(dispatch)=>{
   return fetch("/api/products") //URL
    .then(res=>{
        dispatch({
            type:FETCHING_PRODUCTS //While fetching data
        })
        if(!res.ok){
            dispatch({
                type: ERROR_GET_PRODUCTS //If fetch fails then executes
            })
        }
    return res.json();
    })
    .then(json=>{
        if(json)dispatch({
        type: FETCHED_PRODUCTS,
        payload: json //Fetched json data as payload
    })
})
    .catch(err=>{
        console.log("Error!! failed to fetch data: "+ err)
    })
}

//Reducer Function

//initial state
const initialState = {
  products: [], //this the state where Fetched data gets injected...
  loading: true,
  error: false,
};

const productReducer = (state = initialState, action) => {
  switch (action.type) {
    case FETCHING_PRODUCTS:
      return {
        ...state,
        loading: true,
      };
    case FETCHED_PRODUCTS:
      return {
        ...state,
        products: state.products.concat(action.payload), //I don't know but I doubt here is the problem
        loading: false,
        error: false,
      };
    case ERROR_GET_PRODUCTS:
      return {
        ...state,
        loading: false,
      };
    default:
      return state;
  }
};

export default productReducer;

I believe that something is wrong with the useEffect() hook or Reducer Function..Some people would say that I should try using products state as useEffect dependencie but that makes the situation worse...Please guys help me!!! I have been trying to fix this since 1 day...Thanks!!

Body:
Yes problems seems to be where you think it is

 return {
        ...state,
         // the problem is here, you are adding products when in reality you just be just replacing them
        products: state.products.concat(action.payload), //I don't know but I doubt here is the problem
        loading: false,
        error: false,
      };

replace this to

return {
        ...state,
        products: action.payload
        loading: false,
        error: false,
      };


问:
Pandas: groupby column A and make lists of tuples from other columns?
I would like to aggregate user transactions into lists in pandas. I can't figure out how to make a list comprised of more than one field. For example,

```<code>df = pd.DataFrame({'user':[1,1,2,2,3],
                   'time':[20,10,11,18, 15],
                   'amount':[10.99, 4.99, 2.99, 1.99, 10.99]})
</code>```

which looks like

```<code>    amount  time  user
0   10.99    20     1
1    4.99    10     1
2    2.99    11     2
3    1.99    18     2
4   10.99    15     3
</code>```

If I do

```<code>print(df.groupby('user')['time'].apply(list))
</code>```

I get

```<code>user
1    [20, 10]
2    [11, 18]
3        [15]
</code>```

but if I do

```<code>df.groupby('user')[['time', 'amount']].apply(list)
</code>```

I get

```<code>user
1    [time, amount]
2    [time, amount]
3    [time, amount]
</code>```

Thanks to an answer below, I learned I can do this

```<code>df.groupby('user').agg(lambda x: x.tolist()))
</code>```

to get

```<code>             amount      time
user
1     [10.99, 4.99]  [20, 10]
2      [2.99, 1.99]  [11, 18]
3           [10.99]      [15]
</code>```

but I'm going to want to sort time and amounts in the same order - so I can go through each users transactions in order.

I was looking for a way to produce this:

```<code>             amount-time-tuple
user
1     [(20, 10.99), (10, 4.99)]
2     [(11,  2.99), (18, 1.99)]
3     [(15, 10.99)]
</code>```

but maybe there is a way to do the sort without "tupling" the two columns?

答:
Make a new column for amount-time tuple atpair

```<code> df['atpair'] = list(zip(df.amount, df.time))
</code>```

The data frame looks like

```<code>        user  time  amount       atpair
    0     1    20   10.99  (10.99, 20)
    1     1    10    4.99   (4.99, 10)
    2     2    11    2.99   (2.99, 11)
    3     2    18    1.99   (1.99, 18)
    4     3    15   10.99  (10.99, 15)
</code>```

Now perform groupby and apply list append to atpair

```<code> df = df.groupby('user')['atpair'].apply(lambda x : x.values.tolist())
</code>```

The data frame looks like

```<code>user
1    [(10.99, 20), (4.99, 10)]
2     [(2.99, 11), (1.99, 18)]
3                [(10.99, 15)]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to aggregate user transactions into lists in pandas. I can't figure out how to make a list comprised of more than one field. For example,

df = pd.DataFrame({'user':[1,1,2,2,3],
                   'time':[20,10,11,18, 15],
                   'amount':[10.99, 4.99, 2.99, 1.99, 10.99]})

which looks like

    amount  time  user
0   10.99    20     1
1    4.99    10     1
2    2.99    11     2
3    1.99    18     2
4   10.99    15     3

If I do

print(df.groupby('user')['time'].apply(list))

I get

user
1    [20, 10]
2    [11, 18]
3        [15]

but if I do

df.groupby('user')[['time', 'amount']].apply(list)

I get

user
1    [time, amount]
2    [time, amount]
3    [time, amount]

Thanks to an answer below, I learned I can do this

df.groupby('user').agg(lambda x: x.tolist()))

to get

             amount      time
user
1     [10.99, 4.99]  [20, 10]
2      [2.99, 1.99]  [11, 18]
3           [10.99]      [15]

but I'm going to want to sort time and amounts in the same order - so I can go through each users transactions in order.

I was looking for a way to produce this:

             amount-time-tuple
user
1     [(20, 10.99), (10, 4.99)]
2     [(11,  2.99), (18, 1.99)]
3     [(15, 10.99)]

but maybe there is a way to do the sort without "tupling" the two columns?

Body:
Make a new column for amount-time tuple atpair

 df['atpair'] = list(zip(df.amount, df.time))

The data frame looks like

        user  time  amount       atpair
    0     1    20   10.99  (10.99, 20)
    1     1    10    4.99   (4.99, 10)
    2     2    11    2.99   (2.99, 11)
    3     2    18    1.99   (1.99, 18)
    4     3    15   10.99  (10.99, 15)

Now perform groupby and apply list append to atpair

 df = df.groupby('user')['atpair'].apply(lambda x : x.values.tolist())

The data frame looks like

user
1    [(10.99, 20), (4.99, 10)]
2     [(2.99, 11), (1.99, 18)]
3                [(10.99, 15)]


问:
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?

答:
You can simply iterate the collection, remember all names you've seen, and whenever you see a new name, take the id.

```<code>var seen = new HashSet<string>();
foreach (var item in items)
{
    if (!seen.Add(item.name))
    {
        Console.WriteLine(item.id);
    }
}
</code>```

Output:

```
1
3
5
```

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:
You can simply iterate the collection, remember all names you've seen, and whenever you see a new name, take the id.

var seen = new HashSet<string>();
foreach (var item in items)
{
    if (!seen.Add(item.name))
    {
        Console.WriteLine(item.id);
    }
}

Output:

1
3
5


问:
pygame pacman I want to know the meaning of the code
It's a function that got Ghost to follow player, but I don't understand.
I want to know the meaning of the code.

def followPlayer(g, dirs):
    d = ghosts[g].dir
    if d == 1 or d == 3:
        if player.x > ghosts[g].x and dirs[0] == 1: ghosts[g].dir = 0
        if player.x < ghosts[g].x and dirs[2] == 1: ghosts[g].dir = 2
    if d == 0 or d == 2:
        if player.y > ghosts[g].y and dirs[1] == 1 and not aboveCentre(ghosts[g]): ghosts[g].dir = 1
        if player.y < ghosts[g].y and dirs[3] == 1: ghosts[g].dir = 3
```

答:
The code determines the direction of movement of the ghost. The movement is encoded in ghosts[g].dir. 0 means right, 2 means left, 1 means down and 3 means up.

If the movement of the ghost is vertical (if d == 1 or d == 3), then it is evaluated if the movement direction has to be changed to a horizontal direction (0, 2).

If the movement of the ghost is horizontal (if d == 0 or d == 2:), then it is evaluated if the movement direction has to be changed to a vertical direction (1, 3).

If the movement to certain direction is allowed is stored in the list dirs.

For instance, the meaning of the following lines of code is:

```<code>if d == 1 or d == 3:
    if player.x > ghosts[g].x and dirs[0] == 1: ghosts[g].dir = 0
</code>```

if the movement is vertical (if d == 1 or d == 3:)

and the player is at the right of the ghost (player.x > ghosts[g].x)

and the movement to the right is allowed dirs[0] == 1

then change the direction of movement to the right ghosts[g].dir = 0

Body:
The code determines the direction of movement of the ghost. The movement is encoded in ghosts[g].dir. 0 means right, 2 means left, 1 means down and 3 means up.

If the movement of the ghost is vertical (if d == 1 or d == 3), then it is evaluated if the movement direction has to be changed to a horizontal direction (0, 2).

If the movement of the ghost is horizontal (if d == 0 or d == 2:), then it is evaluated if the movement direction has to be changed to a vertical direction (1, 3).

If the movement to certain direction is allowed is stored in the list dirs.

For instance, the meaning of the following lines of code is:

if d == 1 or d == 3:
    if player.x > ghosts[g].x and dirs[0] == 1: ghosts[g].dir = 0

if the movement is vertical (if d == 1 or d == 3:)

and the player is at the right of the ghost (player.x > ghosts[g].x)

and the movement to the right is allowed dirs[0] == 1

then change the direction of movement to the right ghosts[g].dir = 0


问:
set the waiting time for a command to all users: setTimeout
I set a wait time for the !corona command it works fine but I want to remove a wait time when the user enters the country abbreviation incorrectly. All my codes are as below.

In short, when a wrong country command is entered, for example "!corona US" should query a new one without waiting time.

actually this works fine but two people can start this command at the same time. once the command is entered I want a waiting period for everyone. this only gives a wait time for the member who uses it

const Discord = require("discord.js");
const fetch = require("node-fetch");
const hereTimeOut = new Set();

exports.run = async (bot, message, args) => {
    if (hereTimeOut.has(message.author.id)) {

        const waitsetTimeOut = new Discord.RichEmbed()
        waitsetTimeOut.setColor(0x00AE86)
        waitsetTimeOut.setTimestamp()
        waitsetTimeOut.setAuthor(message.author.username, message.author.avatarURL)
        waitsetTimeOut.setTitle("[wait a while]")
        waitsetTimeOut.setDescription('please wait 1 minute')
        return message.channel.sendEmbed(waitsetTimeOut);
    }else {

    let country = args.slice(0).join(' ');

    if(!country){

        fetch("https://covid19.mathdro.id/api/").then(res => res.json()).then(json => {

            const embed = new Discord.RichEmbed();
                embed.addField("**= Total Number of Cases =**",`**`+ json.confirmed['value'] +` person**`)
                embed.addField("**= Number of Healing Cases =**",`**`+ json.recovered['value'] +` person**`)
                embed.addField("**= Number of Cases Losing Life =**",`**`+ json.deaths['value'] +` person**`)
                embed.setColor(15962634)
                embed.setTitle('Worldwide COVID-19 Statistics')
            message.channel.send({embed: embed});

        });

    }else{

        fetch(`https://covid19.mathdro.id/api/countries/${country}`).then(res => res.json()).then(json => {

                const embed = new Discord.RichEmbed();
                    embed.addField("**= Total Number of Cases =**",`**`+ json.confirmed['value'] +` person**`)
                    embed.addField("**= Number of Healing Cases =**",`**`+ json.recovered['value'] +` person**`)
                    embed.addField("**= Number of Cases Losing Life =**",`**`+ json.deaths['value'] +` person**`)
                    embed.setColor(15962634)
                    embed.setTitle(`COVID-19 Statistics (${country})`)
                message.channel.send({embed: embed});

        }).catch(() => {

            message.reply("I couldn't find the country you are looking for, be careful not to use Turkish letters when writing the country. You can also write country abbreviations (ex: TR, USA, AZ)");

        });

    }

    hereTimeOut.add(message.author.id);
        setTimeout(() => {
          // Removes the user from the set after a minute
          hereTimeOut.delete(message.author.id);
        }, 60000);
    }

};

exports.conf = {
  enabled: true,
  guildOnly: true,
  aliases: ['corona'],
  permLevel: 0
};

exports.help = {
  name: "corona",
  description: "covid19",
  usage: "coronavirus"
};```
</div>
</div>
</p>

<p>part of the error it received when it used a wrong country command;</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>.catch(() => {
    message.reply("I couldn't find the country you are looking for, be careful not to use Turkish letters when writing the country. You can also write country abbreviations (ex: TR, USA, AZ)");
});</code>```

答:
You can use a variable to store whether the command is available to use or not, you can then edit it like this:

// Setup
let isAvailable = true,
  cooldownMS = 5000; // in ms, this is 5 seconds

// When you're running the command:
if (isAvailable) {
  isAvailable = false
  setTimeout(() => {
    isAvailable = true
  }, cooldownMS)
  // Run your command ...
} else {
  // The command is still cooling down, send a message to the user to let them know
}
```

Body:
I set a wait time for the !corona command it works fine but I want to remove a wait time when the user enters the country abbreviation incorrectly. All my codes are as below.

In short, when a wrong country command is entered, for example "!corona US" should query a new one without waiting time.

actually this works fine but two people can start this command at the same time. once the command is entered I want a waiting period for everyone. this only gives a wait time for the member who uses it

const Discord = require("discord.js");
const fetch = require("node-fetch");
const hereTimeOut = new Set();

exports.run = async (bot, message, args) => {
    if (hereTimeOut.has(message.author.id)) {

        const waitsetTimeOut = new Discord.RichEmbed()
        waitsetTimeOut.setColor(0x00AE86)
        waitsetTimeOut.setTimestamp()
        waitsetTimeOut.setAuthor(message.author.username, message.author.avatarURL)
        waitsetTimeOut.setTitle("[wait a while]")
        waitsetTimeOut.setDescription('please wait 1 minute')
        return message.channel.sendEmbed(waitsetTimeOut);
    }else {

    let country = args.slice(0).join(' ');

    if(!country){

        fetch("https://covid19.mathdro.id/api/").then(res => res.json()).then(json => {

            const embed = new Discord.RichEmbed();
                embed.addField("**= Total Number of Cases =**",`**`+ json.confirmed['value'] +` person**`)
                embed.addField("**= Number of Healing Cases =**",`**`+ json.recovered['value'] +` person**`)
                embed.addField("**= Number of Cases Losing Life =**",`**`+ json.deaths['value'] +` person**`)
                embed.setColor(15962634)
                embed.setTitle('Worldwide COVID-19 Statistics')
            message.channel.send({embed: embed});

        });

    }else{

        fetch(`https://covid19.mathdro.id/api/countries/${country}`).then(res => res.json()).then(json => {

                const embed = new Discord.RichEmbed();
                    embed.addField("**= Total Number of Cases =**",`**`+ json.confirmed['value'] +` person**`)
                    embed.addField("**= Number of Healing Cases =**",`**`+ json.recovered['value'] +` person**`)
                    embed.addField("**= Number of Cases Losing Life =**",`**`+ json.deaths['value'] +` person**`)
                    embed.setColor(15962634)
                    embed.setTitle(`COVID-19 Statistics (${country})`)
                message.channel.send({embed: embed});

        }).catch(() => {

            message.reply("I couldn't find the country you are looking for, be careful not to use Turkish letters when writing the country. You can also write country abbreviations (ex: TR, USA, AZ)");

        });

    }

    hereTimeOut.add(message.author.id);
        setTimeout(() => {
          // Removes the user from the set after a minute
          hereTimeOut.delete(message.author.id);
        }, 60000);
    }

};

exports.conf = {
  enabled: true,
  guildOnly: true,
  aliases: ['corona'],
  permLevel: 0
};

exports.help = {
  name: "corona",
  description: "covid19",
  usage: "coronavirus"
};

part of the error it received when it used a wrong country command;

.catch(() => {
    message.reply("I couldn't find the country you are looking for, be careful not to use Turkish letters when writing the country. You can also write country abbreviations (ex: TR, USA, AZ)");
});


问:
What is the application/vnd.github+json media type?
I was going through Github REST API v3 doc and found the media type application/vnd.github+json. I am familiar with traditional media types such as application/json, application/xml.

It seems to be that it is related to OpenAPI 3 specification. If I were to create my own media type, how would I go about creating one for a new a team which would be used by other teams?

答: I believe application/vnd.github+json is just the custom media type that is used for the Github api. The difference being that application/vnd.github+json allows to specify the api version and the format of the data being returned. Having a custom media type is useful for versioning an api and is why this was made in the first place.


问:
Python3 Multiprocessing os.fork operates on the same resource?
```<code>import os
a=[]
pid=os.fork()
if(pid!=0):
    a.append(1)
    print("Original: ", end='')
    print(a,id(a))
else:
    a.append(2)
    print("Child: ", end='')
    print(a,id(a))

# Result:
# Original: [1] 139725666412296
# Child: [2] 139725666412296
</code>```

1. Why the parent and the child process share the same resource id?

2. If they share the same id, after I appended 2 to the list, why child process didn't print out 2?

3.
I then printed out (in a new Jupyter notebook code block) what lst contains now after executing the above code block. It prints: [1]. If the parent process executes first and child process executes last, why lst isn't [1,2]?

答:
[Partial answer: I address your questions 1 and 2 but not 3.]

fork can be thought of as producing a process that starts with a copy of the parent process memory but then the two can be separately modified so the contents can diverge after the initial copy.  In fact for efficiency it is implemented as copy-on-write, so that any copying only takes place if and when memory pages are actually modified, but this fact should not affect the concept of it being a copy.

This means that, to answer your questions 1 and 2, the ID of the object is the same because it was created before the fork, but the assignments done after the fork will not be visible in the other process.  In any case, you have no control here over the timings of the execution in the parent and child process (but even if the timing varied, the results of each would not be affected, only possibly the order in which they were collated).

Body:
import os
a=[]
pid=os.fork()
if(pid!=0):
    a.append(1)
    print("Original: ", end='')
    print(a,id(a))
else:
    a.append(2)
    print("Child: ", end='')
    print(a,id(a))

# Result:
# Original: [1] 139725666412296
# Child: [2] 139725666412296

1. Why the parent and the child process share the same resource id?

2. If they share the same id, after I appended 2 to the list, why child process didn't print out 2?

3.
I then printed out (in a new Jupyter notebook code block) what lst contains now after executing the above code block. It prints: [1]. If the parent process executes first and child process executes last, why lst isn't [1,2]?