问:
RecyclerView Scroll Listener with few items
What I am trying to achieve is a load more on RecyclerView when I scroll up. I have the implementation for scroll down and it works fine. I modified the same implementation for scroll up. It works when my RecyclerView has a lot of items. However, if my RecyclerView only has 1 or 2 items, the onScroll method for the RecyclerView never gets called. Is there any work around for this scenario? How can I load more on scroll up if there are only a few items in the RecyclerView.

Here is the code that I use for scroll up/down to load more

```<code>mAppointmentList.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        if (dy > 0) {
            Log.i("SCROLLING", "DOWN");

        } else if (dy < 0) {
            Log.i("SCROLLING", "UP");
        }
    }
);
</code>```

When I have 1 or 2 items in my RecyclerView, it never scrolls up. How can I scroll up in this scenario?

EDIT
My RecyclerView is in a fragment

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.AppointmentListFragment">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/appointment_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp" />
</FrameLayout>
</code>```

The item layout is also pretty simple.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    app:cardUseCompatPadding="true"
    android:elevation="4dp">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/status_dot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:gravity="center"
            android:text="\u2022"
            android:textColor="@android:color/black"
            android:textSize="24sp"
            app:layout_constraintBottom_toBottomOf="@+id/status"
            app:layout_constraintEnd_toStartOf="@+id/status"
            app:layout_constraintTop_toTopOf="@+id/status" />

        <LinearLayout
            android:id="@+id/date_container"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:background="@drawable/date_view"
            android:gravity="center"
            android:orientation="vertical"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintDimensionRatio="1:1"
            app:layout_constraintStart_toStartOf="@+id/title"
            app:layout_constraintTop_toTopOf="@+id/guideline2">

            <TextView
                android:id="@+id/day"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/montserrat_regular"
                android:gravity="center"
                android:text="Feb, 01"
                android:textColor="@android:color/white"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/month"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/montserrat_regular"
                android:gravity="center"
                android:text="2019"
                android:textColor="@android:color/white"
                android:textSize="16sp" />
        </LinearLayout>

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

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="8dp"
            android:fontFamily="@font/montserrat_regular"
            android:text="SQA"
            android:textColor="@android:color/black"
            android:textStyle="bold"
            app:layout_constraintBottom_toTopOf="@+id/guideline2"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"
            android:fontFamily="@font/montserrat_regular"
            android:text="UNPAID"
            android:textAllCaps="true"
            android:textColor="@android:color/black"
            android:textSize="12sp"
            app:layout_constraintBaseline_toBaselineOf="@+id/title"
            app:layout_constraintEnd_toEndOf="parent" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:fontFamily="@font/montserrat_regular"
            android:text="Imran Aftab"
            android:textColor="@android:color/black"
            app:layout_constraintStart_toEndOf="@+id/date_container"
            app:layout_constraintTop_toTopOf="@+id/date_container" />

        <TextView
            android:id="@+id/time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:fontFamily="@font/montserrat_regular"
            android:text="02:00 AM"
            android:textColor="@color/colorPrimary"
            android:textSize="12sp"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="@+id/name"
            app:layout_constraintTop_toBottomOf="@+id/name" />

        <TextView
            android:id="@+id/length"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="2dp"
            android:fontFamily="@font/montserrat_regular"
            android:text="Length: 01 hr 00 mins"
            android:textSize="12sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="@+id/date_container"
            app:layout_constraintStart_toStartOf="@+id/time"
            app:layout_constraintTop_toBottomOf="@+id/time"
            app:layout_constraintVertical_bias="1.0" />

        <TextView
            android:id="@+id/price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/round_text"
            android:fontFamily="@font/montserrat_regular"
            android:paddingStart="8dp"
            android:paddingTop="4dp"
            android:paddingEnd="8dp"
            android:paddingBottom="4dp"
            android:text="$100"
            android:textColor="@android:color/black"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="@+id/date_container"
            app:layout_constraintEnd_toEndOf="@+id/status"
            app:layout_constraintTop_toBottomOf="@+id/status"
            app:layout_constraintVertical_bias="1.0" />

        <TextView
            android:id="@+id/private_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/round_text"
            android:fontFamily="@font/montserrat_regular"
            android:paddingStart="8dp"
            android:paddingTop="4dp"
            android:paddingEnd="8dp"
            android:paddingBottom="4dp"
            android:text="Private"
            android:textColor="@android:color/black"
            android:textSize="12sp"
            android:textStyle="bold"
            android:visibility="invisible"
            app:layout_constraintBaseline_toBaselineOf="@+id/price"
            app:layout_constraintEnd_toEndOf="@+id/price"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toStartOf="@+id/price" />
    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</code>```

答:
So the way I finally achieved it was to use the fling listener. I checked whether or not the fling was going up and checked if my recyclerview could be scrolled that way. If it couldn't then I was at the top of my list and could just load more items. This works even if my list only has 1 item (other methods which rely on scroll listener don't work in this scenario).

Here is the code that I used

```<code>mAppointmentList.setOnFlingListener(new RecyclerView.OnFlingListener() {
    @Override
    public boolean onFling(int i, int i1) {
        if (!mAppointmentList.canScrollVertically(-1) && i1 < 0) {
            //Fetch items here
        }
        return false;
    }
});
</code>```

I am returning false because this is just a check if the user is trying to scroll up. This might not be the best way to do this but its what worked for me.

Body:
What I am trying to achieve is a load more on RecyclerView when I scroll up. I have the implementation for scroll down and it works fine. I modified the same implementation for scroll up. It works when my RecyclerView has a lot of items. However, if my RecyclerView only has 1 or 2 items, the onScroll method for the RecyclerView never gets called. Is there any work around for this scenario? How can I load more on scroll up if there are only a few items in the RecyclerView.

Here is the code that I use for scroll up/down to load more

mAppointmentList.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        if (dy > 0) {
            Log.i("SCROLLING", "DOWN");

        } else if (dy < 0) {
            Log.i("SCROLLING", "UP");
        }
    }
);

When I have 1 or 2 items in my RecyclerView, it never scrolls up. How can I scroll up in this scenario?

EDIT
My RecyclerView is in a fragment

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.AppointmentListFragment">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/appointment_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp" />
</FrameLayout>

The item layout is also pretty simple.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    app:cardUseCompatPadding="true"
    android:elevation="4dp">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/status_dot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:gravity="center"
            android:text="\u2022"
            android:textColor="@android:color/black"
            android:textSize="24sp"
            app:layout_constraintBottom_toBottomOf="@+id/status"
            app:layout_constraintEnd_toStartOf="@+id/status"
            app:layout_constraintTop_toTopOf="@+id/status" />

        <LinearLayout
            android:id="@+id/date_container"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:background="@drawable/date_view"
            android:gravity="center"
            android:orientation="vertical"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintDimensionRatio="1:1"
            app:layout_constraintStart_toStartOf="@+id/title"
            app:layout_constraintTop_toTopOf="@+id/guideline2">

            <TextView
                android:id="@+id/day"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/montserrat_regular"
                android:gravity="center"
                android:text="Feb, 01"
                android:textColor="@android:color/white"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/month"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/montserrat_regular"
                android:gravity="center"
                android:text="2019"
                android:textColor="@android:color/white"
                android:textSize="16sp" />
        </LinearLayout>

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

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="8dp"
            android:fontFamily="@font/montserrat_regular"
            android:text="SQA"
            android:textColor="@android:color/black"
            android:textStyle="bold"
            app:layout_constraintBottom_toTopOf="@+id/guideline2"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"
            android:fontFamily="@font/montserrat_regular"
            android:text="UNPAID"
            android:textAllCaps="true"
            android:textColor="@android:color/black"
            android:textSize="12sp"
            app:layout_constraintBaseline_toBaselineOf="@+id/title"
            app:layout_constraintEnd_toEndOf="parent" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:fontFamily="@font/montserrat_regular"
            android:text="Imran Aftab"
            android:textColor="@android:color/black"
            app:layout_constraintStart_toEndOf="@+id/date_container"
            app:layout_constraintTop_toTopOf="@+id/date_container" />

        <TextView
            android:id="@+id/time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:fontFamily="@font/montserrat_regular"
            android:text="02:00 AM"
            android:textColor="@color/colorPrimary"
            android:textSize="12sp"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="@+id/name"
            app:layout_constraintTop_toBottomOf="@+id/name" />

        <TextView
            android:id="@+id/length"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="2dp"
            android:fontFamily="@font/montserrat_regular"
            android:text="Length: 01 hr 00 mins"
            android:textSize="12sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="@+id/date_container"
            app:layout_constraintStart_toStartOf="@+id/time"
            app:layout_constraintTop_toBottomOf="@+id/time"
            app:layout_constraintVertical_bias="1.0" />

        <TextView
            android:id="@+id/price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/round_text"
            android:fontFamily="@font/montserrat_regular"
            android:paddingStart="8dp"
            android:paddingTop="4dp"
            android:paddingEnd="8dp"
            android:paddingBottom="4dp"
            android:text="$100"
            android:textColor="@android:color/black"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="@+id/date_container"
            app:layout_constraintEnd_toEndOf="@+id/status"
            app:layout_constraintTop_toBottomOf="@+id/status"
            app:layout_constraintVertical_bias="1.0" />

        <TextView
            android:id="@+id/private_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/round_text"
            android:fontFamily="@font/montserrat_regular"
            android:paddingStart="8dp"
            android:paddingTop="4dp"
            android:paddingEnd="8dp"
            android:paddingBottom="4dp"
            android:text="Private"
            android:textColor="@android:color/black"
            android:textSize="12sp"
            android:textStyle="bold"
            android:visibility="invisible"
            app:layout_constraintBaseline_toBaselineOf="@+id/price"
            app:layout_constraintEnd_toEndOf="@+id/price"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toStartOf="@+id/price" />
    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>

Body:
So the way I finally achieved it was to use the fling listener. I checked whether or not the fling was going up and checked if my recyclerview could be scrolled that way. If it couldn't then I was at the top of my list and could just load more items. This works even if my list only has 1 item (other methods which rely on scroll listener don't work in this scenario).

Here is the code that I used

