问:
How To Hide AppBar When Scrolling Down
I have an AppBar and other things in my layout. When the user scrolls down, I want AppBar(actually, the Toolbar to hide. This is what I have tried, the app bar isn't hiding all small part it just stays there. Actually I think the problem is with my header of the screen it gets collapsed and adds a small space when I scroll.

As you can see in second image some part stays it doesn't hide. I need to hide that part while scrolling.
Please provide me solution what am I doing wrong?

```<code><?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:orientation="vertical">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleTextAppearance="@style/TextAppearance.AppCompat.Title"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                app:titleEnabled="false">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical"
                    android:orientation="vertical">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">

                        <ImageView
                            android:id="@+id/slideIV"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:adjustViewBounds="true"
                            android:src="@drawable/ic_dish" />

                        <View
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_above="@+id/bottomButtonRL"
                            android:layout_gravity="bottom"
                            android:background="@drawable/gradient_bg" />

                        <View style="@style/itemBottomViewLarge" />

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_centerVertical="true"
                            android:layout_margin="@dimen/_20"
                            android:gravity="center_vertical"
                            android:orientation="vertical">

                            <de.hdodenhof.circleimageview.CircleImageView
                                android:layout_width="80dp"
                                android:layout_height="80dp"
                                android:src="@drawable/fake_chef_bg"
                                app:civ_border_color="@color/border_grey_color"
                                app:civ_border_width="@dimen/_2" />

                            <LinearLayout
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_margin="@dimen/_5"
                                android:orientation="vertical">

                                <TextView
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:fontFamily="@font/bold_font"
                                    android:text="@string/fatima_al_zahraa"
                                    android:textColor="@color/white"
                                    android:textSize="@dimen/large_text_size"
                                    android:textStyle="bold" />

                                <TextView
                                    android:layout_width="wrap_content"
                                    android:layout_height="match_parent"
                                    android:fontFamily="@font/regular_font"
                                    android:text="@string/presenter_of_the_cuient"
                                    android:textColor="@color/white"
                                    android:textSize="@dimen/app_text_size" />
                            </LinearLayout>
                        </LinearLayout>

                        <RelativeLayout
                            android:id="@+id/bottomButtonRL"
                            android:layout_width="match_parent"
                            android:layout_height="50dp"
                            android:layout_below="@+id/slideIV"
                            android:layout_marginTop="-25dp">

                            <LinearLayout
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:orientation="vertical">

                                <View
                                    android:layout_width="match_parent"
                                    android:layout_height="@dimen/_0"
                                    android:layout_weight="1" />

                                <View
                                    android:layout_width="match_parent"
                                    android:layout_height="@dimen/_0"
                                    android:layout_weight="1"
                                    android:background="@color/defaultColor" />
                            </LinearLayout>

                            <LinearLayout
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:orientation="horizontal"
                                android:paddingStart="@dimen/_20"
                                android:paddingLeft="@dimen/_20">

                                <ImageView
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:adjustViewBounds="true"
                                    android:src="@drawable/ic_share" />

                                <RelativeLayout
                                    android:layout_width="220dp"
                                    android:layout_height="wrap_content"
                                    android:layout_marginStart="@dimen/_10"
                                    android:layout_marginLeft="@dimen/_10"
                                    android:background="@drawable/ic_rec1">

                                    <TextView
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent"
                                        android:fontFamily="@font/regular_font"
                                        android:gravity="center"
                                        android:layout_centerInParent="true"
                                        android:text="@string/add_to_fav"
                                        android:textColor="@color/white"
                                        android:textSize="@dimen/medium_text_size" />
                                </RelativeLayout>

                            </LinearLayout>

                        </RelativeLayout>
                    </RelativeLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="@drawable/bottom_radius_view">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/regular_font"
                            android:padding="@dimen/_20"
                            android:text="@string/galetes_fires_au_plates_fires_au_plates_fires_au_plates_fires_au_plates_fires_au_plates"
                            android:textColor="@color/white"
                            android:textSize="@dimen/app_text_size" />
                    </LinearLayout>
                </LinearLayout>

                <androidx.appcompat.widget.Toolbar
                    android:visibility="gone"
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    />
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>

        <androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:paddingLeft="@dimen/_20"
                android:paddingTop="@dimen/_10"
                android:paddingRight="@dimen/_20">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/bold_font"
                    android:padding="@dimen/_5"
                    android:text="@string/les_videos"
                    android:textColor="@color/medium_grey_text_color"
                    android:textSize="@dimen/large_text_size" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/itemFRV"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="@dimen/_5" />
            </LinearLayout>

        </androidx.core.widget.NestedScrollView>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>
</code>```

This is the header code:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/header_height"
        android:background="@color/white"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingLeft="@dimen/_20"
        android:paddingRight="@dimen/_20">

        <LinearLayout
            android:id="@+id/backLL"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="left"
            android:gravity="center"
            android:paddingRight="@dimen/_20"
            android:layout_marginBottom="@dimen/_10"
            android:visibility="gone">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:src="@drawable/ic_back" />
        </LinearLayout>

        <ImageView
            android:id="@+id/logoIV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:adjustViewBounds="true"
            android:paddingStart="0dp"
            android:paddingTop="@dimen/_15"
            android:paddingEnd="@dimen/_10"
            android:layout_marginBottom="@dimen/_10"
            android:src="@drawable/ic_header_logo" />

        <View
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <ImageView
            android:id="@+id/profileIV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:adjustViewBounds="true"
            android:paddingStart="@dimen/_10"
            android:paddingTop="@dimen/_15"
            android:paddingEnd="0dp"
            android:layout_marginBottom="@dimen/_10"
            android:src="@drawable/ic_default_user" />
    </LinearLayout>
</layout>
</code>```

答:
Change the layout_scrollFlags

app:layout_scrollFlags="scroll|exitUntilCollapsed"

replace above line with

app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"

Title: How To Hide AppBar When Scrolling Down

Body:
I have an AppBar and other things in my layout. When the user scrolls down, I want AppBar(actually, the Toolbar to hide. This is what I have tried, the app bar isn't hiding all small part it just stays there. Actually I think the problem is with my header of the screen it gets collapsed and adds a small space when I scroll.

As you can see in second image some part stays it doesn't hide. I need to hide that part while scrolling.
Please provide me solution what am I doing wrong?

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:orientation="vertical">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleTextAppearance="@style/TextAppearance.AppCompat.Title"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                app:titleEnabled="false">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical"
                    android:orientation="vertical">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">

                        <ImageView
                            android:id="@+id/slideIV"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:adjustViewBounds="true"
                            android:src="@drawable/ic_dish" />

                        <View
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_above="@+id/bottomButtonRL"
                            android:layout_gravity="bottom"
                            android:background="@drawable/gradient_bg" />

                        <View style="@style/itemBottomViewLarge" />

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_centerVertical="true"
                            android:layout_margin="@dimen/_20"
                            android:gravity="center_vertical"
                            android:orientation="vertical">

                            <de.hdodenhof.circleimageview.CircleImageView
                                android:layout_width="80dp"
                                android:layout_height="80dp"
                                android:src="@drawable/fake_chef_bg"
                                app:civ_border_color="@color/border_grey_color"
                                app:civ_border_width="@dimen/_2" />

                            <LinearLayout
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_margin="@dimen/_5"
                                android:orientation="vertical">

                                <TextView
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:fontFamily="@font/bold_font"
                                    android:text="@string/fatima_al_zahraa"
                                    android:textColor="@color/white"
                                    android:textSize="@dimen/large_text_size"
                                    android:textStyle="bold" />

                                <TextView
                                    android:layout_width="wrap_content"
                                    android:layout_height="match_parent"
                                    android:fontFamily="@font/regular_font"
                                    android:text="@string/presenter_of_the_cuient"
                                    android:textColor="@color/white"
                                    android:textSize="@dimen/app_text_size" />
                            </LinearLayout>
                        </LinearLayout>

                        <RelativeLayout
                            android:id="@+id/bottomButtonRL"
                            android:layout_width="match_parent"
                            android:layout_height="50dp"
                            android:layout_below="@+id/slideIV"
                            android:layout_marginTop="-25dp">

                            <LinearLayout
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:orientation="vertical">

                                <View
                                    android:layout_width="match_parent"
                                    android:layout_height="@dimen/_0"
                                    android:layout_weight="1" />

                                <View
                                    android:layout_width="match_parent"
                                    android:layout_height="@dimen/_0"
                                    android:layout_weight="1"
                                    android:background="@color/defaultColor" />
                            </LinearLayout>

                            <LinearLayout
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:orientation="horizontal"
                                android:paddingStart="@dimen/_20"
                                android:paddingLeft="@dimen/_20">

                                <ImageView
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:adjustViewBounds="true"
                                    android:src="@drawable/ic_share" />

                                <RelativeLayout
                                    android:layout_width="220dp"
                                    android:layout_height="wrap_content"
                                    android:layout_marginStart="@dimen/_10"
                                    android:layout_marginLeft="@dimen/_10"
                                    android:background="@drawable/ic_rec1">

                                    <TextView
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent"
                                        android:fontFamily="@font/regular_font"
                                        android:gravity="center"
                                        android:layout_centerInParent="true"
                                        android:text="@string/add_to_fav"
                                        android:textColor="@color/white"
                                        android:textSize="@dimen/medium_text_size" />
                                </RelativeLayout>

                            </LinearLayout>

                        </RelativeLayout>
                    </RelativeLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="@drawable/bottom_radius_view">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/regular_font"
                            android:padding="@dimen/_20"
                            android:text="@string/galetes_fires_au_plates_fires_au_plates_fires_au_plates_fires_au_plates_fires_au_plates"
                            android:textColor="@color/white"
                            android:textSize="@dimen/app_text_size" />
                    </LinearLayout>
                </LinearLayout>

                <androidx.appcompat.widget.Toolbar
                    android:visibility="gone"
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    />
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>

        <androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:paddingLeft="@dimen/_20"
                android:paddingTop="@dimen/_10"
                android:paddingRight="@dimen/_20">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/bold_font"
                    android:padding="@dimen/_5"
                    android:text="@string/les_videos"
                    android:textColor="@color/medium_grey_text_color"
                    android:textSize="@dimen/large_text_size" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/itemFRV"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="@dimen/_5" />
            </LinearLayout>

        </androidx.core.widget.NestedScrollView>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>

This is the header code:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/header_height"
        android:background="@color/white"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingLeft="@dimen/_20"
        android:paddingRight="@dimen/_20">

        <LinearLayout
            android:id="@+id/backLL"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="left"
            android:gravity="center"
            android:paddingRight="@dimen/_20"
            android:layout_marginBottom="@dimen/_10"
            android:visibility="gone">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:src="@drawable/ic_back" />
        </LinearLayout>

        <ImageView
            android:id="@+id/logoIV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:adjustViewBounds="true"
            android:paddingStart="0dp"
            android:paddingTop="@dimen/_15"
            android:paddingEnd="@dimen/_10"
            android:layout_marginBottom="@dimen/_10"
            android:src="@drawable/ic_header_logo" />

        <View
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <ImageView
            android:id="@+id/profileIV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:adjustViewBounds="true"
            android:paddingStart="@dimen/_10"
            android:paddingTop="@dimen/_15"
            android:paddingEnd="0dp"
            android:layout_marginBottom="@dimen/_10"
            android:src="@drawable/ic_default_user" />
    </LinearLayout>
</layout>


来源: stackexchange

问:
how to keep user logged in even when browser is closed in codeigniter
I have this problem in my login system that after login if user closes the window/browser and then open that same page it will ask to login again. I want to keep user logged in until user logs out.
I am using following code to login user

```<code>  public function adminLogin()
   {
   $email = $this->input->post('email');
   $password = md5($this->input->post('password'));
   $user = $this->login_model->getUserDate($email,$password);
   $user_data = array(
              'user_id' => $user['user_id'],
              'role' => $user['role'],
              'logged_in' => true
              );
   $this->session->set_userdata($user_data);
   redirect('admin-panel');
 }
</code>```

and this is config

```<code>$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 172800;//48 hours
$config['sess_save_path'] = APPPATH . 'session';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
</code>```

How can i achieve this, so that user doesn't have to login again when window/browser is closed and reopened.

答:
I think that you should use cookies with timer.

```<code><?php
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
</code>```

Check this source

ContentLicense: CC BY-SA 4.0

Body:
I have this problem in my login system that after login if user closes the window/browser and then open that same page it will ask to login again. I want to keep user logged in until user logs out.
I am using following code to login user

  public function adminLogin()
   {
   $email = $this->input->post('email');
   $password = md5($this->input->post('password'));
   $user = $this->login_model->getUserDate($email,$password);
   $user_data = array(
              'user_id' => $user['user_id'],
              'role' => $user['role'],
              'logged_in' => true
              );
   $this->session->set_userdata($user_data);
   redirect('admin-panel');
 }

and this is config

$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 172800;//48 hours
$config['sess_save_path'] = APPPATH . 'session';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

How can i achieve this, so that user doesn't have to login again when window/browser is closed and reopened.

Body:
I think that you should use cookies with timer.

<?php
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>

Check this source


问:
Replace Value with the number of times a group of numbers has appeared in the vector up to that point
I have a vector like this of 1s and 0s next to each other.

```<code>vec <- c(1,1,1,0,0,1,1,1,1,0,0,0,1,1,1)

</code>```

I want to replace the 1s with the number the consecutive 1s showed up so the final vector would look like the one below.

```<code>vec1 <- c(1,1,1,0,0,2,2,2,2,0,0,0,3,3,3)

</code>```

I am not sure how to even start with this problem. Any help is appreciated.

答:
One way using rle :

```<code>with(rle(vec), rep(values * cumsum(values), lengths))
#[1] 1 1 1 0 0 2 2 2 2 0 0 0 3 3 3
</code>```

Body:
I have a vector like this of 1s and 0s next to each other.

vec <- c(1,1,1,0,0,1,1,1,1,0,0,0,1,1,1)

I want to replace the 1s with the number the consecutive 1s showed up so the final vector would look like the one below.

vec1 <- c(1,1,1,0,0,2,2,2,2,0,0,0,3,3,3)

I am not sure how to even start with this problem. Any help is appreciated.

Body:
One way using rle :

with(rle(vec), rep(values * cumsum(values), lengths))
#[1] 1 1 1 0 0 2 2 2 2 0 0 0 3 3 3


问:
Convert integer value to fractional value (decimal)
Looking for a way to convert a positive number (integer) from e.g. 123 to 0.123 without using strings. Can be any size integer. Not concerned about negative values.

```<code>Dim value As Integer = 123
Dim num As Decimal = "." & value.ToString
</code>```

It seems simple but I'm not sure how to do it using math. How can I convert without using strings?

答:
You can get the number of digits using Log10.  I think the best way is thusly:

```<code>Dim value = 123 'Or whatever other value
Dim digitCount = Math.Floor(Math.Log10(Math.Abs(value))) + 1
Dim result = value * CDec(10 ^ (-digitCount))
</code>```

You need to use Floor rather than Ceiling in order to get the right result for 0, 10, 100, etc.

Body:
Looking for a way to convert a positive number (integer) from e.g. 123 to 0.123 without using strings. Can be any size integer. Not concerned about negative values.

Dim value As Integer = 123
Dim num As Decimal = "." & value.ToString

It seems simple but I'm not sure how to do it using math. How can I convert without using strings?

Body:
You can get the number of digits using Log10.  I think the best way is thusly:

Dim value = 123 'Or whatever other value
Dim digitCount = Math.Floor(Math.Log10(Math.Abs(value))) + 1
Dim result = value * CDec(10 ^ (-digitCount))

You need to use Floor rather than Ceiling in order to get the right result for 0, 10, 100, etc.


问:
how compilers detect overflow in numbers while compiling?
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255.

My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this case - against type limits?

I made a simple algorithm to do that for type 'int' for decimal, octal, hexadecimal and little endian binary but i don't think compiler do such thing like that to detect overflow in numbers.

the algorithm i made are coded in C++:

```<code>typedef signed char int8;
typedef signed int  int32;

#define DEC  0
#define HEX  1
#define OCT  2
#define BIN  3

bool isOverflow(const char* value, int32 base)
{
    // left-most digit for maximum and minimum number
    static const char* max_numbers[4][2] =
    {
        //                 INT_MAX                           INT_MIN
        {                       "2147483647",                       "2147483648" }, // decimal
        {                         "7fffffff",                         "80000000" }, // hexadecimal
        {                      "17777777777",                      "20000000000" }, // octal
        { "01111111111111111111111111111111", "10000000000000000000000000000000" }  // binary
    };

    // size of strings in max_numbers array
    static const int32 number_sizes[] = { 10, 8, 11, 32 };

    // input string size
    int32 str_len = strlen(value);

    // is sign mark exist in input string
    int32 signExist = ((base == DEC || base == OCT) && *value == '-');

    // first non zero digit in input number
    int32 non_zero_index = signExist;

    // locate first non zero index
    while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;

    // if non_zero_index equal length then all digits are zero
    if (non_zero_index == str_len) return false;

    // get number of digits that actually represent the number
    int32 diff = str_len - non_zero_index;

    // if difference less than 10 digits then no overflow will happened
    if (diff < number_sizes[base]) return false;
    // if difference greater than 10 digits then overflow will happened
    if (diff > number_sizes[base]) return true;

    // left digit in input and search strings
    int8 left1 = 0, left2 = 0;

    // if digits equal to 10 then loop over digits from left to right and compare
    for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
    {
        // get input digit
        left1 = value[non_zero_index];
        // get match digit
        left2 = max_numbers[signExist][i];

        // if digits not equal then if left1 is greater overflow will occurred, false otherwise
        if (left1 != left2) return left1 > left2;
    }

    // overflow won't happened
    return false;
}
</code>```

This algorithm can be optimized to work with all integers types but with float-point i have to make new one to work with IEEE float-point representation.

i think compilers use efficient algorithm to detect overflow other than mine, don't you?

答:
Compilers handle it pretty much the easiest possible way: they convert the number to an integer or float as appropriate.  There's no law that says the compiler can't convert from strings to some other representation as appropriate.

But now, consider your original problem; what about if you took the digits and just built routines to treat them as numbers?  Say, for example, an algorithm that could take

6 + 5

and compute the sum as a two-digit string 11?  Extend that to other operations and you could compute whether  32769 is greater than 32768 directly.

ContentLicense: CC BY-SA 3.0

Body:
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255.

My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this case - against type limits?

I made a simple algorithm to do that for type 'int' for decimal, octal, hexadecimal and little endian binary but i don't think compiler do such thing like that to detect overflow in numbers.

the algorithm i made are coded in C++:

typedef signed char int8;
typedef signed int  int32;

#define DEC  0
#define HEX  1
#define OCT  2
#define BIN  3

bool isOverflow(const char* value, int32 base)
{
    // left-most digit for maximum and minimum number
    static const char* max_numbers[4][2] =
    {
        //                 INT_MAX                           INT_MIN
        {                       "2147483647",                       "2147483648" }, // decimal
        {                         "7fffffff",                         "80000000" }, // hexadecimal
        {                      "17777777777",                      "20000000000" }, // octal
        { "01111111111111111111111111111111", "10000000000000000000000000000000" }  // binary
    };

    // size of strings in max_numbers array
    static const int32 number_sizes[] = { 10, 8, 11, 32 };

    // input string size
    int32 str_len = strlen(value);

    // is sign mark exist in input string
    int32 signExist = ((base == DEC || base == OCT) && *value == '-');

    // first non zero digit in input number
    int32 non_zero_index = signExist;

    // locate first non zero index
    while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;

    // if non_zero_index equal length then all digits are zero
    if (non_zero_index == str_len) return false;

    // get number of digits that actually represent the number
    int32 diff = str_len - non_zero_index;

    // if difference less than 10 digits then no overflow will happened
    if (diff < number_sizes[base]) return false;
    // if difference greater than 10 digits then overflow will happened
    if (diff > number_sizes[base]) return true;

    // left digit in input and search strings
    int8 left1 = 0, left2 = 0;

    // if digits equal to 10 then loop over digits from left to right and compare
    for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
    {
        // get input digit
        left1 = value[non_zero_index];
        // get match digit
        left2 = max_numbers[signExist][i];

        // if digits not equal then if left1 is greater overflow will occurred, false otherwise
        if (left1 != left2) return left1 > left2;
    }

    // overflow won't happened
    return false;
}

This algorithm can be optimized to work with all integers types but with float-point i have to make new one to work with IEEE float-point representation.

i think compilers use efficient algorithm to detect overflow other than mine, don't you?


问:
Python Using Adblock with Selenium and Firefox Webdriver
My goal is to use Adblock Plus with Selenium via Python. I have been able to get it to the point where it will load the extension, but by default it does not include the default filter "EasyList." Here is what I have so far:

```<code> from selenium import webdriver
 from time import sleep
 ffprofile = webdriver.FirefoxProfile()
 adblockfile = '/Users/username/Downloads/adblock_plus-2.4-tb+fx+an+sm.xpi'
 ffprofile.add_extension(adblockfile)
 ffprofile.set_preference("extensions.adblockplus.currentVersion", "2.4")
 browser = webdriver.Firefox(ffprofile)
 while(True):
    browser.get("www.cnn.com")
    sleep(5)
</code>```

Most of this code was ripped off of http://selenium-python.readthedocs.org/en/latest/faq.html

答:
I just recently found out how to block the first-run page without any issues by trial and error:

Go to the folder where your extension is located

In lib/adblockplus.js, set defaults.suppress_first_run_page to true instead of false.

Body:
My goal is to use Adblock Plus with Selenium via Python. I have been able to get it to the point where it will load the extension, but by default it does not include the default filter "EasyList." Here is what I have so far:

 from selenium import webdriver
 from time import sleep
 ffprofile = webdriver.FirefoxProfile()
 adblockfile = '/Users/username/Downloads/adblock_plus-2.4-tb+fx+an+sm.xpi'
 ffprofile.add_extension(adblockfile)
 ffprofile.set_preference("extensions.adblockplus.currentVersion", "2.4")
 browser = webdriver.Firefox(ffprofile)
 while(True):
    browser.get("www.cnn.com")
    sleep(5)

Most of this code was ripped off of http://selenium-python.readthedocs.org/en/latest/faq.html


问:
iText / BouncyCastle throws "java.lang.VerifyError: class overrides final method equals"
We have an application that creates PDFs unsing jasperreports.

It also manipulates said PDFs using iText after they have been created.

We recently started using encryption on some PDF. That means before the app can handle the PDF after its creation, it has to be decrypted. While attempting to do so using iText's PdfReader(String path, byte[] password) I get the following exception:

```<code>java.lang.VerifyError: class org.bouncycastle.asn1.ASN1Primitive overrides final method equals.(Ljava/lang/Object;)Z
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at com.simontuffs.onejar.JarClassLoader.defineClass(JarClassLoader.java:561)
    at com.simontuffs.onejar.JarClassLoader.findClass(JarClassLoader.java:475)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.itextpdf.text.pdf.PdfEncryption.<init>(PdfEncryption.java:148)
    at com.itextpdf.text.pdf.PdfReader.readDecryptedDocObj(PdfReader.java:914)
    at com.itextpdf.text.pdf.PdfReader.readDocObj(PdfReader.java:1294)
    at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:643)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:187)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:212)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:202)