mAppointmentList.setOnFlingListener(new RecyclerView.OnFlingListener() {
    @Override
    public boolean onFling(int i, int i1) {
        if (!mAppointmentList.canScrollVertically(-1) && i1 < 0) {
            //Fetch items here
        }
        return false;
    }
});

I am returning false because this is just a check if the user is trying to scroll up. This might not be the best way to do this but its what worked for me.


来源: stackexchange

问:
I have a model in which i am getting one key value nil but data comes in json response is perfect
i am getting clinic nil and i have mentioned my model and error message.

i have check and compare all key with json response key .

and my json reponse of clinic is in which i am getting error

```<code>"clinic": [
    {
        "id": 45,
        "user_id": "75",
        "clinic_id": "2",
        "created_at": null,
        "updated_at": null,
        "clinic": {
            "id": 2,
            "name": "Al Azhar Hospital",
            "status": "1",
            "created_at": "2019-04-18 07:01:07",
            "updated_at": null
        }
    }
]
</code>```

```<code>typealias SpecialityDoctor = [SpecialityWiseDoctorResponse]

struct SpecialityWiseDoctorResponse: Codable {
    let id: Int
    let firstName: String
    let lastName: String?
    let email: String
    let postMail: String?
    let mobile, age, password, gender: String
    let dateOfBirth: String?
    let profilePic, deviceID: String
    let language, insuranceCompanyName, insurancePolicyNo: String?
    let welcomeDescription: String
    let emrNumber: String?
    let startTime, endTime: String
    let status: Int
    let totalSubscriptionMonth, planStartDate, planEndDate, createdAt: String?
    let updatedAt: String?
    let speciality: [SpecialityElement]
    let clinic: [ClinicElementOfDoctor]
    let education: [EducationOfDoctor]
    let experience: [ExperienceOfDoctor]

    enum CodingKeys: String, CodingKey {
        case id
        case firstName = "first_name"
        case lastName = "last_name"
        case email
        case postMail = "post_mail"
        case mobile, age, password, gender
        case dateOfBirth = "date_of_birth"
        case profilePic = "profile_pic"
        case deviceID = "device_id"
        case language
        case insuranceCompanyName = "insurance_company_name"
        case insurancePolicyNo = "insurance_policy_no"
        case welcomeDescription = "description"
        case emrNumber = "emr_number"
        case startTime = "start_time"
        case endTime = "end_time"
        case status
        case totalSubscriptionMonth = "total_subscription_month"
        case planStartDate = "plan_start_date"
        case planEndDate = "plan_end_date"
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case speciality, clinic, education, experience
    }
}

struct ClinicElementOfDoctor: Codable {
    let id: Int
    let userID, clinicID: String
    let createdAt, updatedAt: String?
    let clinic: ClinicClinicOfDoctor

    enum CodingKeys: String, CodingKey {
        case id
        case userID = "user_id"
        case clinicID = "clinic_id"
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case clinic
    }
}

struct ClinicClinicOfDoctor: Codable {
    let id: Int
    let name, status, createdAt: String
    let updatedAt: String?

    enum CodingKeys: String, CodingKey {
        case id, name, status
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

struct EducationOfDoctor: Codable {
    let id: Int
    let userID, instituteName, course, year: String
    let createdAt, updatedAt: String?

    enum CodingKeys: String, CodingKey {
        case id
        case userID = "user_id"
        case instituteName = "institute_name"
        case course, year
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

struct ExperienceOfDoctor: Codable {
    let id: Int
    let userID, hospitalName, position, year: String
    let createdAt, updatedAt: String?

    enum CodingKeys: String, CodingKey {
        case id
        case userID = "user_id"
        case hospitalName = "hospital_name"
        case position, year
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "clinic", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"clinic\", intValue: nil) (\"clinic\").", underlyingError: nil)))))
</code>```

答:
I just tried with my own response of a web API and I think the problem lies with the datatype which is defined in the structs.

```<code>"clinic": {
            "id": 2,
            "name": "Al Azhar Hospital",
            "status": "1",
            "created_at": "2019-04-18 07:01:07",
            "updated_at": null
        }
</code>```

Whichever data you are getting in the numeric form should be saved to the Int datatype as below.

```<code>struct ClinicClinicOfDoctor: Codable {
    let id, status : Int
    let name, createdAt: String
    let updatedAt: String?

    enum CodingKeys: String, CodingKey {
        case id, name, status
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}
</code>```

Please verify the values in the response, datatypes and change all the models accordingly.
Hope this helps you in some way.

ContentLicense: CC BY-SA 4.0

Body:
i am getting clinic nil and i have mentioned my model and error message.

i have check and compare all key with json response key .

and my json reponse of clinic is in which i am getting error

"clinic": [
    {
        "id": 45,
        "user_id": "75",
        "clinic_id": "2",
        "created_at": null,
        "updated_at": null,
        "clinic": {
            "id": 2,
            "name": "Al Azhar Hospital",
            "status": "1",
            "created_at": "2019-04-18 07:01:07",
            "updated_at": null
        }
    }
]

typealias SpecialityDoctor = [SpecialityWiseDoctorResponse]

struct SpecialityWiseDoctorResponse: Codable {
    let id: Int
    let firstName: String
    let lastName: String?
    let email: String
    let postMail: String?
    let mobile, age, password, gender: String
    let dateOfBirth: String?
    let profilePic, deviceID: String
    let language, insuranceCompanyName, insurancePolicyNo: String?
    let welcomeDescription: String
    let emrNumber: String?
    let startTime, endTime: String
    let status: Int
    let totalSubscriptionMonth, planStartDate, planEndDate, createdAt: String?
    let updatedAt: String?
    let speciality: [SpecialityElement]
    let clinic: [ClinicElementOfDoctor]
    let education: [EducationOfDoctor]
    let experience: [ExperienceOfDoctor]

    enum CodingKeys: String, CodingKey {
        case id
        case firstName = "first_name"
        case lastName = "last_name"
        case email
        case postMail = "post_mail"
        case mobile, age, password, gender
        case dateOfBirth = "date_of_birth"
        case profilePic = "profile_pic"
        case deviceID = "device_id"
        case language
        case insuranceCompanyName = "insurance_company_name"
        case insurancePolicyNo = "insurance_policy_no"
        case welcomeDescription = "description"
        case emrNumber = "emr_number"
        case startTime = "start_time"
        case endTime = "end_time"
        case status
        case totalSubscriptionMonth = "total_subscription_month"
        case planStartDate = "plan_start_date"
        case planEndDate = "plan_end_date"
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case speciality, clinic, education, experience
    }
}

struct ClinicElementOfDoctor: Codable {
    let id: Int
    let userID, clinicID: String
    let createdAt, updatedAt: String?
    let clinic: ClinicClinicOfDoctor

    enum CodingKeys: String, CodingKey {
        case id
        case userID = "user_id"
        case clinicID = "clinic_id"
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case clinic
    }
}

struct ClinicClinicOfDoctor: Codable {
    let id: Int
    let name, status, createdAt: String
    let updatedAt: String?

    enum CodingKeys: String, CodingKey {
        case id, name, status
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

struct EducationOfDoctor: Codable {
    let id: Int
    let userID, instituteName, course, year: String
    let createdAt, updatedAt: String?

    enum CodingKeys: String, CodingKey {
        case id
        case userID = "user_id"
        case instituteName = "institute_name"
        case course, year
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

struct ExperienceOfDoctor: Codable {
    let id: Int
    let userID, hospitalName, position, year: String
    let createdAt, updatedAt: String?

    enum CodingKeys: String, CodingKey {
        case id
        case userID = "user_id"
        case hospitalName = "hospital_name"
        case position, year
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "clinic", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"clinic\", intValue: nil) (\"clinic\").", underlyingError: nil)))))

Body:
I just tried with my own response of a web API and I think the problem lies with the datatype which is defined in the structs.

"clinic": {
            "id": 2,
            "name": "Al Azhar Hospital",
            "status": "1",
            "created_at": "2019-04-18 07:01:07",
            "updated_at": null
        }

Whichever data you are getting in the numeric form should be saved to the Int datatype as below.

struct ClinicClinicOfDoctor: Codable {
    let id, status : Int
    let name, createdAt: String
    let updatedAt: String?

    enum CodingKeys: String, CodingKey {
        case id, name, status
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

Please verify the values in the response, datatypes and change all the models accordingly.
Hope this helps you in some way.


问:
How to load from database with condition
I am new to programming and I have my hands on a web app from a company and tried to mess around and do some changes. The app was built with PHP, MySQL, and CodeIgniter, as I was told, and it's used from the company to manage orders.

When a user wants to see the orders he clicks on the specified button and the app loads all the orders from the database, but because there are more than 10.000 orders it's slow at load. So, I want to add an option where the first load happens to get only the orders of the last 6 months and if the user wants to view older orders then I should add a button or something similar and load the rest.

<?php
 $count=1;
 $this->db->order_by("order_number", "desc");
 $completed_orders=$this->db->get_where('orders' , array(
                                        'order_status' => 'completed',
                                        'category' => 'mesoportes'
                                        ))->result_array();
 foreach ($completed_orders as $row):
?>
```

Any idea how i may do that.

答: I think the limit() function should work for you. here ist a link</p>

Body:
I am new to programming and I have my hands on a web app from a company and tried to mess around and do some changes. The app was built with PHP, MySQL, and CodeIgniter, as I was told, and it's used from the company to manage orders.

When a user wants to see the orders he clicks on the specified button and the app loads all the orders from the database, but because there are more than 10.000 orders it's slow at load. So, I want to add an option where the first load happens to get only the orders of the last 6 months and if the user wants to view older orders then I should add a button or something similar and load the rest.

<?php
 $count=1;
 $this->db->order_by("order_number", "desc");
 $completed_orders=$this->db->get_where('orders' , array(
                                        'order_status' => 'completed',
                                        'category' => 'mesoportes'
                                        ))->result_array();
 foreach ($completed_orders as $row):
?>

Any idea how i may do that.


问:
How to fix the error in left-recursion used with semantic predicates?
I would like to parse two type of expression with boolean :

- the first would be an init expression with boolean like : init : false

- and the last one would be a derive expression with boolean like : derive : !express or (express and (amount >= 100))

My idea is to put semantic predicates in a set of rules,
the goal is when I'm parsing a boolean expression beginning with the word 'init' then it has to go to only one alternative rule proposed who is boolliteral, the last alternative in boolExpression. And if it's an expression beginning with the word 'derive' then it could have access to all alternatives of boolExpression.

I know that I could make two type of boolExpression without semantic predicates like boolExpressionInit and boolExpressionDerive... But I would like to try with my idea if it's could work with a only one boolExpression with semantic predicates.

Here's my grammar

```<code>grammar TestExpression;

@header
{
package testexpressionparser;
}

@parser::members {
                    int vConstraintType;
                 }

/* SYNTAX RULES */
textInput       : initDefinition
                | derDefinition ;

initDefinition  : t=INIT {vConstraintType = $t.type;} ':' boolExpression ;

derDefinition   : t=DERIVE {vConstraintType = $t.type;} ':' boolExpression ;

boolExpression  : {vConstraintType != INIT || vConstraintType == DERIVE}? boolExpression (boolOp|relOp) boolExpression
                | {vConstraintType != INIT || vConstraintType == DERIVE}? NOT boolExpression
                | {vConstraintType != INIT || vConstraintType == DERIVE}? '(' boolExpression ')'
                | {vConstraintType != INIT || vConstraintType == DERIVE}? attributeName
                | {vConstraintType != INIT || vConstraintType == DERIVE}? numliteral
                | {vConstraintType == INIT || vConstraintType == DERIVE}? boolliteral
                ;

boolOp          : OR | AND ;
relOp           : EQ | NEQ | GT | LT | GEQT | LEQT ;
attributeName   : WORD;
numliteral      : intliteral | decliteral;
intliteral      : INT ;
decliteral      : DEC ;
boolliteral     : BOOLEAN;

/* LEXICAL RULES */
INIT            : 'init';
DERIVE          : 'derive';
BOOLEAN         : 'true' | 'false' ;
BRACKETSTART    : '(' ;
BRACKETSTOP     : ')' ;
BRACESTART      : '{' ;
BRACESTOP       : '}' ;
EQ              : '=' ;
NEQ             : '!=' ;
NOT             : '!' ;
GT              : '>' ;
LT              : '<' ;
GEQT            : '>=' ;
LEQT            : '<=' ;
OR              : 'or' ;
AND             : 'and' ;
DEC             : [0-9]* '.' [0-9]* ;
INT             : ZERO | POSITIF;
ZERO            : '0';
POSITIF         : [1-9] [0-9]* ;
WORD            : [a-zA-Z] [_0-9a-zA-Z]* ;
WS              : (SPACE | NEWLINE)+ -> skip ;
SPACE           : [ \t] ;                       /* Space or tab */
NEWLINE         : '\r'? '\n' ;                  /* Carriage return and new line */

</code>```

I except that the grammar would run successfully, but what i receive is : "error(119): TestExpression.g4::: The following sets of rules are mutually left-recursive [boolExpression]

1 error(s)
BUILD FAIL"

答:
Apparently ANTLR4's support for (direct) left-recursion does not work when a predicate appears before a left-recursive rule invocation. So you can fix the error by moving the predicate after the first boolExpression in the left-recursive alternatives.

That said, it seems like the predicates aren't really necessary in the first place - at least not in the example you've shown us (or the one before your edit as far as I could tell). Since a boolExpression with the constraint type INIT can apparently only match boolLiteral, you can just change initDefinition as follows:

```<code>initDefinition  : t=INIT ':' boolLiteral ;
</code>```

Then boolExpression will always have the constraint type DERIVE and no predicates are necessary anymore.

Generally, if you want to allow different alternatives in non-terminal x based on whether it was invoked by y or z, you should simply have multiple versions of x and then call one from y and the other from z. That's usually a lot less hassle than littering the code with actions and predicates.

Similarly it can also make sense to have a rule that matches more than it should and then detect illegal expressions in a later phase instead of trying to reject them at the syntax level. Specifically beginners often try to write grammars that only allow well-typed expressions (rejecting something like 1+true with a syntax error) and that never works out well.

Body:
I would like to parse two type of expression with boolean :

- the first would be an init expression with boolean like : init : false

- and the last one would be a derive expression with boolean like : derive : !express or (express and (amount >= 100))

My idea is to put semantic predicates in a set of rules,
the goal is when I'm parsing a boolean expression beginning with the word 'init' then it has to go to only one alternative rule proposed who is boolliteral, the last alternative in boolExpression. And if it's an expression beginning with the word 'derive' then it could have access to all alternatives of boolExpression.

I know that I could make two type of boolExpression without semantic predicates like boolExpressionInit and boolExpressionDerive... But I would like to try with my idea if it's could work with a only one boolExpression with semantic predicates.

Here's my grammar

grammar TestExpression;

@header
{
package testexpressionparser;
}

@parser::members {
                    int vConstraintType;
                 }

/* SYNTAX RULES */
textInput       : initDefinition
                | derDefinition ;

initDefinition  : t=INIT {vConstraintType = $t.type;} ':' boolExpression ;

derDefinition   : t=DERIVE {vConstraintType = $t.type;} ':' boolExpression ;

boolExpression  : {vConstraintType != INIT || vConstraintType == DERIVE}? boolExpression (boolOp|relOp) boolExpression
                | {vConstraintType != INIT || vConstraintType == DERIVE}? NOT boolExpression
                | {vConstraintType != INIT || vConstraintType == DERIVE}? '(' boolExpression ')'
                | {vConstraintType != INIT || vConstraintType == DERIVE}? attributeName
                | {vConstraintType != INIT || vConstraintType == DERIVE}? numliteral
                | {vConstraintType == INIT || vConstraintType == DERIVE}? boolliteral
                ;

boolOp          : OR | AND ;
relOp           : EQ | NEQ | GT | LT | GEQT | LEQT ;
attributeName   : WORD;
numliteral      : intliteral | decliteral;
intliteral      : INT ;
decliteral      : DEC ;
boolliteral     : BOOLEAN;

/* LEXICAL RULES */
INIT            : 'init';
DERIVE          : 'derive';
BOOLEAN         : 'true' | 'false' ;
BRACKETSTART    : '(' ;
BRACKETSTOP     : ')' ;
BRACESTART      : '{' ;
BRACESTOP       : '}' ;
EQ              : '=' ;
NEQ             : '!=' ;
NOT             : '!' ;
GT              : '>' ;
LT              : '<' ;
GEQT            : '>=' ;
LEQT            : '<=' ;
OR              : 'or' ;
AND             : 'and' ;
DEC             : [0-9]* '.' [0-9]* ;
INT             : ZERO | POSITIF;
ZERO            : '0';
POSITIF         : [1-9] [0-9]* ;
WORD            : [a-zA-Z] [_0-9a-zA-Z]* ;
WS              : (SPACE | NEWLINE)+ -> skip ;
SPACE           : [ \t] ;                       /* Space or tab */
NEWLINE         : '\r'? '\n' ;                  /* Carriage return and new line */

I except that the grammar would run successfully, but what i receive is : "error(119): TestExpression.g4::: The following sets of rules are mutually left-recursive [boolExpression]

1 error(s)
BUILD FAIL"

Body:
Apparently ANTLR4's support for (direct) left-recursion does not work when a predicate appears before a left-recursive rule invocation. So you can fix the error by moving the predicate after the first boolExpression in the left-recursive alternatives.

That said, it seems like the predicates aren't really necessary in the first place - at least not in the example you've shown us (or the one before your edit as far as I could tell). Since a boolExpression with the constraint type INIT can apparently only match boolLiteral, you can just change initDefinition as follows:

initDefinition  : t=INIT ':' boolLiteral ;

Then boolExpression will always have the constraint type DERIVE and no predicates are necessary anymore.

Generally, if you want to allow different alternatives in non-terminal x based on whether it was invoked by y or z, you should simply have multiple versions of x and then call one from y and the other from z. That's usually a lot less hassle than littering the code with actions and predicates.

Similarly it can also make sense to have a rule that matches more than it should and then detect illegal expressions in a later phase instead of trying to reject them at the syntax level. Specifically beginners often try to write grammars that only allow well-typed expressions (rejecting something like 1+true with a syntax error) and that never works out well.


问:
What does O(log n) mean exactly?
I am learning about Big O Notation running times and amortized times.  I understand the notion of O(n) linear time, meaning that the size of the input affects the growth of the algorithm proportionally...and the same goes for, for example, quadratic time O(n2) etc..even algorithms, such as permutation generators, with O(n!) times, that grow by factorials.

For example, the following function is O(n) because the algorithm grows in proportion to its input n:

```<code>f(int n) {
  int i;
  for (i = 0; i < n; ++i)
    printf("%d", i);
}
</code>```

Similarly, if there was a nested loop, the time would be O(n2).

But what exactly is O(log n)?  For example, what does it mean to say that the height of a complete binary tree is O(log n)?

I do know (maybe not in great detail) what Logarithm is, in the sense that:  log10 100 = 2, but I cannot understand how to identify a function with a logarithmic time.

答:
O(logn) is one of the polynomial time complexity to measure the runtime performance of any code.

I hope you have already heard of Binary search algorithm.

Let's assume you have to find an element in the array of size N.

Basically, the code execution is like
N
N/2
N/4
N/8....etc

If you sum all the work done at each level you will end up with n(1+1/2+1/4....) and that is equal to O(logn)

Title: What does O(log n) mean exactly?

Body:
I am learning about Big O Notation running times and amortized times.  I understand the notion of O(n) linear time, meaning that the size of the input affects the growth of the algorithm proportionally...and the same goes for, for example, quadratic time O(n2) etc..even algorithms, such as permutation generators, with O(n!) times, that grow by factorials.

For example, the following function is O(n) because the algorithm grows in proportion to its input n:

f(int n) {
  int i;
  for (i = 0; i < n; ++i)
    printf("%d", i);
}

Similarly, if there was a nested loop, the time would be O(n2).

But what exactly is O(log n)?  For example, what does it mean to say that the height of a complete binary tree is O(log n)?

I do know (maybe not in great detail) what Logarithm is, in the sense that:  log10 100 = 2, but I cannot understand how to identify a function with a logarithmic time.


问:
Are non-generic collections in .NET obsolete?
Put differently:

Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility?

As far as I understand, generic collections not only are type-safe, but their performance is better.

Here's a comprehensive article on the topic: An Extensive Examination of Data Structures Using C# 2.0.

答:
Yes, as far as I understand they are only there for compatibility with existing products. You should always use the type safe version (i.e. use System.Collections.Generic over System.Collections).

http://msdn.microsoft.com/en-us/library/ms379564.aspx

OwnerDisplayName: guillermooo

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: guillermooo

OwnerDisplayName: Mark Ingram

ContentLicense: CC BY-SA 2.5


问:
Disk space required by pg_basebackup
I need to setup the PostgreSQL slave and i am using pg_basebackup to get the master data. However, is there any way to calculate the space required on slave before running pg_basebackup.

答: pg_basebackup takes a file-level backup of the running database, so you can just see how much space is being used by the database currently.  If you're on linux, you can use du -s on the data directory.  The function pg_database_size('dbname') will also get you close, if you only have one database.</p>

Title: Disk space required by pg_basebackup


问:
Attach and or mount unmanaged page blob snapshot to another Azure VM using powershell
We are using unmanaged disks and want to be able to locate a blob given a Live VM name and a disk name, create a snapshot of the disk and mount that disk in another (backup) VM and gain access to its file system.

Live VM may be Linux or Windows
Backup VM will typically be Linux but possibly Windows

So far, I am able to locate the live VM, and the page blob I want to snapshot and create the snapshot.

```<code>$key = (Get-AzStorageAccountKey -Name $storageAccount -ResourceGroupName $vm.ResourceGroupName | select -first 1).Value
$context = New-AzStorageContext -StorageAccountName $storageAccount  -StorageAccountKey $key
$blob = Get-AzStorageBlob -Context $context -Container $containerName -Blob $blobName
$snapshot = $blob.ICloudBlob.CreateSnapshot()
</code>```

I now want to mount the snapshot identified by $snapshot on the backup VM. Is this possible?

I don't mind if it requires additional steps (such as copying the snapshot to another blob) but would rather keep the steps to a minimum.

答: It isn't possible. Copying the snapshot to a blob, and then attaching the blob is the way to do it.</p>

Body:
We are using unmanaged disks and want to be able to locate a blob given a Live VM name and a disk name, create a snapshot of the disk and mount that disk in another (backup) VM and gain access to its file system.

Live VM may be Linux or Windows
Backup VM will typically be Linux but possibly Windows

So far, I am able to locate the live VM, and the page blob I want to snapshot and create the snapshot.

$key = (Get-AzStorageAccountKey -Name $storageAccount -ResourceGroupName $vm.ResourceGroupName | select -first 1).Value
$context = New-AzStorageContext -StorageAccountName $storageAccount  -StorageAccountKey $key
$blob = Get-AzStorageBlob -Context $context -Container $containerName -Blob $blobName
$snapshot = $blob.ICloudBlob.CreateSnapshot()

I now want to mount the snapshot identified by $snapshot on the backup VM. Is this possible?

I don't mind if it requires additional steps (such as copying the snapshot to another blob) but would rather keep the steps to a minimum.


问:
How to check whether an object key exists or not in JavaScript?
I am getting an object from backend and that object has several keys and values. According to the database data sometimes some of the keys won't be available. So I have used ternary operator for it but still, it is not working.

```<code> `
  <tr>
     <td>
         ${(df[temp].image.status)?df[temp].image.status:'Not Assigned'}
     </td>
  </tr>
  `
</code>```

Expected result:
Whether an "image" key is there or not there shouldn't be any error.
Either it should be some status or 'Not Assigned';

Current result:
TypeError: df[temp].image is undefined

Anyone any idea why this is happening?

答:
You are checking on already undefined value. First you need to verify that image exists and then you can access its fields.

```<code><tr>
    <td>
        ${(df[temp].image && df[temp].image.status) ? (df[temp].image.status) : 'Not Assigned'}
    </td>
</tr>
</code>```

Body:
I am getting an object from backend and that object has several keys and values. According to the database data sometimes some of the keys won't be available. So I have used ternary operator for it but still, it is not working.

 `