</code>```

The project is built as a runnable .jar using Maven and uses the following dependencies:

iText 5.4.2

bouncycastle 1.48

I should mention that jasperreports has its own dependency of iText and bouncycastle:

iText 2.1.7

bouncycastle 1.38

I can't figure out what's going on on and need help.

答:
Had the same problem, and it got solved in a wierd way. All i had to do is to add bcprov-ext</p>

```<code>    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-ext-jdk15on</artifactId>
        <version>1.52</version>
    </dependency>
</code>```

Body:
We have an application that creates PDFs unsing jasperreports.

It also manipulates said PDFs using iText after they have been created.

We recently started using encryption on some PDF. That means before the app can handle the PDF after its creation, it has to be decrypted. While attempting to do so using iText's PdfReader(String path, byte[] password) I get the following exception:

java.lang.VerifyError: class org.bouncycastle.asn1.ASN1Primitive overrides final method equals.(Ljava/lang/Object;)Z
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at com.simontuffs.onejar.JarClassLoader.defineClass(JarClassLoader.java:561)
    at com.simontuffs.onejar.JarClassLoader.findClass(JarClassLoader.java:475)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.itextpdf.text.pdf.PdfEncryption.<init>(PdfEncryption.java:148)
    at com.itextpdf.text.pdf.PdfReader.readDecryptedDocObj(PdfReader.java:914)
    at com.itextpdf.text.pdf.PdfReader.readDocObj(PdfReader.java:1294)
    at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:643)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:187)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:212)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:202)

The project is built as a runnable .jar using Maven and uses the following dependencies:

iText 5.4.2

bouncycastle 1.48

I should mention that jasperreports has its own dependency of iText and bouncycastle:

iText 2.1.7

bouncycastle 1.38

I can't figure out what's going on on and need help.

Body:
Had the same problem, and it got solved in a wierd way. All i had to do is to add bcprov-ext

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-ext-jdk15on</artifactId>
        <version>1.52</version>
    </dependency>


问:
System.Security.Authentication.AuthenticationException: System error
I'm hosting an ASP.NET Core 3.1 web app with IIS 10, and it's throwing the following exception when trying to hit my API's through Postman:

```<code>System.Security.Authentication.AuthenticationException: System error.
   at Microsoft.AspNetCore.Authorization.AuthorizationHandler`1.HandleAsync(AuthorizationHandlerContext context)
   at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.AuthorizeAsync(ClaimsPrincipal user, Object resource, IEnumerable`1 requirements)
   at Microsoft.AspNetCore.Authorization.Policy.PolicyEvaluator.AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, Object resource)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
</code>```

When using Postman on the machine running the web app, I can make successful HTTP requests and not have any issues.  It seems to only be happening when trying to make external requests, but the error text is extremely unhelpful and I'm not sure where to begin diagnosing.  As far as I can tell, the directory containing the web app project files doesn't have any specific security restrictions and the Application Pool is using an account with sufficient permissions to access and use them.

Has anyone seen error text like this before, or have any idea what the issue might be?

答:
As it turns out, this exception was being thrown as a result of an incorrect database connection string.  This particular request checks against a local database to ensure the user exists there.

Strangely enough, I've encountered this same type of issue before (where a database connection string is broken / changed at some point), but the resulting exception was much more specific in its Exception text and stack trace.  The only thing I can't explain here is why the above error is so generic.

Body:
I'm hosting an ASP.NET Core 3.1 web app with IIS 10, and it's throwing the following exception when trying to hit my API's through Postman:

System.Security.Authentication.AuthenticationException: System error.
   at Microsoft.AspNetCore.Authorization.AuthorizationHandler`1.HandleAsync(AuthorizationHandlerContext context)
   at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.AuthorizeAsync(ClaimsPrincipal user, Object resource, IEnumerable`1 requirements)
   at Microsoft.AspNetCore.Authorization.Policy.PolicyEvaluator.AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, Object resource)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

When using Postman on the machine running the web app, I can make successful HTTP requests and not have any issues.  It seems to only be happening when trying to make external requests, but the error text is extremely unhelpful and I'm not sure where to begin diagnosing.  As far as I can tell, the directory containing the web app project files doesn't have any specific security restrictions and the Application Pool is using an account with sufficient permissions to access and use them.

Has anyone seen error text like this before, or have any idea what the issue might be?


问:
Geotools OSM Tile layer Failed to load image, can't create an ImageInputStream
I'am trying to print an OSM tiles in a given bounding box using geotools and the tile client,i have implemented a wms service that can read a wms request and render the image in a given boudning box, the OSM layer is used as a base layer,i have other layers that are vector layers that i can add later,vector layer are displayed correctly in the given bounding box but osm tiles are not displayed ,the Url used for sending the request to the osm server don't get any response ?i have the following error :

```<code>2020-05-27 16:03:00.291 ERROR 26094 --- [pool-6-thread-1] org.geotools.tile                        : Failed to load image: https://tile.openstreetmap.org/8/123/106.png

java.io.IOException: Can't create an ImageInputStream!
    at org.geotools.image.io.ImageIOExt.read(ImageIOExt.java:339) ~[gt-coverage-22.2.jar:na]
    at org.geotools.image.io.ImageIOExt.readBufferedImage(ImageIOExt.java:402) ~[gt-coverage-22.2.jar:na]
    at org.geotools.tile.Tile.loadImageTileImage(Tile.java:175) ~[gt-tile-client-22.2.jar:na]
    at org.geotools.tile.Tile.getBufferedImage(Tile.java:163) ~[gt-tile-client-22.2.jar:na]
    at org.geotools.tile.util.TileLayer.getTileImage(TileLayer.java:143) [gt-tile-client-22.2.jar:na]
    at org.geotools.tile.util.TileLayer.renderTile(TileLayer.java:131) [gt-tile-client-22.2.jar:na]
    at org.geotools.tile.util.TileLayer.renderTiles(TileLayer.java:125) [gt-tile-client-22.2.jar:na]
    at org.geotools.tile.util.TileLayer.draw(TileLayer.java:86) [gt-tile-client-22.2.jar:na]
    at org.geotools.renderer.lite.CompositingGroup$WrappingDirectLayer.draw(CompositingGroup.java:228) [gt-render-22.2.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer$RenderDirectLayerRequest.execute(StreamingRenderer.java:3850) [gt-render-22.2.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer$PainterThread.run(StreamingRenderer.java:3911) [gt-render-22.2.jar:na]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_232]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_232]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_232]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_232]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_232]