         ${(df[temp].image.status)?df[temp].image.status:'Not Assigned'}

  `

Expected result:
Whether an "image" key is there or not there shouldn't be any error.
Either it should be some status or 'Not Assigned';

Current result:
TypeError: df[temp].image is undefined

Anyone any idea why this is happening?

Body:
You are checking on already undefined value. First you need to verify that image exists and then you can access its fields.

<tr>
    <td>
        ${(df[temp].image && df[temp].image.status) ? (df[temp].image.status) : 'Not Assigned'}
    </td>
</tr>


问:
NHibernate: Returning extra properties from stored procedure not in model
Is there a way when executing a stored procedure with NHibernate to return an extra field that is not in the original model?

What I'm doing is creating a sproc to return search results of a Resource. It returns all of the normal fields of my Resource class, but also an extra field called Rank. Is there a way to map that on to the current Resource class (or even create a class that inherits from Resource and just adds that one property)?

The execution of my sproc is:

```<code><sql-query name="GetRelatedResources">
    <return alias="item" class="ResourceRanked">
        <return-property column="Rank" name="Rank" />
        <return-property column="ResourceId" name="Id" />
        <return-property column="Name" name="Name" />
        <return-property column="Description" name="Description" />
        <return-property column="Filename" name="Filename" />
        <return-property column="Filetype" name="Filetype" />
        <return-property column="IsPublic" name="IsPublic" />
        <return-property column="IsFeatured" name="IsFeatured" />
        <return-property column="VideoEmbedCode" name="VideoEmbedCode" />
        <return-property column="VideoId" name="VideoId" />
        <return-property column="VideoPlayerId" name="VideoPlayerId" />
        <return-property column="VideoPlayerKey" name="VideoPlayerKey" />
        <return-property column="VideoHeight" name="VideoHeight" />
        <return-property column="VideoWidth" name="VideoWidth" />
        <return-property column="IsDeleted" name="IsDeleted" />
        <return-property column="CreatedOn" name="CreatedOn" />
        <return-property column="ModifiedOn" name="ModifiedOn" />
        <return-property column="CreatedBy" name="CreatedBy" />
        <return-property column="ModifiedBy" name="ModifiedBy" />
        <return-property column="CreatedByName" name="CreatedByName" />
        <return-property column="ModifiedByName" name="ModifiedByName" />
    </return>
    exec dbo.gbi_sp_GetRelatedResources :pageSize, :pageIndex, :resourceId
</sql-query>
</code>```

And my class:

```<code>public class Resource : DomainEntity
{
    [Required(ErrorMessage = "Please enter a name"), StringLength(100, ErrorMessage = "Name length can not exceed 100 characters")]
    public virtual string Name { get; set; }

    [StringLength(200, ErrorMessage = "Description length can not exceed 200 characters")]
    public virtual string Description { get; set; }

    public virtual string Filename { get; set; }
    public virtual string Filetype { get; set; }

    public virtual bool IsPublic { get; set; }
    public virtual bool IsFeatured { get; set; }

    [StringLength(500, ErrorMessage = "Embed Code length can not exceed 500 characters")]
    public virtual string VideoEmbedCode { get; set; }
    public virtual long? VideoId { get; set; }
    public virtual long? VideoPlayerId { get; set; }
    [StringLength(100, ErrorMessage = "Player Key length can not exceed 100 characters")]
    public virtual string VideoPlayerKey { get; set; }
    public virtual int? VideoHeight { get; set; }
    public virtual int? VideoWidth { get; set; }

    //public virtual int Rank { get; set; }

    public virtual string Format {
        get
        {
            if (ResourceFileType == ResourceFileType.EmbeddedVideo || ResourceFileType == ResourceFileType.VideoPlayer)
                return "Video";

            switch (Filetype)
            {
                case "pdf":
                    return "Adobe Acrobat";
                case "docx":
                case "doc":
                    return "Microsoft Word";
                case "ppt":
                case "pptx":
                    return "Microsoft PowerPoint";
                case "xls":
                case "xlsx":
                    return "Microsoft Excel";
                default:
                    return Filetype.ToUpper();
            }
        }
    }

    public virtual ResourceFileType ResourceFileType
    {
        get
        {
            if (VideoId.HasValue)
                return ResourceFileType.VideoPlayer;
            if (!VideoEmbedCode.IsNullOrEmpty() || VideoId.HasValue)
                return ResourceFileType.EmbeddedVideo;
            return ResourceFileType.Document;
        }
    }

    public virtual IEnumerable<Market> Markets { get; set; }
    public virtual IEnumerable<Workstream> Workstreams { get; set; }
    public virtual IEnumerable<Tag> Tags { get; set; }
    public virtual IEnumerable<Topic> Topics { get; set; }
    public virtual IEnumerable<ResourceType> Types { get; set; }

    public override string ToString()
    {
        return Id + " - " + Name;
    }
}
</code>```

Ideally I'd like to just make a class like this to extend Resource

```<code>public class ResourceRanked : Resource
{
    public virtual int Rank { get; set; }
}
</code>```

But I can't get that to work unless I duplicate the xml mapping of the Resource class. I've looked at subclasses for nhibernate, but they don't seem to fit what I'm trying to do.

答: I couldn't find any suitable solution that worked for me, so I unfortunately just had to map another class specifically for the return result of the stored proc.</p>

Body:
Is there a way when executing a stored procedure with NHibernate to return an extra field that is not in the original model?

What I'm doing is creating a sproc to return search results of a Resource. It returns all of the normal fields of my Resource class, but also an extra field called Rank. Is there a way to map that on to the current Resource class (or even create a class that inherits from Resource and just adds that one property)?

The execution of my sproc is:

<sql-query name="GetRelatedResources">
    <return alias="item" class="ResourceRanked">
        <return-property column="Rank" name="Rank" />
        <return-property column="ResourceId" name="Id" />
        <return-property column="Name" name="Name" />
        <return-property column="Description" name="Description" />
        <return-property column="Filename" name="Filename" />
        <return-property column="Filetype" name="Filetype" />
        <return-property column="IsPublic" name="IsPublic" />
        <return-property column="IsFeatured" name="IsFeatured" />
        <return-property column="VideoEmbedCode" name="VideoEmbedCode" />
        <return-property column="VideoId" name="VideoId" />
        <return-property column="VideoPlayerId" name="VideoPlayerId" />
        <return-property column="VideoPlayerKey" name="VideoPlayerKey" />
        <return-property column="VideoHeight" name="VideoHeight" />
        <return-property column="VideoWidth" name="VideoWidth" />
        <return-property column="IsDeleted" name="IsDeleted" />
        <return-property column="CreatedOn" name="CreatedOn" />
        <return-property column="ModifiedOn" name="ModifiedOn" />
        <return-property column="CreatedBy" name="CreatedBy" />
        <return-property column="ModifiedBy" name="ModifiedBy" />
        <return-property column="CreatedByName" name="CreatedByName" />
        <return-property column="ModifiedByName" name="ModifiedByName" />
    </return>
    exec dbo.gbi_sp_GetRelatedResources :pageSize, :pageIndex, :resourceId
</sql-query>

And my class:

public class Resource : DomainEntity
{
    [Required(ErrorMessage = "Please enter a name"), StringLength(100, ErrorMessage = "Name length can not exceed 100 characters")]
    public virtual string Name { get; set; }

    [StringLength(200, ErrorMessage = "Description length can not exceed 200 characters")]
    public virtual string Description { get; set; }

    public virtual string Filename { get; set; }
    public virtual string Filetype { get; set; }

    public virtual bool IsPublic { get; set; }
    public virtual bool IsFeatured { get; set; }

    [StringLength(500, ErrorMessage = "Embed Code length can not exceed 500 characters")]
    public virtual string VideoEmbedCode { get; set; }
    public virtual long? VideoId { get; set; }
    public virtual long? VideoPlayerId { get; set; }
    [StringLength(100, ErrorMessage = "Player Key length can not exceed 100 characters")]
    public virtual string VideoPlayerKey { get; set; }
    public virtual int? VideoHeight { get; set; }
    public virtual int? VideoWidth { get; set; }

    //public virtual int Rank { get; set; }

    public virtual string Format {
        get
        {
            if (ResourceFileType == ResourceFileType.EmbeddedVideo || ResourceFileType == ResourceFileType.VideoPlayer)
                return "Video";

            switch (Filetype)
            {
                case "pdf":
                    return "Adobe Acrobat";
                case "docx":
                case "doc":
                    return "Microsoft Word";
                case "ppt":
                case "pptx":
                    return "Microsoft PowerPoint";
                case "xls":
                case "xlsx":
                    return "Microsoft Excel";
                default:
                    return Filetype.ToUpper();
            }
        }
    }

    public virtual ResourceFileType ResourceFileType
    {
        get
        {
            if (VideoId.HasValue)
                return ResourceFileType.VideoPlayer;
            if (!VideoEmbedCode.IsNullOrEmpty() || VideoId.HasValue)
                return ResourceFileType.EmbeddedVideo;
            return ResourceFileType.Document;
        }
    }

    public virtual IEnumerable<Market> Markets { get; set; }
    public virtual IEnumerable<Workstream> Workstreams { get; set; }
    public virtual IEnumerable<Tag> Tags { get; set; }
    public virtual IEnumerable<Topic> Topics { get; set; }
    public virtual IEnumerable<ResourceType> Types { get; set; }

    public override string ToString()
    {
        return Id + " - " + Name;
    }
}

Ideally I'd like to just make a class like this to extend Resource

public class ResourceRanked : Resource
{
    public virtual int Rank { get; set; }
}

But I can't get that to work unless I duplicate the xml mapping of the Resource class. I've looked at subclasses for nhibernate, but they don't seem to fit what I'm trying to do.


问:
How to add parameters to UIViewController extension?
I've successfully created an extension on UIViewController that allows me to call a function that triggers a UIView to animate down. However instead of just a plain UIView, I want to improve on the extension so that it is it takes two parameters (background color, and label text) that are a subview on the UIView 'popupAlert?

```<code>extension UIViewController {

func showAlert() {
    let popupAlert = UIView(frame: CGRect(x: 0, y: -60, width: view.frame.width, height: 60))
    popupAlert.backgroundColor = UIColor.brandSuccess()
    let window = (UIApplication.shared.delegate as! AppDelegate).window!

    window.addSubview(popupAlert)

    UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseIn, animations: {
        popupAlert.transform = .init(translationX: 0, y: 60)
    }) { (_) in
        UIView.animate(withDuration: 0.6, delay: 4, options: .curveEaseIn, animations: {
            popupAlert.transform = .init(translationX: 0, y: -60)

        }, completion: { (_) in
            popupAlert.removeFromSuperview()
        })
    }
}
}
</code>```

答:
```<code>extension UIViewController {

    func showAlert(bgColor: UIColor, lblText: String) {
        let popupAlert = UIView(frame: CGRect(x: 0, y: -60, width: view.frame.width, height: 60))
        let popupLbl = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 60))
        popupAlert.backgroundColor = bgColor
        popupLbl.text = lblText
        popupLbl.textColor = .green
        popupLbl.textAlignment = .center
        let window = (UIApplication.shared.delegate as! AppDelegate).window!

        popupAlert.addSubview(popupLbl)
        window.addSubview(popupAlert)

        UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseIn, animations: {
            popupAlert.transform = .init(translationX: 0, y: 60)
        }) { (_) in
            UIView.animate(withDuration: 0.6, delay: 4, options: .curveEaseIn, animations: {
                popupAlert.transform = .init(translationX: 0, y: -60)

            }, completion: { (_) in
                popupAlert.removeFromSuperview()
            })
        }
    }
}
</code>```

call

```<code>    showAlert(bgColor: .red, lblText: "testtttt")
</code>```

Body:
I've successfully created an extension on UIViewController that allows me to call a function that triggers a UIView to animate down. However instead of just a plain UIView, I want to improve on the extension so that it is it takes two parameters (background color, and label text) that are a subview on the UIView 'popupAlert?

extension UIViewController {

func showAlert() {
    let popupAlert = UIView(frame: CGRect(x: 0, y: -60, width: view.frame.width, height: 60))
    popupAlert.backgroundColor = UIColor.brandSuccess()
    let window = (UIApplication.shared.delegate as! AppDelegate).window!

    window.addSubview(popupAlert)

    UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseIn, animations: {
        popupAlert.transform = .init(translationX: 0, y: 60)
    }) { (_) in
        UIView.animate(withDuration: 0.6, delay: 4, options: .curveEaseIn, animations: {
            popupAlert.transform = .init(translationX: 0, y: -60)

        }, completion: { (_) in
            popupAlert.removeFromSuperview()
        })
    }
}
}

Body:
extension UIViewController {

    func showAlert(bgColor: UIColor, lblText: String) {
        let popupAlert = UIView(frame: CGRect(x: 0, y: -60, width: view.frame.width, height: 60))
        let popupLbl = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 60))
        popupAlert.backgroundColor = bgColor
        popupLbl.text = lblText
        popupLbl.textColor = .green
        popupLbl.textAlignment = .center
        let window = (UIApplication.shared.delegate as! AppDelegate).window!

        popupAlert.addSubview(popupLbl)
        window.addSubview(popupAlert)

        UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseIn, animations: {
            popupAlert.transform = .init(translationX: 0, y: 60)
        }) { (_) in
            UIView.animate(withDuration: 0.6, delay: 4, options: .curveEaseIn, animations: {
                popupAlert.transform = .init(translationX: 0, y: -60)

            }, completion: { (_) in
                popupAlert.removeFromSuperview()
            })
        }
    }
}

call

    showAlert(bgColor: .red, lblText: "testtttt")


问:
Message: Undefined index: password

Severity: Notice

Message: Undefined index: password

Filename: models/userr.php

Line Number: 10

Backtrace:

File: C:\xampp\htdocs\cooladmin\application\models\userr.php Line: 10
  Function: _error_handler

File: C:\xampp\htdocs\cooladmin\application\controllers\auth.php Line:
  17 Function: login

File: C:\xampp\htdocs\cooladmin\index.php Line: 315 Function:
  require_once

class userr extends CI_Model {

```<code>public function login($post)
{
    $this->db->select('*');
    $this->db->from('user');
    $this->db->where('username', $post['username']);
    $this->db->where('password', $post['password']);
    $query = $this->db->get();
    return $query;
}
</code>```

class auth extends CI_Controller
{

```<code>public function login()
{
    $this->load->view('login');
}

public function process()
{
    $post = $this->input->post(null, TRUE);
    if(isset($post['login'])) {
        $this->load->model('userr');
        $query = $this->userr->login($post);
        if($query->num_rows() > 0) {
            echo "login berhasil !";
        } else {
            echo "login gagal !";
        }
    }
}
</code>```

}

答:
use this:

```<code>$this->db->where('password', isset($post['password']) ? $post['password'] : '');
</code>```

It just means the password has not been posted from the form

Title: Message: Undefined index: password

Body:
Severity: Notice

Message: Undefined index: password

Filename: models/userr.php

Line Number: 10

Backtrace:

File: C:\xampp\htdocs\cooladmin\application\models\userr.php Line: 10
  Function: _error_handler

File: C:\xampp\htdocs\cooladmin\application\controllers\auth.php Line:
  17 Function: login

File: C:\xampp\htdocs\cooladmin\index.php Line: 315 Function:
  require_once

class userr extends CI_Model {

public function login($post)
{
    $this->db->select('*');
    $this->db->from('user');
    $this->db->where('username', $post['username']);
    $this->db->where('password', $post['password']);
    $query = $this->db->get();
    return $query;
}

class auth extends CI_Controller
{

public function login()
{
    $this->load->view('login');
}

public function process()
{
    $post = $this->input->post(null, TRUE);
    if(isset($post['login'])) {
        $this->load->model('userr');
        $query = $this->userr->login($post);
        if($query->num_rows() > 0) {
            echo "login berhasil !";
        } else {
            echo "login gagal !";
        }
    }
}

}

Body:
use this:

$this->db->where('password', isset($post['password']) ? $post['password'] : '');

It just means the password has not been posted from the form


问:
Check object permission for user with global permission
How i can check permission to object for user with global permission ?</p>

```<code>joe = User.objects.get(username="joe")
assign_perm('parse.show_company', joe) # assign global permission
company = Company.objects.get(id=id)