</code>```

for the source code these is how i add the osm tile layer :

```<code>MapContent mapContent = new MapContent();
String baseURL = "https://tile.openstreetmap.org/";
TileService service = new OSMService("OSM", baseURL);
mapContent.addLayer(new TileLayer(service));
</code>```

later i print it using gt-render :

```<code>StreamingRenderer renderer = new StreamingRenderer();
renderer.setMapContent(map);
ReferencedEnvelope mapBounds = mapRequest.getReferencedEnvelope();
Rectangle imageBounds = new Rectangle(0, 0, mapRequest.getWidth(), mapRequest.getHeight());

map.getViewport().setScreenArea(imageBounds);
map.getViewport().setBounds( mapBounds );

BufferedImage image = new BufferedImage(mapRequest.getWidth(), mapRequest.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D gr = image.createGraphics();

gr.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));

int threads = Runtime.getRuntime().availableProcessors();
ExecutorService fixedPool = Executors.newFixedThreadPool(threads - 1);
        renderer.setThreadPool(fixedPool);

try {
        renderer.paint(gr, imageBounds, mapBounds);
        ImageIO.write(image, imageExtension, os);
    }
catch (IOException e) {
            throw new RuntimeException(e);
    }

gr.dispose();
map.dispose();
</code>```

i have a hard coded version of the source code to test it:

```<code>  public void test(OutputStream os) throws NoSuchAuthorityCodeException, FactoryException {

        MapContent map = new MapContent();

        String baseURL = "https://tile.openstreetmap.org/";
        TileService service = new OSMService("OSM", baseURL);
        map.addLayer(new TileLayer(service));

        StreamingRenderer renderer = new StreamingRenderer();
        renderer.setMapContent(map);

        CoordinateReferenceSystem crs = CRS.decode("EPSG:3857");

        ReferencedEnvelope mapBounds = new ReferencedEnvelope(-939258.203568246,-626172.1357121639,3130860.67856082,3443946.746416902,crs);
        Rectangle imageBounds = new Rectangle(0, 0, 256, 256);

        map.getViewport().setScreenArea(imageBounds);
        map.getViewport().setBounds( mapBounds );

        BufferedImage image = new BufferedImage(256, 256,
                BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D gr = image.createGraphics();

        gr.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));

        try {
            renderer.paint(gr, imageBounds, mapBounds);
            ImageIO.write(image, imageExtension, os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        gr.dispose();
        map.dispose();
    }
</code>```

答:
The problem seems to be that OpenStreetMap will return an HTTP-429 error (Too Many Requests) if you don't set a valid User-Agent header in your requests.

I'm assuming this is a new requirement since the OSM tile code was last used or tested. Though looking at the test it may not actually fetch a tile to render.

I've raised a bug against gt-tile-client at the issue tracker and I have a PR to fix the issue, to add a header in as the WMTSTile implementation does.

It should be available in the master nightly build later today 30/5/2020.

Body:
I'am trying to print an OSM tiles in a given bounding box using geotools and the tile client,i have implemented a wms service that can read a wms request and render the image in a given boudning box, the OSM layer is used as a base layer,i have other layers that are vector layers that i can add later,vector layer are displayed correctly in the given bounding box but osm tiles are not displayed ,the Url used for sending the request to the osm server don't get any response ?i have the following error :

2020-05-27 16:03:00.291 ERROR 26094 --- [pool-6-thread-1] org.geotools.tile                        : Failed to load image: https://tile.openstreetmap.org/8/123/106.png

java.io.IOException: Can't create an ImageInputStream!
    at org.geotools.image.io.ImageIOExt.read(ImageIOExt.java:339) ~[gt-coverage-22.2.jar:na]
    at org.geotools.image.io.ImageIOExt.readBufferedImage(ImageIOExt.java:402) ~[gt-coverage-22.2.jar:na]
    at org.geotools.tile.Tile.loadImageTileImage(Tile.java:175) ~[gt-tile-client-22.2.jar:na]
    at org.geotools.tile.Tile.getBufferedImage(Tile.java:163) ~[gt-tile-client-22.2.jar:na]
    at org.geotools.tile.util.TileLayer.getTileImage(TileLayer.java:143) [gt-tile-client-22.2.jar:na]
    at org.geotools.tile.util.TileLayer.renderTile(TileLayer.java:131) [gt-tile-client-22.2.jar:na]
    at org.geotools.tile.util.TileLayer.renderTiles(TileLayer.java:125) [gt-tile-client-22.2.jar:na]
    at org.geotools.tile.util.TileLayer.draw(TileLayer.java:86) [gt-tile-client-22.2.jar:na]
    at org.geotools.renderer.lite.CompositingGroup$WrappingDirectLayer.draw(CompositingGroup.java:228) [gt-render-22.2.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer$RenderDirectLayerRequest.execute(StreamingRenderer.java:3850) [gt-render-22.2.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer$PainterThread.run(StreamingRenderer.java:3911) [gt-render-22.2.jar:na]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_232]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_232]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_232]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_232]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_232]

for the source code these is how i add the osm tile layer :

MapContent mapContent = new MapContent();
String baseURL = "https://tile.openstreetmap.org/";
TileService service = new OSMService("OSM", baseURL);
mapContent.addLayer(new TileLayer(service));

later i print it using gt-render :

StreamingRenderer renderer = new StreamingRenderer();
renderer.setMapContent(map);
ReferencedEnvelope mapBounds = mapRequest.getReferencedEnvelope();
Rectangle imageBounds = new Rectangle(0, 0, mapRequest.getWidth(), mapRequest.getHeight());

map.getViewport().setScreenArea(imageBounds);
map.getViewport().setBounds( mapBounds );

BufferedImage image = new BufferedImage(mapRequest.getWidth(), mapRequest.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D gr = image.createGraphics();

gr.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));

int threads = Runtime.getRuntime().availableProcessors();
ExecutorService fixedPool = Executors.newFixedThreadPool(threads - 1);
        renderer.setThreadPool(fixedPool);

try {
        renderer.paint(gr, imageBounds, mapBounds);
        ImageIO.write(image, imageExtension, os);
    }
catch (IOException e) {
            throw new RuntimeException(e);
    }

gr.dispose();
map.dispose();

i have a hard coded version of the source code to test it:

  public void test(OutputStream os) throws NoSuchAuthorityCodeException, FactoryException {

        MapContent map = new MapContent();

        String baseURL = "https://tile.openstreetmap.org/";
        TileService service = new OSMService("OSM", baseURL);
        map.addLayer(new TileLayer(service));

        StreamingRenderer renderer = new StreamingRenderer();
        renderer.setMapContent(map);

        CoordinateReferenceSystem crs = CRS.decode("EPSG:3857");

        ReferencedEnvelope mapBounds = new ReferencedEnvelope(-939258.203568246,-626172.1357121639,3130860.67856082,3443946.746416902,crs);
        Rectangle imageBounds = new Rectangle(0, 0, 256, 256);

        map.getViewport().setScreenArea(imageBounds);
        map.getViewport().setBounds( mapBounds );

        BufferedImage image = new BufferedImage(256, 256,
                BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D gr = image.createGraphics();

        gr.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));

        try {
            renderer.paint(gr, imageBounds, mapBounds);
            ImageIO.write(image, imageExtension, os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        gr.dispose();
        map.dispose();
    }


问:
Can C# Infer the Generic Parameter on Object Construction when there's an Explicit Reference Type?
Java can infer generic type parameters when the reference type is explicitly given. For example, both of these are fine:

```<code>Set<String> set = new HashSet<string>();
Set<String> set2 = new HashSet<>();
</code>```

Unfortunately if I try to do something similar in C# it doesn't seem supported:

```<code>//Doesn't compile
ISet<string> set = new HashSet<>();
//Works OK
ISet<string> set2 = new HashSet<string>();
</code>```

I get two compiler messages in C# from the above:

CS7003 Unexpected use of an unbound generic name

and

CS0266 Cannot implicitly convert type
  'System.Collections.Generic.HashSet' to
  'System.Collections.Generic.ISet'. An explicit conversion exists (are
  you missing a cast?)

Is this feature genuinely not supported or am I just missing out on some C# syntax?

答:
Thanks to a comment by canton7 we have an answer. The feature is not supported (yet) by C# but there are discussions around this in the pipelines. There are two possible directions this may be taken:

The Diamond Operator <>

There is the proposal to use the diamond operator, exactly as stated in the question:

https://github.com/dotnet/csharplang/issues/2935

This would allow one to use Java-like syntax as above, where the reference type is an interface and the object type is some implementation of that interface.

The new Keyword

There is the proposal to use the new keyword:

https://github.com/dotnet/csharplang/issues/100

This proposal, for example, would allow the following:

```<code>Point p = new Point(1, 2);
</code>```

To be replaced with simply:

```<code>Point p = new (1, 2);
</code>```

Indeed, for generic types, both the type, and any generics that come with it, would be inferred. So we could do, for example:

```<code>Hashset<string> set = new();
</code>```

This initially seems more powerful than the diamond operator proposal. However, returning to the original example from the question, this feature, if developed, would not work for the case where the reference type is an interface. In that case, it would be unclear which object to create from new. For example if we did:

```<code>ISet<string> set = new ();
</code>```

Then how would the compiler know which implementation of the ISet interface to use to instantiate an object of that type? So even if this feature were implemented, it wouldn't solve the use case where the reference type is an interface.

Body:
Java can infer generic type parameters when the reference type is explicitly given. For example, both of these are fine:

Set<String> set = new HashSet<string>();
Set<String> set2 = new HashSet<>();

Unfortunately if I try to do something similar in C# it doesn't seem supported:

//Doesn't compile
ISet<string> set = new HashSet<>();
//Works OK
ISet<string> set2 = new HashSet<string>();

I get two compiler messages in C# from the above:

CS7003 Unexpected use of an unbound generic name

and

CS0266 Cannot implicitly convert type
  'System.Collections.Generic.HashSet' to
  'System.Collections.Generic.ISet'. An explicit conversion exists (are
  you missing a cast?)

Is this feature genuinely not supported or am I just missing out on some C# syntax?

Body:
Thanks to a comment by canton7 we have an answer. The feature is not supported (yet) by C# but there are discussions around this in the pipelines. There are two possible directions this may be taken:

The Diamond Operator <>

There is the proposal to use the diamond operator, exactly as stated in the question:

https://github.com/dotnet/csharplang/issues/2935

This would allow one to use Java-like syntax as above, where the reference type is an interface and the object type is some implementation of that interface.

The new Keyword

There is the proposal to use the new keyword:

https://github.com/dotnet/csharplang/issues/100

This proposal, for example, would allow the following:

Point p = new Point(1, 2);

To be replaced with simply:

Point p = new (1, 2);

Indeed, for generic types, both the type, and any generics that come with it, would be inferred. So we could do, for example:

Hashset<string> set = new();

This initially seems more powerful than the diamond operator proposal. However, returning to the original example from the question, this feature, if developed, would not work for the case where the reference type is an interface. In that case, it would be unclear which object to create from new. For example if we did:

ISet<string> set = new ();

Then how would the compiler know which implementation of the ISet interface to use to instantiate an object of that type? So even if this feature were implemented, it wouldn't solve the use case where the reference type is an interface.


问:
npm install from github: Module not found: Can't resolve 'react-big-calendar'
I had to make some changes on react-big-calendar module so I forked the project on github, made modifications and pushed. Then I used this command to install the new package:

```<code>npm install https://github.com/wafa-yahyaoui/react-big-calendar/tarball/master --save
</code>```

The package figures out in the dependencies on package.json:

```<code>"dependencies": {
"@babel/runtime": "7.0.0-beta.55",
"@fortawesome/fontawesome-svg-core": "^1.2.10",
"@fortawesome/free-solid-svg-icons": "^5.6.1",
"@fortawesome/react-fontawesome": "^0.1.3",
"@material-ui/core": "^3.6.2",
"@material-ui/icons": "^2.0.3",
"@types/googlemaps": "3.30.11",
"@types/markerclustererplus": "2.1.33",
"ajv": "6.5.2",
"axios": "^0.18.0",
"bootstrap": "^4.1.3",
"chartist": "^0.11.0",
"classnames": "2.2.6",
"emotion": "^10.0.5",
"enhanced-resolve": "^3.4.1",
"globalize": "^1.4.0",
"history": "^4.7.2",
"iban": "0.0.11",
"jwt-decode": "^2.2.0",
"moment": "2.22.2",
"perfect-scrollbar": "1.4.0",
"react": "^16.6.3",
"react-big-calendar": "https://github.com/wafa-yahyaoui/react-big-calendar/tarball/master",
"react-bootstrap-sweetalert": "^4.4.1",
"react-chartist": "^0.13.1",
"react-datetime": "^2.16.3",
"react-dom": "^16.6.3",
"react-facebook-pixel": "^0.1.2",
"react-ga": "^2.5.6",
"react-google-maps": "^9.4.5",
"react-jvectormap": "0.0.3",
"react-nouislider": "2.0.1",
"react-redux": "^5.1.1",
"react-router": "4.3.1",
"react-router-dom": "^4.3.1",
"react-router-redux": "^5.0.0-alpha.9",
"react-scripts": "1.1.4",
"react-spinners": "^0.4.7",
"react-swipeable-views": "0.12.15",
"react-table": "6.8.6",
"react-tagsinput": "3.19.0",
"react-transition-group": "^1.2.1",
"reactstrap": "^6.5.0",
"redux": "^4.0.1",
"redux-api-middleware": "^2.3.0",
"redux-persist": "^5.10.0",
"redux-persist-transform-filter": "0.0.18",
"redux-thunk": "^2.3.0",
"universal-cookie": "^3.0.7"}
</code>```

I removed the node_modules folder, ran npm install but when running npm start I got this error:

```<code>./src/containers/apartments/calendar.js
Module not found: Can't resolve 'react-big-calendar' in
'/Users/wafayahyaoui/homereact/src/containers/apartments'
</code>```

The imports on calendar.js file looks like this:

```<code>import React from "react";
import BigCalendar from "react-big-calendar";
</code>```

What can be the source if the import error ? thank you

答:
I had a similar problem, so maybe it would be helpful to someone. main property from package.json was pointing to the built file which wasn't accessible, so I added a prepare script to run build before publishing the package.

```<code>"main": "dist/index.js",
"scripts": {
  "prepare": "npm run build"
}
</code>```

Body:
I had to make some changes on react-big-calendar module so I forked the project on github, made modifications and pushed. Then I used this command to install the new package:

npm install https://github.com/wafa-yahyaoui/react-big-calendar/tarball/master --save

The package figures out in the dependencies on package.json:

"dependencies": {
"@babel/runtime": "7.0.0-beta.55",
"@fortawesome/fontawesome-svg-core": "^1.2.10",
"@fortawesome/free-solid-svg-icons": "^5.6.1",
"@fortawesome/react-fontawesome": "^0.1.3",
"@material-ui/core": "^3.6.2",
"@material-ui/icons": "^2.0.3",
"@types/googlemaps": "3.30.11",
"@types/markerclustererplus": "2.1.33",
"ajv": "6.5.2",
"axios": "^0.18.0",
"bootstrap": "^4.1.3",
"chartist": "^0.11.0",
"classnames": "2.2.6",
"emotion": "^10.0.5",
"enhanced-resolve": "^3.4.1",
"globalize": "^1.4.0",
"history": "^4.7.2",
"iban": "0.0.11",
"jwt-decode": "^2.2.0",
"moment": "2.22.2",
"perfect-scrollbar": "1.4.0",
"react": "^16.6.3",
"react-big-calendar": "https://github.com/wafa-yahyaoui/react-big-calendar/tarball/master",
"react-bootstrap-sweetalert": "^4.4.1",
"react-chartist": "^0.13.1",
"react-datetime": "^2.16.3",
"react-dom": "^16.6.3",
"react-facebook-pixel": "^0.1.2",
"react-ga": "^2.5.6",
"react-google-maps": "^9.4.5",
"react-jvectormap": "0.0.3",
"react-nouislider": "2.0.1",
"react-redux": "^5.1.1",
"react-router": "4.3.1",
"react-router-dom": "^4.3.1",
"react-router-redux": "^5.0.0-alpha.9",
"react-scripts": "1.1.4",
"react-spinners": "^0.4.7",
"react-swipeable-views": "0.12.15",
"react-table": "6.8.6",
"react-tagsinput": "3.19.0",
"react-transition-group": "^1.2.1",
"reactstrap": "^6.5.0",
"redux": "^4.0.1",
"redux-api-middleware": "^2.3.0",
"redux-persist": "^5.10.0",
"redux-persist-transform-filter": "0.0.18",
"redux-thunk": "^2.3.0",
"universal-cookie": "^3.0.7"}

I removed the node_modules folder, ran npm install but when running npm start I got this error:

./src/containers/apartments/calendar.js
Module not found: Can't resolve 'react-big-calendar' in
'/Users/wafayahyaoui/homereact/src/containers/apartments'

The imports on calendar.js file looks like this:

import React from "react";
import BigCalendar from "react-big-calendar";

What can be the source if the import error ? thank you

Body:
I had a similar problem, so maybe it would be helpful to someone. main property from package.json was pointing to the built file which wasn't accessible, so I added a prepare script to run build before publishing the package.

"main": "dist/index.js",
"scripts": {
  "prepare": "npm run build"
}


问:
For loop crashes program while trying to read array c++
Exercise: The vector A[1 to N] and a value s is given. Build the program that writes backwards every group of s elements. If s divided by N has a remainder, then the remaining values should be unchanged. If s is bigger than N (the nr of elements of the vector) than there will be no modification.

Lets say s = 4 and  A = (1, 2, 3, 4, 5, 6, 7, 8)then after execution the values will be A = (4, 3, 2, 1, 8, 7, 6, 5)

My teacher requires this kind of vector: int n, A[n] where n is a value given by the user. And i think this is what is causing my program to crash when i read the final values. If not, where is the problem?

```<code>#include <iomanip>

using namespace std;

int ordering(int s, int n, int A[]);

int main()
{
    int n, A[n];
    int s;
    cout << "Vlera e s: ";
    cin >> s;

    if (s <= 0)
    {
        return 1;
    }

    cout << "\nN: ";
    cin >> n;

    if (n <= 0)
    {
        return 1;
    }

    cout << "\nVector:";
    for (int i = 0; i < n; i++)
    {
        A[i] = i + 1;
        cout << " " << A[i] << " ";
    }

    if (s > n)
    {
        cout << "\nNo change\n";
        return 0;
    }
    else
    {
        ordering(s, n, A);
    }

    cout << "\nNew vector:";
    for (int i = 0; i < n; i++)
    {
        cout << " " << A[i] << " ";
    }

    return 0;
}

int ordering(int s, int n, int A[])
{
    int counter = 0;
    for (int i = 0, divider = n / s; i < divider; i++)
    {
        int decrease = 0;
        for (int j = counter, a = counter + s; j < a; j++)
        {
            A[j] = a - decrease;
            decrease++;
        }
        counter += s;
    }
    return 0;
}
</code>```

答:
This program using a compiler extension to allow variable sized arrays in the form myArray[variableSize]. Whilst not standard, it does work on some compilers.

You are using this feature here:

```<code>int n, A[n];
</code>```

However, n is uninitialised at this point. This is undefined behaviour even on the compilers that support such variable sized arrays. One possible (but not the only) outcome of undefined behaviour is your program crashing.

Undefined behaviour can do anything in theory, but the realistic set of things in can do in reality is smaller. Some of the likely implications of the undefined behaviour here:

n has some huge number in it, from whatever last used that bit of memory. As a result, A is huge.

n is 0. You can't have a 0 sized array. If the compiler doesn't notice this, you could end up trashing memory.

Since n is uninitialised, the optimiser for the compiler (they usually do very some optimisations, even when on -O0) assumes that undefined behaviour cannot occur, which is violated here, leading to strange behaviour.

n is a reasonable value, just by luck, but because it is later updated it no longer matches the size of the array and you end up reading / writing memory off the end of the array, trashing memory.

There are other possibilities, but this gives an idea of the kind of things that can happen as a result of this specific instance of undefined behaviour. If you're interested to know more, using a debugger to step through the code in assembly (you only need learn a little to understand the output, it looks more scary than it need be) will show you what's actually happening.

Body:
Exercise: The vector A[1 to N] and a value s is given. Build the program that writes backwards every group of s elements. If s divided by N has a remainder, then the remaining values should be unchanged. If s is bigger than N (the nr of elements of the vector) than there will be no modification.

Lets say s = 4 and  A = (1, 2, 3, 4, 5, 6, 7, 8)then after execution the values will be A = (4, 3, 2, 1, 8, 7, 6, 5)

My teacher requires this kind of vector: int n, A[n] where n is a value given by the user. And i think this is what is causing my program to crash when i read the final values. If not, where is the problem?

#include <iomanip>

using namespace std;

int ordering(int s, int n, int A[]);

int main()
{
    int n, A[n];
    int s;
    cout << "Vlera e s: ";
    cin >> s;

    if (s <= 0)
    {
        return 1;
    }

    cout << "\nN: ";
    cin >> n;

    if (n <= 0)
    {
        return 1;
    }

    cout << "\nVector:";
    for (int i = 0; i < n; i++)
    {
        A[i] = i + 1;
        cout << " " << A[i] << " ";
    }

    if (s > n)
    {
        cout << "\nNo change\n";
        return 0;
    }
    else
    {
        ordering(s, n, A);
    }

    cout << "\nNew vector:";
    for (int i = 0; i < n; i++)
    {
        cout << " " << A[i] << " ";
    }

    return 0;
}

int ordering(int s, int n, int A[])
{
    int counter = 0;
    for (int i = 0, divider = n / s; i < divider; i++)
    {
        int decrease = 0;
        for (int j = counter, a = counter + s; j < a; j++)
        {
            A[j] = a - decrease;
            decrease++;
        }
        counter += s;
    }
    return 0;
}

Body:
This program using a compiler extension to allow variable sized arrays in the form myArray[variableSize]. Whilst not standard, it does work on some compilers.

You are using this feature here:

int n, A[n];

However, n is uninitialised at this point. This is undefined behaviour even on the compilers that support such variable sized arrays. One possible (but not the only) outcome of undefined behaviour is your program crashing.

Undefined behaviour can do anything in theory, but the realistic set of things in can do in reality is smaller. Some of the likely implications of the undefined behaviour here:

n has some huge number in it, from whatever last used that bit of memory. As a result, A is huge.

n is 0. You can't have a 0 sized array. If the compiler doesn't notice this, you could end up trashing memory.

Since n is uninitialised, the optimiser for the compiler (they usually do very some optimisations, even when on -O0) assumes that undefined behaviour cannot occur, which is violated here, leading to strange behaviour.

n is a reasonable value, just by luck, but because it is later updated it no longer matches the size of the array and you end up reading / writing memory off the end of the array, trashing memory.

There are other possibilities, but this gives an idea of the kind of things that can happen as a result of this specific instance of undefined behaviour. If you're interested to know more, using a debugger to step through the code in assembly (you only need learn a little to understand the output, it looks more scary than it need be) will show you what's actually happening.


问:
Can managed code perform computations as fast as unmamanged?
I've been interested in different chess engines lately. There are many open and closed sources project in this field. They are all (most of them anyway) written in C/C++. This is kind of an obvious thing - you have a computationally intensive task, you use C/C++ so you get both portability and speed. This seems like a no-brainier.

However, I would like to question that idea. When .NET first appeared, there were many people saying that .NET idea would not work because .NET programs were doomed to be super-slow. In reality this did not happen. Somebody did a good job with the VM, JIT, etc and we have decent performance for most tasks now. But not all. Microsoft never promised that .NET will be suitable for all task and admitted for some tasks you will still need C/C++.

Going back to the question of computationally heavy task - is there a way to write a .NET program so that it does not perform computations considerably worse that an unmanaged code using the same algorithms? I'd be happy with "constant" speed loss, but anything worse than that is going to be a problem.

What do you think? Can we be close in speed to unmanaged code for computations in managed code, or unmanaged code is the only viable answer? If we can, how? If we can't why?

Update:  a lot of good feedback here. I'm going to accept the most up-voted answer.

答:
"Can" it? Yes, of course. Even without unsafe/unverifiable code, well-optimized .NET code can outperform native code. Case in point, Dr. Jon Harrop's answer on this thread: F# performance in scientific computing

Will it? Usually, no, unless you go way out of your way to avoid allocations.


问:
Cannot install npm package in Angular project
I clone my project from GitLab and I need to install the NPM packages in my project.

When I run npm install it shows me this error:

and I go to the log file and see:

```<code>30601 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...19"},"dist":{"integri'
30601 verbose stack     at JSON.parse (<anonymous>)
30601 verbose stack     at parseJson (/usr/lib/node_modules/npm/node_modules/json-parse-better-errors/index.js:7:17)
30601 verbose stack     at /usr/lib/node_modules/npm/node_modules/node-fetch-npm/src/body.js:96:50
30601 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:97:5)
30602 verbose cwd /home/mrcoder/Projects/Angular/Ava/PFA/pfa-front-cpl
30603 verbose Linux 5.4.0-33-generic
30604 verbose argv "/usr/bin/node" "/usr/bin/npm" "install"
30605 verbose node v12.17.0
30606 verbose npm  v6.14.4
30607 error Unexpected end of JSON input while parsing near '...19"},"dist":{"integri'
30608 verbose exit [ 1, true ]
</code>```

This is my package.json:

```<code>{
  "name": "vex",
  "version": "9.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.7",
    "@angular/cdk": "~9.1.3",
    "@angular/common": "~9.0.7",
    "@angular/compiler": "~9.0.7",
    "@angular/core": "~9.0.7",
    "@angular/flex-layout": "9.0.0-beta.29",
    "@angular/forms": "~9.0.7",
    "@angular/material": "~9.1.3",
    "@angular/platform-browser": "~9.0.7",
    "@angular/platform-browser-dynamic": "~9.0.7",
    "@angular/router": "~9.0.7",
    "@iconify/icons-emojione": "~1.0.5",
    "@iconify/icons-fa-brands": "~1.0.10",
    "@iconify/icons-fa-solid": "~1.0.8",
    "@iconify/icons-ic": "~1.0.9",
    "@iconify/icons-logos": "~1.0.9",
    "@ngrx/store": "^9.1.2",
    "@ngx-loading-bar/core": "~5.0.0-alpha.1",
    "@ngx-loading-bar/router": "~5.0.0-alpha.1",
    "@ngx-translate/core": "^12.1.2",
    "@visurel/iconify-angular": "^0.0.7",
    "angular-calendar": "~0.28.5",
    "angular2-promise-buttons": "^4.0.6",
    "apexcharts": "~3.17.0",
    "color": "~3.1.2",
    "date-fns": "~2.11.0",
    "highlight.js": "~9.18.1",
    "jalali-moment": "^3.3.3",
    "luxon": "~1.22.0",
    "ng2-jalali-date-picker": "^2.3.0",
    "ngx-material-file-input": "^2.1.1",
    "ngx-quill": "~8.1.0",
    "ngx-showdown": "~5.1.0",
    "ngx-take-until-destroy": "~5.4.0",
    "ngx-toastr": "^12.0.1",
    "quill": "~1.3.7",
    "rxjs": "~6.5.4",
    "showdown": "^1.9.1",
    "simplebar": "~4.2.3",
    "tailwindcss": "~1.2.0",
    "tslib": "~1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "~9.0.0",
    "@angular-devkit/build-angular": "~0.900.7",
    "@angular/cli": "~9.0.7",
    "@angular/compiler-cli": "~9.0.7",
    "@angular/language-service": "~9.0.7",
    "@fullhuman/purgecss-loader": "^1.0.0",
    "@types/color": "~3.0.0",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/luxon": "~1.22.0",
    "@types/node": "~13.9.3",
    "@types/showdown": "~1.9.3",
    "@types/simplebar": "~5.1.1",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "postcss-loader": "~3.0.0",
    "postcss-scss": "~2.0.0",
    "protractor": "~5.4.0",
    "tailwindcss-dir": "~4.0.0",
    "ts-node": "^8.8.1",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5"
  }
}
</code>```

What's the problem? How can I solve it?

答:
Try npm cache clean --force and then reinstall using npm install.

Hope it works! :)

Body:
I clone my project from GitLab and I need to install the NPM packages in my project.

When I run npm install it shows me this error:

and I go to the log file and see:

30601 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...19"},"dist":{"integri'
30601 verbose stack     at JSON.parse (<anonymous>)
30601 verbose stack     at parseJson (/usr/lib/node_modules/npm/node_modules/json-parse-better-errors/index.js:7:17)
30601 verbose stack     at /usr/lib/node_modules/npm/node_modules/node-fetch-npm/src/body.js:96:50
30601 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:97:5)
30602 verbose cwd /home/mrcoder/Projects/Angular/Ava/PFA/pfa-front-cpl
30603 verbose Linux 5.4.0-33-generic
30604 verbose argv "/usr/bin/node" "/usr/bin/npm" "install"
30605 verbose node v12.17.0
30606 verbose npm  v6.14.4
30607 error Unexpected end of JSON input while parsing near '...19"},"dist":{"integri'
30608 verbose exit [ 1, true ]

This is my package.json:

{
  "name": "vex",
  "version": "9.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.7",
    "@angular/cdk": "~9.1.3",
    "@angular/common": "~9.0.7",
    "@angular/compiler": "~9.0.7",
    "@angular/core": "~9.0.7",
    "@angular/flex-layout": "9.0.0-beta.29",
    "@angular/forms": "~9.0.7",
    "@angular/material": "~9.1.3",
    "@angular/platform-browser": "~9.0.7",
    "@angular/platform-browser-dynamic": "~9.0.7",
    "@angular/router": "~9.0.7",
    "@iconify/icons-emojione": "~1.0.5",
    "@iconify/icons-fa-brands": "~1.0.10",
    "@iconify/icons-fa-solid": "~1.0.8",
    "@iconify/icons-ic": "~1.0.9",
    "@iconify/icons-logos": "~1.0.9",
    "@ngrx/store": "^9.1.2",
    "@ngx-loading-bar/core": "~5.0.0-alpha.1",
    "@ngx-loading-bar/router": "~5.0.0-alpha.1",
    "@ngx-translate/core": "^12.1.2",
    "@visurel/iconify-angular": "^0.0.7",
    "angular-calendar": "~0.28.5",
    "angular2-promise-buttons": "^4.0.6",
    "apexcharts": "~3.17.0",
    "color": "~3.1.2",
    "date-fns": "~2.11.0",
    "highlight.js": "~9.18.1",
    "jalali-moment": "^3.3.3",
    "luxon": "~1.22.0",
    "ng2-jalali-date-picker": "^2.3.0",
    "ngx-material-file-input": "^2.1.1",
    "ngx-quill": "~8.1.0",
    "ngx-showdown": "~5.1.0",
    "ngx-take-until-destroy": "~5.4.0",
    "ngx-toastr": "^12.0.1",
    "quill": "~1.3.7",
    "rxjs": "~6.5.4",
    "showdown": "^1.9.1",
    "simplebar": "~4.2.3",
    "tailwindcss": "~1.2.0",
    "tslib": "~1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "~9.0.0",
    "@angular-devkit/build-angular": "~0.900.7",
    "@angular/cli": "~9.0.7",
    "@angular/compiler-cli": "~9.0.7",
    "@angular/language-service": "~9.0.7",
    "@fullhuman/purgecss-loader": "^1.0.0",
    "@types/color": "~3.0.0",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/luxon": "~1.22.0",
    "@types/node": "~13.9.3",
    "@types/showdown": "~1.9.3",
    "@types/simplebar": "~5.1.1",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "postcss-loader": "~3.0.0",
    "postcss-scss": "~2.0.0",
    "protractor": "~5.4.0",
    "tailwindcss-dir": "~4.0.0",
    "ts-node": "^8.8.1",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5"
  }
}

What's the problem? How can I solve it?


问:
Setting up gradle and project structure for Kotlin Multiplatform project
I want to build a CLI tool with Kotlin Multiplatform which runs on Linux, Macos and Windows.

But I am struggling with setting up my build.gradle and my project structure. I am using IntelliJ IDEA 2020.1 and created my basic project with File -> New -> Project -> Kotlin / Native | Gradle

Currently I am looking through guides from kotlinlang.org but I am more falling then achieving something.

So far my build.gradle looks as follows:

```<code>plugins {
   id 'org.jetbrains.kotlin.multiplatform' version '1.3.72'
}
repositories {
    mavenCentral()
}
kotlin {
// For ARM, should be changed to iosArm32 or iosArm64
// For Linux, should be changed to e.g. linuxX64
// For MacOS, should be changed to e.g. macosX64
// For Windows, should be changed to e.g. mingwX64

     linuxX64("linux") {

     }
     mingwX64("mingw") {

     }
     macosX64("macos") {
         binaries {
             executable {
            // Change to specify fully qualified name of your application's entry point:
                entryPoint = 'sample.main'
            // Specify command-line arguments, if necessary:
            runTask?.args('')
        }
    }
}

sourceSets {
    commonMain {
        kotlin.srcDir('src/main')
        resources.srcDir('src/res')
        dependencies {
            implementation kotlin('stdlib-common')
            implementation "com.github.ajalt:clikt-multiplatform:2.7.0"
        }
    }
    commonTest {
        dependencies {
            implementation kotlin('test-common')
            implementation kotlin('test-annotations-common')
        }
    }

    macosX64().compilations.test.defaultSourceSet {
        dependsOn commonMain
    }
    // Note: To enable common source sets please comment out
    'kotlin.import.noCommonSourceSets' property
    // in gradle.properties file and re-import your project in IDE.
    macosMain {
    }
    macosTest {
    }
}
}

 wrapper {
    gradleVersion = "6.4.1"
    distributionType = "ALL"
}
</code>```

And my project structure is still basic:

Project structure

Formerly I only worked on Android Projects with Kotlin, and I guess I am spoiled with gradle as Android generates the most basic stuff and everything is working without doing that much.

I understand that I need to create packages like linuxMain and mingwMain, but where to I put common sourcesets? I tried to create a package called commonMain, but it won't even let me create Kotlin files in that package.

When I am finished I want to have (in the best case) one common source set and one entry point for all my targets. Is this even possible?

答: As far as I can see, you specify your commonMain source set's source locations as /src/main/. By default, it's usually set onto /src/commonMain/kotlin/. So if you will remove those srcDir settings and create a .kt file in your /src/commonMain/kotlin/ folder, everything should work fine. Also, I hope you have removed 'kotlin.import.noCommonSourceSets' property from your gradle.properties as your script recommended.

Body:
I want to build a CLI tool with Kotlin Multiplatform which runs on Linux, Macos and Windows.

But I am struggling with setting up my build.gradle and my project structure. I am using IntelliJ IDEA 2020.1 and created my basic project with File -> New -> Project -> Kotlin / Native | Gradle

Currently I am looking through guides from kotlinlang.org but I am more falling then achieving something.

So far my build.gradle looks as follows:

plugins {
   id 'org.jetbrains.kotlin.multiplatform' version '1.3.72'
}
repositories {
    mavenCentral()
}
kotlin {
// For ARM, should be changed to iosArm32 or iosArm64
// For Linux, should be changed to e.g. linuxX64
// For MacOS, should be changed to e.g. macosX64
// For Windows, should be changed to e.g. mingwX64

     linuxX64("linux") {

     }
     mingwX64("mingw") {

     }
     macosX64("macos") {
         binaries {
             executable {
            // Change to specify fully qualified name of your application's entry point:
                entryPoint = 'sample.main'
            // Specify command-line arguments, if necessary:
            runTask?.args('')
        }
    }
}

sourceSets {
    commonMain {
        kotlin.srcDir('src/main')
        resources.srcDir('src/res')
        dependencies {
            implementation kotlin('stdlib-common')
            implementation "com.github.ajalt:clikt-multiplatform:2.7.0"
        }
    }
    commonTest {
        dependencies {
            implementation kotlin('test-common')
            implementation kotlin('test-annotations-common')
        }
    }

    macosX64().compilations.test.defaultSourceSet {
        dependsOn commonMain
    }
    // Note: To enable common source sets please comment out
    'kotlin.import.noCommonSourceSets' property
    // in gradle.properties file and re-import your project in IDE.
    macosMain {
    }
    macosTest {
    }
}
}

 wrapper {
    gradleVersion = "6.4.1"
    distributionType = "ALL"
}

And my project structure is still basic:

Project structure

Formerly I only worked on Android Projects with Kotlin, and I guess I am spoiled with gradle as Android generates the most basic stuff and everything is working without doing that much.

I understand that I need to create packages like linuxMain and mingwMain, but where to I put common sourcesets? I tried to create a package called commonMain, but it won't even let me create Kotlin files in that package.

When I am finished I want to have (in the best case) one common source set and one entry point for all my targets. Is this even possible?


问:
How to use nupmy.as_strided
I am creating my own neural network library and I am now creating a convolution algorithm. I am trying to part the input to local receptive fields, and then multiply it by the respective weights, sum the multiplied receptive fields, add the biases and return the result. I am using the 'numpy.lib.stride_tricks.as_strided' function, and I'm not sure how set the strides. I would really appreciate your help. Here's the code:</p>

```<code>"""
the matrix shape is:
mini_batch_size X
numberOfFilters X
numberOfInputFeatureMaps X
sizeOfInputImage[0] X
sizeOfInputImage[1]

the kernel shape is:
mini_batch_size X
numberOfFilters X
sizeOfLocalReceptiveField[0] X
sizeOfLocalReceptiveField[1]
"""

    s1, s2, s3, s4, s5 =  matrix.strides
    imageWidth, imageHeight = matrix.shape[-2:]
    localReceptiveFieldWidth, localReceptiveFieldHeight = kernel.shape[-2:]
    matrix_shape = matrix.shape
    numberOfLocalReceptiveFields =
    (1 + (imageWidth - localReceptiveFieldWidth) // stride) *
    (1 + (imageHeight - localReceptiveFieldHeight) // stride) *
    matrix_shape[1]

    view_shape = (
        matrix_shape[0], # mini batch size
        matrix_shape[1], # number of filters
        numberOfLocalReceptiveFields,
        localReceptiveFieldWidth,
        localReceptiveFieldHeight
    )

    strides = () # don't know what to put here
    subs = numpy.lib.stride_tricks.as_strided(matrix, view_shape, strides=strides)

</code>```

答:
Hey if anyone is interested I managed to create an algorithm in this way:</p>

```<code>    @staticmethod
    def getOutputImageDims(imageWidth, imageHeight, lrfWidth, lrfHeight, stride):
        return [
            (1 + (imageWidth - lrfWidth) // stride),
            (1 + (imageHeight - lrfHeight) // stride)
        ]

    @staticmethod
    def getNumberOfLocalReceptiveFields(imageWidth, imageHeight, lrfWidth, lrfHeight, stride,
                                        numberOfInputFeatureMaps, numberOfFilters):
        return _MathHelper.getOutputImageDims(imageWidth, imageHeight, lrfWidth, lrfHeight, stride) * \
            numberOfFilters * numberOfInputFeatureMaps

    @staticmethod
    def getLocalReceptiveFields(
            matrix,
            stride,
            outputImageWidth,
            outputImageHeight,
            lrfWidth,
            lrfHeight
    ):
        s0, s1 = matrix.strides[-2:]
        matrix_dims = np.ndim(matrix)
        view_shape = matrix.shape[:2-matrix_dims] + (outputImageWidth, outputImageHeight, lrfWidth, lrfHeight)
        strides = matrix.strides[:2-matrix_dims] + (stride * s0, stride * s1, s0, s1)
        return np.lib.stride_tricks.as_strided(matrix, view_shape, strides=strides)

    @staticmethod
    def conv5D(matrix, kernel, stride=1):
        # needed variables
        imageWidth, imageHeight = matrix.shape[-2:]
        localReceptiveFieldWidth, localReceptiveFieldHeight = kernel.shape[-2:]
        x, y = _MathHelper.getOutputImageDims(imageWidth, imageHeight,
                                              localReceptiveFieldWidth, localReceptiveFieldHeight,
                                              stride)

        # wraps the kernel in a [] and then duplicates the array
        kernel = np.repeat(kernel[:, :, None, :, :], x, axis=2)
        kernel = np.repeat(kernel[:, :, :, None, :, :], y, axis=3)
        subs = _MathHelper.getLocalReceptiveFields(matrix, stride, x, y,
                                            localReceptiveFieldWidth, localReceptiveFieldHeight)

        # multipling the kernel in the local receptive fields and summing up
        arr = subs * kernel
        conv = np.sum(subs * kernel, axis=(4, 5))

        return conv
</code>```

Title: How to use nupmy.as_strided

Body:
I am creating my own neural network library and I am now creating a convolution algorithm. I am trying to part the input to local receptive fields, and then multiply it by the respective weights, sum the multiplied receptive fields, add the biases and return the result. I am using the 'numpy.lib.stride_tricks.as_strided' function, and I'm not sure how set the strides. I would really appreciate your help. Here's the code:

"""
the matrix shape is:
mini_batch_size X
numberOfFilters X
numberOfInputFeatureMaps X
sizeOfInputImage[0] X
sizeOfInputImage[1]

the kernel shape is:
mini_batch_size X
numberOfFilters X
sizeOfLocalReceptiveField[0] X
sizeOfLocalReceptiveField[1]
"""

    s1, s2, s3, s4, s5 =  matrix.strides
    imageWidth, imageHeight = matrix.shape[-2:]
    localReceptiveFieldWidth, localReceptiveFieldHeight = kernel.shape[-2:]
    matrix_shape = matrix.shape
    numberOfLocalReceptiveFields =
    (1 + (imageWidth - localReceptiveFieldWidth) // stride) *
    (1 + (imageHeight - localReceptiveFieldHeight) // stride) *
    matrix_shape[1]

    view_shape = (
        matrix_shape[0], # mini batch size
        matrix_shape[1], # number of filters
        numberOfLocalReceptiveFields,
        localReceptiveFieldWidth,
        localReceptiveFieldHeight
    )

    strides = () # don't know what to put here
    subs = numpy.lib.stride_tricks.as_strided(matrix, view_shape, strides=strides)

Body:
Hey if anyone is interested I managed to create an algorithm in this way:

    @staticmethod
    def getOutputImageDims(imageWidth, imageHeight, lrfWidth, lrfHeight, stride):
        return [
            (1 + (imageWidth - lrfWidth) // stride),
            (1 + (imageHeight - lrfHeight) // stride)
        ]

    @staticmethod
    def getNumberOfLocalReceptiveFields(imageWidth, imageHeight, lrfWidth, lrfHeight, stride,
                                        numberOfInputFeatureMaps, numberOfFilters):
        return _MathHelper.getOutputImageDims(imageWidth, imageHeight, lrfWidth, lrfHeight, stride) * \
            numberOfFilters * numberOfInputFeatureMaps

    @staticmethod
    def getLocalReceptiveFields(
            matrix,
            stride,
            outputImageWidth,
            outputImageHeight,
            lrfWidth,
            lrfHeight
    ):
        s0, s1 = matrix.strides[-2:]
        matrix_dims = np.ndim(matrix)
        view_shape = matrix.shape[:2-matrix_dims] + (outputImageWidth, outputImageHeight, lrfWidth, lrfHeight)
        strides = matrix.strides[:2-matrix_dims] + (stride * s0, stride * s1, s0, s1)
        return np.lib.stride_tricks.as_strided(matrix, view_shape, strides=strides)

    @staticmethod
    def conv5D(matrix, kernel, stride=1):
        # needed variables
        imageWidth, imageHeight = matrix.shape[-2:]
        localReceptiveFieldWidth, localReceptiveFieldHeight = kernel.shape[-2:]
        x, y = _MathHelper.getOutputImageDims(imageWidth, imageHeight,
                                              localReceptiveFieldWidth, localReceptiveFieldHeight,
                                              stride)

        # wraps the kernel in a [] and then duplicates the array
        kernel = np.repeat(kernel[:, :, None, :, :], x, axis=2)
        kernel = np.repeat(kernel[:, :, :, None, :, :], y, axis=3)
        subs = _MathHelper.getLocalReceptiveFields(matrix, stride, x, y,
                                            localReceptiveFieldWidth, localReceptiveFieldHeight)

        # multipling the kernel in the local receptive fields and summing up
        arr = subs * kernel
        conv = np.sum(subs * kernel, axis=(4, 5))

        return conv