joe.has_perm('parse.show_company', company ) # check permission for object, return False
</code>```

答:
This is an open issue with permission checker in django guardian app. You can find it on github.

https://github.com/django-guardian/django-guardian/issues/294

You can also check global permission for the object with user like below:

```<code>from guardian.shortcuts import get_objects_for_user
if company in get_objects_for_user(company, 'parse.show_company'):
    # do your stuff
</code>```

I hope this will help you.

Body:
How i can check permission to object for user with global permission ?

joe = User.objects.get(username="joe")
assign_perm('parse.show_company', joe) # assign global permission
company = Company.objects.get(id=id)

joe.has_perm('parse.show_company', company ) # check permission for object, return False

Body:
This is an open issue with permission checker in django guardian app. You can find it on github.

https://github.com/django-guardian/django-guardian/issues/294

You can also check global permission for the object with user like below:

from guardian.shortcuts import get_objects_for_user
if company in get_objects_for_user(company, 'parse.show_company'):
    # do your stuff

I hope this will help you.


问:
textToBePresentInElement() is not working with exact text
I'm trying to locate and wait for an element with the text "Total " with space after "Total". The locator I've used is:

```<code>//td[./text()='Total ']
</code>```

The wait I've implemented for it is:

```<code>wait.until(ExpectedConditions.textToBePresentInElement(element,"Total "));
</code>```

I'm getting TimeOutException. If I remove the space after the text "Total". it's working. The wait implementation now is:

```<code>wait.until(ExpectedConditions.textToBePresentInElement(element, "Total"));
</code>```

Why the condition textToBePresentInElement is not working with the exact text?

答:
You can see the answer in the source code

```<code>public static ExpectedCondition<Boolean> textToBePresentInElement(final WebElement element, final String text) {
    //...
    String elementText = element.getText();
    return elementText.contains(text);
    //...
}
</code>```

The method get the text using element.getText();, which means the text returned as rendered by the browser, i.e. without trailing space

The Get Element Text command intends to return an element’s text “as
  rendered”...

When you use the text "Total " you are basically check in the expected condition if

```<code>"Total".contains("Total ");
</code>```

Which is false, but without the trailing space it works.

Body:
I'm trying to locate and wait for an element with the text "Total " with space after "Total". The locator I've used is:

//td[./text()='Total ']

The wait I've implemented for it is:

wait.until(ExpectedConditions.textToBePresentInElement(element,"Total "));

I'm getting TimeOutException. If I remove the space after the text "Total". it's working. The wait implementation now is:

wait.until(ExpectedConditions.textToBePresentInElement(element, "Total"));

Why the condition textToBePresentInElement is not working with the exact text?

Body:
You can see the answer in the source code

public static ExpectedCondition<Boolean> textToBePresentInElement(final WebElement element, final String text) {
    //...
    String elementText = element.getText();
    return elementText.contains(text);
    //...
}

The method get the text using element.getText();, which means the text returned as rendered by the browser, i.e. without trailing space

The Get Element Text command intends to return an element’s text “as
  rendered”...

When you use the text "Total " you are basically check in the expected condition if

"Total".contains("Total ");

Which is false, but without the trailing space it works.


问:
Why my programm prints wrong decimal number
I have given the 8 hex digits (as example):

```<code>long a0 = 00
long a1 = 2E
long a2 = E8
long a3 = A0
long a4 = 58
long a5 = 0F
long a6 = 37
long a7 = FF
</code>```

and i want to print this in decimal.

So I have tried:

```<code>long long Decimal = (pow(16, 14) * a) + (pow(16, 12) * a1) + (pow(16, 10) * a2) + (pow(16, 8) * a3) + (pow(16, 6) * a4) + (pow(16, 4) * a5) + (pow(16, 2) * a6) + (pow(16, 0) * a7);
</code>```

but i get a decimal number which isnt the right decimal. As for the example the decimal value is 13203624298493951 but i get 13203624298493952.

Thanks guys for helping

答:
pow uses floating-point arithmetic and returns a double result, which causes the rest of the arithmetic in your statement to use double. The double floating-point arithmetic in your C implementation does not have sufficient precision to represent the numbers you are working with exactly.

Instead of using (pow(16, 14) * a0), use (long long) a0 << 4*14. This uses integer arithmetic, and the results will be exact as long as the values do not overflow the long long type.

Note that if the high bit of a0 (considering it as an eight-bit number) might be set, meaning that the final result is intended to be a negative number, then (long long) a0 << 4*14 will overflow a 64-bit long long type. You will need to write different code to handle the negative-number cases. If you want all results to be unsigned, not negative, use unsigned long long instead of long long.

Body:
I have given the 8 hex digits (as example):

long a0 = 00
long a1 = 2E
long a2 = E8
long a3 = A0
long a4 = 58
long a5 = 0F
long a6 = 37
long a7 = FF

and i want to print this in decimal.

So I have tried:

long long Decimal = (pow(16, 14) * a) + (pow(16, 12) * a1) + (pow(16, 10) * a2) + (pow(16, 8) * a3) + (pow(16, 6) * a4) + (pow(16, 4) * a5) + (pow(16, 2) * a6) + (pow(16, 0) * a7);

but i get a decimal number which isnt the right decimal. As for the example the decimal value is 13203624298493951 but i get 13203624298493952.

Thanks guys for helping


问:
GWT CellTable with checkbox selection and on row click event
How to call a method when some row is clicked using the checkbox selection model?

I'm setting the checkbox selection model like this:

```<code>table.setSelectionModel(selectionModel,
      DefaultSelectionEventManager.<T> createCheckboxManager(0));
</code>```

答:
Create a function that you call,</p>

```<code>table.setSelectionModel(selectionModel, ClassName.myMethod(0));

static <T> DefaultSelectionEventManager<T> myMethod(int column) {
   //call whatever functions you want
   return DefaultSelectionEventManager.<T> createCheckboxManager(column);
}
</code>```

Body:
How to call a method when some row is clicked using the checkbox selection model?

I'm setting the checkbox selection model like this:

table.setSelectionModel(selectionModel,
      DefaultSelectionEventManager.<T> createCheckboxManager(0));

Body:
Create a function that you call,

table.setSelectionModel(selectionModel, ClassName.myMethod(0));

static <T> DefaultSelectionEventManager<T> myMethod(int column) {
   //call whatever functions you want
   return DefaultSelectionEventManager.<T> createCheckboxManager(column);
}


问:
About remove elements inside iframe
How to remove or hide contents or elements of website inside
 iframe in jquery?

答:
Remove all contents in iframe

```<code>   $("iframe").children().remove();
</code>```

Hide all contents in iframe

```<code>   $("iframe").children().hide();
</code>```

Title: About remove elements inside iframe

Body:
Remove all contents in iframe

   $("iframe").children().remove();

Hide all contents in iframe

   $("iframe").children().hide();


问:
Finding not equal adjacent indexes in vector
I have this vector of ints:

```<code>std::vector<int> v = {1, 1, 2, 2, 2, 3};
</code>```

and I want to find indexes, where the adjacent elements aren't equal:

```<code>1
4
5
</code>```

My solution is (which isn't working):

```<code>std::vector<int> v = {1, 1, 2, 2, 2, 3};

auto i1 = std::begin(v);

while(1)
{
    i1 = std::adjacent_find(i1, std::end(v), std::not_equal_to<int>());
    std::cout << std::distance(std::begin(v), i1) << '\n';

    if (i1++ == std::end(v))
        break;
}
</code>```

This prints:

```<code>1
4
6
</code>```

The last elements points to index 6, but I want it to point 5 (value 3). Any help appreciated!

答: Assuming it will always treat the last index in this way, you could just subtract 1 from the last value in the otherwise correct result.</p>

Body:
I have this vector of ints:

std::vector<int> v = {1, 1, 2, 2, 2, 3};

and I want to find indexes, where the adjacent elements aren't equal:

1
4
5

My solution is (which isn't working):

std::vector<int> v = {1, 1, 2, 2, 2, 3};

auto i1 = std::begin(v);

while(1)
{
    i1 = std::adjacent_find(i1, std::end(v), std::not_equal_to<int>());
    std::cout << std::distance(std::begin(v), i1) << '\n';

    if (i1++ == std::end(v))
        break;
}

This prints:

1
4
6

The last elements points to index 6, but I want it to point 5 (value 3). Any help appreciated!


问:
SOLVED: Laravel: connection to AWS RDS results in a timed out
I was trying to migrate the database to AWS RDS through Laravel using php artisan migrate, however, it gave me this error:

```<code>Illuminate\Database\QueryException  : SQLSTATE[08006] [7] could not connect to server: Connection timed out (0x0000274C/10060)
Is the server running on host "xxxxxxxxx.xxxxxxxxx.us-east-2.rds.amazonaws.com" (xx.xxx.xxx.xxx) and accepting
TCP/IP connections on port 5432? (SQL: select * from information_schema.tables where table_schema = public and table_name = migrations)
</code>```

I have done some researches on this issue, what I found is I need to create a new security group to allow the access from my IP address, and I have added a new rule with the Type of "PostgreSQL" and its default settings but my IP in the "Source" column.  And I am still not able to migrate my database (giving me the same error as above)

This is the database config in the .env file, maybe some fields are wrong?

```<code>DB_CONNECTION=pgsql
DB_HOST=xxxxxxxxx.xxxxxxxxx.us-east-2.rds.amazonaws.com
DB_PORT=5432
DB_DATABASE=xxxx
DB_USERNAME=xxxx
DB_PASSWORD=xxxx
</code>```

I would be appreciated for any helps!

答:
Have you checked if the server has access to RDS? </p>

<p>ssh into your server, then run </p>

```<code>psql -h xxxxxxxxx.xxxxxxxxx.us-east-2.rds.amazonaws.com -d mydb -U myuser
</code>```

Body:
I was trying to migrate the database to AWS RDS through Laravel using php artisan migrate, however, it gave me this error:

Illuminate\Database\QueryException  : SQLSTATE[08006] [7] could not connect to server: Connection timed out (0x0000274C/10060)
Is the server running on host "xxxxxxxxx.xxxxxxxxx.us-east-2.rds.amazonaws.com" (xx.xxx.xxx.xxx) and accepting
TCP/IP connections on port 5432? (SQL: select * from information_schema.tables where table_schema = public and table_name = migrations)

I have done some researches on this issue, what I found is I need to create a new security group to allow the access from my IP address, and I have added a new rule with the Type of "PostgreSQL" and its default settings but my IP in the "Source" column.  And I am still not able to migrate my database (giving me the same error as above)

This is the database config in the .env file, maybe some fields are wrong?

DB_CONNECTION=pgsql
DB_HOST=xxxxxxxxx.xxxxxxxxx.us-east-2.rds.amazonaws.com
DB_PORT=5432
DB_DATABASE=xxxx
DB_USERNAME=xxxx
DB_PASSWORD=xxxx

I would be appreciated for any helps!

Body:
Have you checked if the server has access to RDS?

ssh into your server, then run

psql -h xxxxxxxxx.xxxxxxxxx.us-east-2.rds.amazonaws.com -d mydb -U myuser


问:
How to bundle a static YAML file with a React Native app?
I'd like to ship my React Native app together with some static assets, like images, audio files, and one YAML file.

The images can be automatically bundled as described here:

```<code><Image source={require('./my-icon.png')} />
</code>```

Now I'm trying to do the same with the YAML file. This seems to work:

```<code>let yamlContent = require('../data/content.yaml');
</code>```

However, when running this in the Android simulator, I get an error:

```<code>error: bundling failed: Error: Unable to resolve module `../content.yaml` from
`C:\Users\....\path\to\loader.ts`:
The module `../content.yaml` could not be found from
`C:\Users\....\path\to\loader.ts`. Indeed, none of these files exist:
  * `C:\Users\....\path\to\data\content.yaml(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)`
  * `C:\Users\....\path\to\content.yaml\index(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)`
</code>```

I double-checked the path in the output, the file really exists.

How can I read static YAML files in React Native?

I also tried the same code outside of React Native, in a Node.js console app. In this situation, the file seems to be read (if the YAML is malformed, I get an error). However, the object yamlContent is always an empty Javascript object.

答:
Close 'packager' and delete node_modules folder.

and than reinstall all packages with npm install command

Body:
I'd like to ship my React Native app together with some static assets, like images, audio files, and one YAML file.

The images can be automatically bundled as described here:

<Image source={require('./my-icon.png')} />

Now I'm trying to do the same with the YAML file. This seems to work:

let yamlContent = require('../data/content.yaml');

However, when running this in the Android simulator, I get an error:

error: bundling failed: Error: Unable to resolve module `../content.yaml` from
`C:\Users\....\path\to\loader.ts`:
The module `../content.yaml` could not be found from
`C:\Users\....\path\to\loader.ts`. Indeed, none of these files exist:
  * `C:\Users\....\path\to\data\content.yaml(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)`
  * `C:\Users\....\path\to\content.yaml\index(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)`

I double-checked the path in the output, the file really exists.

How can I read static YAML files in React Native?

I also tried the same code outside of React Native, in a Node.js console app. In this situation, the file seems to be read (if the YAML is malformed, I get an error). However, the object yamlContent is always an empty Javascript object.


问:
How to remove overlay effect from html canvas image when event occur
I want to change the t-shirt color with input type color event listener. image is good in canvas. but, whenever the user changes color and an event fires, an overlay effect of that color comes on the image. I wanted to remove that overlay effect.
I wanted the image to look like exactly like as it looks like at starting point with the blue color with no overlay.

<input id="selectedColor" type="color" value="#0000ff">
        <canvas id="myDrawing" width="530" height="600">
```

```var x; //drawing context
var width; // canvas width
var height; // canvas height
var fg; //image
var buffer; //inner canvas
var color = '#0000ff'; //default color
function shirtColor(){
  return color;
}
function updateShirtColor(){
  //update value of color
  var currentColor = document.getElementById('selectedColor').value;
  color = currentColor;
}
window.onload = function() {
  var myColor = document.getElementById('selectedColor');
  myColor.addEventListener('change',draw);

    var drawingCanvas = document.getElementById('myDrawing');
    // Check the element is in the DOM and the browser supports canvas
    if(drawingCanvas && drawingCanvas.getContext) {
        // Initaliase a 2-dimensional drawing context
        width = drawingCanvas.width;
        height = drawingCanvas.height;
        x = drawingCanvas.getContext('2d');

        // grey box grid for transparency testing
        x.fillStyle = shirtColor();
        x.fillRect(0,0,width,height);
        fg = new Image();
        fg.src = 'https://d1b2zzpxewkr9z.cloudfront.net/images/products/apparel/product_type_1_front.png';

        // create offscreen buffer,
        buffer = document.createElement('canvas');
        buffer.width = fg.width;
        buffer.height = fg.height;
        bx = buffer.getContext('2d');

        // fill offscreen buffer with the tint color
        bx.fillStyle = '#FF';
        bx.fillRect(0,0,buffer.width,buffer.height);

        // destination atop makes a result with an alpha channel identical to fg, but with all pixels retaining their original color *as far as I can tell*
        bx.globalCompositeOperation = "destination-atop";
        bx.drawImage(fg,0,0);

        // to tint the image, draw it first
        x.drawImage(fg,0,0);

        //then set the global alpha to the amound that you want to tint it, and draw the buffer directly on top of it.
        x.globalAlpha = 0.5;
        x=x.drawImage(buffer,0,0);
    }
}
function draw(){
  updateShirtColor();
  var drawingCanvas = document.getElementById('myDrawing');
  // Check the element is in the DOM and the browser supports canvas
  if(drawingCanvas && drawingCanvas.getContext) {
      // Initaliase a 2-dimensional drawing context
      width = drawingCanvas.width;
      height = drawingCanvas.height;
      x = drawingCanvas.getContext('2d');
      x.clearRect(0, 0,width,height);
      // grey box grid for transparency testing
      x.fillStyle = shirtColor();
      x.fillRect(0,0,width,height);

      fg = new Image();
      fg.src = 'https://d1b2zzpxewkr9z.cloudfront.net/images/products/apparel/product_type_1_front.png';

      // create offscreen buffer,
      buffer.width = fg.width;
      buffer.height = fg.height;
      bx = buffer.getContext('2d');

      // fill offscreen buffer with the tint color
      bx.clearRect(0, 0, buffer.width, buffer.height);
      bx.fillStyle = '#FF';
      bx.fillRect(0,0,buffer.width,buffer.height);

      // destination atop makes a result with an alpha channel identical to fg, but with all pixels retaining their original color *as far as I can tell*
      bx.globalCompositeOperation = "destination-atop";
      bx.drawImage(fg,0,0);

      // to tint the image, draw it first
      x.drawImage(fg,0,0);

      //then set the global alpha to the amound that you want to tint it, and draw the buffer directly on top of it.
      x.globalAlpha = 0.5;
      x=x.drawImage(buffer,0,0);
  }
}
```

I expect to have clear image without overlay effect after color change event occur.

答:
I'm not very sure this is what you were asking. You have an error in your code. You try to draw the image before it's loaded. I've wrapped that part of code in fg.onload = function() {....}

A second error you have: in the function draw you create a new image every time you call the function. You don't need to. You already have the fg variable. Just use it.

var x; //drawing context
var width; // canvas width
var height; // canvas height
var fg; //image
var buffer; //inner canvas
var color = "#0000ff"; //default color
function shirtColor() {
  return color;
}
function updateShirtColor() {
  //update value of color
  var currentColor = document.getElementById("selectedColor").value;
  color = currentColor;
}
window.onload = function() {
  var myColor = document.getElementById("selectedColor");
  myColor.addEventListener("change", draw);

  var drawingCanvas = document.getElementById("myDrawing");
  // Check the element is in the DOM and the browser supports canvas
  if (drawingCanvas && drawingCanvas.getContext) {
    // Initaliase a 2-dimensional drawing context
    width = drawingCanvas.width;
    height = drawingCanvas.height;
    x = drawingCanvas.getContext("2d");

    // grey box grid for transparency testing
    x.fillStyle = shirtColor();
    x.fillRect(0, 0, width, height);
    fg = new Image();
    fg.src =
      "https://d1b2zzpxewkr9z.cloudfront.net/images/products/apparel/product_type_1_front.png";
    fg.onload = function() {
      // create offscreen buffer,
      buffer = document.createElement("canvas");
      buffer.width = fg.width;
      buffer.height = fg.height;
      bx = buffer.getContext("2d");

      // fill offscreen buffer with the tint color
      bx.fillStyle = "#FF";
      bx.fillRect(0, 0, buffer.width, buffer.height);

      // destination atop makes a result with an alpha channel identical to fg, but with all pixels retaining their original color *as far as I can tell*
      bx.globalCompositeOperation = "destination-atop";
      bx.drawImage(fg, 0, 0);

      // to tint the image, draw it first
      x.drawImage(fg, 0, 0);

      //then set the global alpha to the amound that you want to tint it, and draw the buffer directly on top of it.
      //x.globalAlpha = 0.5;
      //x=x.drawImage(buffer,0,0);
    };
  }
};
function draw() {
  updateShirtColor();
  var drawingCanvas = document.getElementById("myDrawing");
  // Check the element is in the DOM and the browser supports canvas
  if (drawingCanvas && drawingCanvas.getContext) {
    // Initaliase a 2-dimensional drawing context
    width = drawingCanvas.width;
    height = drawingCanvas.height;
    x = drawingCanvas.getContext("2d");
    x.clearRect(0, 0, width, height);
    // grey box grid for transparency testing
    x.fillStyle = shirtColor();
    x.fillRect(0, 0, width, height);

      // create offscreen buffer,
      buffer.width = fg.width;
      buffer.height = fg.height;
      bx = buffer.getContext("2d");

      // fill offscreen buffer with the tint color
      bx.clearRect(0, 0, buffer.width, buffer.height);
      bx.fillStyle = "#FF";
      bx.fillRect(0, 0, buffer.width, buffer.height);

      // destination atop makes a result with an alpha channel identical to fg, but with all pixels retaining their original color *as far as I can tell*
      bx.globalCompositeOperation = "destination-atop";
      bx.drawImage(fg, 0, 0);

      // to tint the image, draw it first
      x.drawImage(fg, 0, 0);

      //then set the global alpha to the amound that you want to tint it, and draw the buffer directly on top of it.
      //x.globalAlpha = 0.5;
      //x=x.drawImage(buffer,0,0);

  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="selectedColor" type="color" value="#0000ff">
        <canvas id="myDrawing" width="530" height="600"></code>```

Body:
I want to change the t-shirt color with input type color event listener. image is good in canvas. but, whenever the user changes color and an event fires, an overlay effect of that color comes on the image. I wanted to remove that overlay effect.
I wanted the image to look like exactly like as it looks like at starting point with the blue color with no overlay.

<input id="selectedColor" type="color" value="#0000ff">
        <canvas id="myDrawing" width="530" height="600">

var x; //drawing context
var width; // canvas width
var height; // canvas height
var fg; //image
var buffer; //inner canvas
var color = '#0000ff'; //default color
function shirtColor(){
  return color;
}
function updateShirtColor(){
  //update value of color
  var currentColor = document.getElementById('selectedColor').value;
  color = currentColor;
}
window.onload = function() {
  var myColor = document.getElementById('selectedColor');
  myColor.addEventListener('change',draw);

    var drawingCanvas = document.getElementById('myDrawing');
    // Check the element is in the DOM and the browser supports canvas
    if(drawingCanvas && drawingCanvas.getContext) {
        // Initaliase a 2-dimensional drawing context
        width = drawingCanvas.width;
        height = drawingCanvas.height;
        x = drawingCanvas.getContext('2d');

        // grey box grid for transparency testing
        x.fillStyle = shirtColor();
        x.fillRect(0,0,width,height);
        fg = new Image();
        fg.src = 'https://d1b2zzpxewkr9z.cloudfront.net/images/products/apparel/product_type_1_front.png';

        // create offscreen buffer,
        buffer = document.createElement('canvas');
        buffer.width = fg.width;
        buffer.height = fg.height;
        bx = buffer.getContext('2d');

        // fill offscreen buffer with the tint color
        bx.fillStyle = '#FF';
        bx.fillRect(0,0,buffer.width,buffer.height);

        // destination atop makes a result with an alpha channel identical to fg, but with all pixels retaining their original color *as far as I can tell*
        bx.globalCompositeOperation = "destination-atop";
        bx.drawImage(fg,0,0);

        // to tint the image, draw it first
        x.drawImage(fg,0,0);

        //then set the global alpha to the amound that you want to tint it, and draw the buffer directly on top of it.
        x.globalAlpha = 0.5;
        x=x.drawImage(buffer,0,0);
    }
}
function draw(){
  updateShirtColor();
  var drawingCanvas = document.getElementById('myDrawing');
  // Check the element is in the DOM and the browser supports canvas
  if(drawingCanvas && drawingCanvas.getContext) {
      // Initaliase a 2-dimensional drawing context
      width = drawingCanvas.width;
      height = drawingCanvas.height;
      x = drawingCanvas.getContext('2d');
      x.clearRect(0, 0,width,height);
      // grey box grid for transparency testing
      x.fillStyle = shirtColor();
      x.fillRect(0,0,width,height);

      fg = new Image();
      fg.src = 'https://d1b2zzpxewkr9z.cloudfront.net/images/products/apparel/product_type_1_front.png';

      // create offscreen buffer,
      buffer.width = fg.width;
      buffer.height = fg.height;
      bx = buffer.getContext('2d');

      // fill offscreen buffer with the tint color
      bx.clearRect(0, 0, buffer.width, buffer.height);
      bx.fillStyle = '#FF';
      bx.fillRect(0,0,buffer.width,buffer.height);

      // destination atop makes a result with an alpha channel identical to fg, but with all pixels retaining their original color *as far as I can tell*
      bx.globalCompositeOperation = "destination-atop";
      bx.drawImage(fg,0,0);

      // to tint the image, draw it first
      x.drawImage(fg,0,0);

      //then set the global alpha to the amound that you want to tint it, and draw the buffer directly on top of it.
      x.globalAlpha = 0.5;
      x=x.drawImage(buffer,0,0);
  }
}

I expect to have clear image without overlay effect after color change event occur.

Body:
I'm not very sure this is what you were asking. You have an error in your code. You try to draw the image before it's loaded. I've wrapped that part of code in fg.onload = function() {....}

A second error you have: in the function draw you create a new image every time you call the function. You don't need to. You already have the fg variable. Just use it.

var x; //drawing context
var width; // canvas width
var height; // canvas height
var fg; //image
var buffer; //inner canvas
var color = "#0000ff"; //default color
function shirtColor() {
  return color;
}
function updateShirtColor() {
  //update value of color
  var currentColor = document.getElementById("selectedColor").value;
  color = currentColor;
}
window.onload = function() {
  var myColor = document.getElementById("selectedColor");
  myColor.addEventListener("change", draw);

  var drawingCanvas = document.getElementById("myDrawing");
  // Check the element is in the DOM and the browser supports canvas
  if (drawingCanvas && drawingCanvas.getContext) {
    // Initaliase a 2-dimensional drawing context
    width = drawingCanvas.width;
    height = drawingCanvas.height;
    x = drawingCanvas.getContext("2d");

    // grey box grid for transparency testing
    x.fillStyle = shirtColor();
    x.fillRect(0, 0, width, height);
    fg = new Image();
    fg.src =
      "https://d1b2zzpxewkr9z.cloudfront.net/images/products/apparel/product_type_1_front.png";
    fg.onload = function() {
      // create offscreen buffer,
      buffer = document.createElement("canvas");
      buffer.width = fg.width;
      buffer.height = fg.height;
      bx = buffer.getContext("2d");

      // fill offscreen buffer with the tint color
      bx.fillStyle = "#FF";
      bx.fillRect(0, 0, buffer.width, buffer.height);

      // destination atop makes a result with an alpha channel identical to fg, but with all pixels retaining their original color *as far as I can tell*
      bx.globalCompositeOperation = "destination-atop";
      bx.drawImage(fg, 0, 0);

      // to tint the image, draw it first
      x.drawImage(fg, 0, 0);

      //then set the global alpha to the amound that you want to tint it, and draw the buffer directly on top of it.
      //x.globalAlpha = 0.5;
      //x=x.drawImage(buffer,0,0);
    };
  }
};
function draw() {
  updateShirtColor();
  var drawingCanvas = document.getElementById("myDrawing");
  // Check the element is in the DOM and the browser supports canvas
  if (drawingCanvas && drawingCanvas.getContext) {
    // Initaliase a 2-dimensional drawing context
    width = drawingCanvas.width;
    height = drawingCanvas.height;
    x = drawingCanvas.getContext("2d");
    x.clearRect(0, 0, width, height);
    // grey box grid for transparency testing
    x.fillStyle = shirtColor();
    x.fillRect(0, 0, width, height);

      // create offscreen buffer,
      buffer.width = fg.width;
      buffer.height = fg.height;
      bx = buffer.getContext("2d");

      // fill offscreen buffer with the tint color
      bx.clearRect(0, 0, buffer.width, buffer.height);
      bx.fillStyle = "#FF";
      bx.fillRect(0, 0, buffer.width, buffer.height);

      // destination atop makes a result with an alpha channel identical to fg, but with all pixels retaining their original color *as far as I can tell*
      bx.globalCompositeOperation = "destination-atop";
      bx.drawImage(fg, 0, 0);

      // to tint the image, draw it first
      x.drawImage(fg, 0, 0);

      //then set the global alpha to the amound that you want to tint it, and draw the buffer directly on top of it.
      //x.globalAlpha = 0.5;
      //x=x.drawImage(buffer,0,0);

  }
}

<input id="selectedColor" type="color" value="#0000ff">
        <canvas id="myDrawing" width="530" height="600">


问:
How can I match on a specific io::Error type?
I am trying to read in a file until the end 2 bytes at a time and I want to catch the EOF error:</p>
```<code>use byteorder::{BigEndian, ReadBytesExt}; // 1.3.4
use std::fs::File;

fn main() {
    let filename = "/etc/hosts";
    let mut file = File::open(filename).expect("Cannot open file");
    loop {
        let binary = match file.read_u16::<BigEndian>() {
            Ok(binary) => binary,
            Err(e) => panic!("Can't read from file: {}, err {}", filename, e),
            // Can I catch the EOF error here?
        };
        println!("{:?}", binary);
    }
}
</code>```

答:
Here is an example of matching a MySQL IoError:

```<code>match pool.prep_exec("SELECT SLEEP(10)", ()) {
    Ok(_) => (),
    Err(mysql::Error::IoError(e)) => {
        eprintln!("IoError: {}", e);
        do_something();
    }
    Err(e) => {
        eprintln!("{}", e);
        return;
    }
}
</code>```

Body:
I am trying to read in a file until the end 2 bytes at a time and I want to catch the EOF error:

use byteorder::{BigEndian, ReadBytesExt}; // 1.3.4
use std::fs::File;

fn main() {
    let filename = "/etc/hosts";
    let mut file = File::open(filename).expect("Cannot open file");
    loop {
        let binary = match file.read_u16::<BigEndian>() {
            Ok(binary) => binary,
            Err(e) => panic!("Can't read from file: {}, err {}", filename, e),
            // Can I catch the EOF error here?
        };
        println!("{:?}", binary);
    }
}

Body:
Here is an example of matching a MySQL IoError:

match pool.prep_exec("SELECT SLEEP(10)", ()) {
    Ok(_) => (),
    Err(mysql::Error::IoError(e)) => {
        eprintln!("IoError: {}", e);
        do_something();
    }
    Err(e) => {
        eprintln!("{}", e);
        return;
    }
}