问:
Adding 12 months to February 29
I want to add 12 months to my date. My start date is 02/29/2020 and I want to add 12 months to this.

Code:

```<code>$startdate = '02/29/2020';
date('m/d/Y', strtotime('+12 months', strtotime($startdate)));
</code>```

Output:

```<code>03/01/2021
</code>```

I used this code to add 12 months but the output is 03/01/2021, when the real output should be 02/28/2020.

答:
Have a look!

```<code> function add_months($months, DateTime $dateObject)
   {
        $next = new DateTime($dateObject->format('Y-m-d'));
        $next->modify('last day of +'.$months.' month');

        if($dateObject->format('d') > $next->format('d')) {
            return $dateObject->diff($next);
        } else {
            return new DateInterval('P'.$months.'M');
        }
    }

function getCalculatedDate($d1, $months)
{
    $date = new DateTime($d1);

    // call second function to add the months
    $newDate = $date->add(add_months($months, $date));

    //formats final date to m/d/Y form
    $dateReturned = $newDate->format('m/d/Y');

    return $dateReturned;
}
</code>```

An example would be:-

```<code>$startDate = '02/29/2020';
$nMonths = 12; // choose how many months you want to add
$finalDate = getCalculatedDate($startDate, $nMonths); // output: 02/28/2021
</code>```

This way you will get the output of 02/28/2021

Title: Adding 12 months to February 29

Body:
I want to add 12 months to my date. My start date is 02/29/2020 and I want to add 12 months to this.

Code:

$startdate = '02/29/2020';
date('m/d/Y', strtotime('+12 months', strtotime($startdate)));

Output:

03/01/2021

I used this code to add 12 months but the output is 03/01/2021, when the real output should be 02/28/2020.

Body:
Have a look!

 function add_months($months, DateTime $dateObject)
   {
        $next = new DateTime($dateObject->format('Y-m-d'));
        $next->modify('last day of +'.$months.' month');

        if($dateObject->format('d') > $next->format('d')) {
            return $dateObject->diff($next);
        } else {
            return new DateInterval('P'.$months.'M');
        }
    }

function getCalculatedDate($d1, $months)
{
    $date = new DateTime($d1);

    // call second function to add the months
    $newDate = $date->add(add_months($months, $date));

    //formats final date to m/d/Y form
    $dateReturned = $newDate->format('m/d/Y');

    return $dateReturned;
}

An example would be:-

$startDate = '02/29/2020';
$nMonths = 12; // choose how many months you want to add
$finalDate = getCalculatedDate($startDate, $nMonths); // output: 02/28/2021

This way you will get the output of 02/28/2021


来源: stackexchange

问:
Are triple quotation marks unicode characters according to python
I'm trying to use triple quotes to designate a large comment, but I'm getting a new error that says

SyntaxError: invalid string (possibly contains a unicode character) on line 2

Here's the code.

```<code>"""

Write a program that asks the user how many names they have.
(If they have a first name, two middle names, and a last
name, for example, they would type 4.) Then, using a for
loop, ask the user for each of their names. Finally, print
their full name.

"""
</code>```

The triple quotes that I'm having a problem with are the ones at the top.

With that information out of the way, my question is "Are triple quotation marks unicode characters according to python?"

If this is a repeat post, feel free to move it.

答:
In your example, the provided characters are all valid ASCII characters (The Basic Latin Unicode block just happens to have the exact same character set as ASCII). So this should not cause any issues in a standard Python interpreter like CPython or PyPy (regardless whether it's Python 2 or 3).

Are triple quotation marks Unicode characters according to Python?

Technically all ASCII characters are included in Unicode, but what I think you're really asking is "Are triple quotation marks non-ASCII characters?", to which the answer is "No". They're just three QUOTATION MARK (") in a row.

>>> for c in '"""':
...     print('Character:', repr(c))
...
Character: '"'
Character: '"'
Character: '"'
```

<p>You can also check this pretty easily in Python 3.7+ using the <code>str.isascii</code> method:</p>

<pre class="lang-py prettyprint-override"><code>>>> '"""'.isascii()
True
>>> '""☺'.isascii()
False
</code>```

It used to be that to use Unicode literals in your source files you would need to include a special comment in the first or second line of your source files (e.g. # -*- coding: utf-8 -*-), but as of Python 3 source files default to using UTF-8.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use triple quotes to designate a large comment, but I'm getting a new error that says

SyntaxError: invalid string (possibly contains a unicode character) on line 2

Here's the code.

"""

Write a program that asks the user how many names they have.
(If they have a first name, two middle names, and a last
name, for example, they would type 4.) Then, using a for
loop, ask the user for each of their names. Finally, print
their full name.

"""

The triple quotes that I'm having a problem with are the ones at the top.

With that information out of the way, my question is "Are triple quotation marks unicode characters according to python?"

If this is a repeat post, feel free to move it.

Body:
In your example, the provided characters are all valid ASCII characters (The Basic Latin Unicode block just happens to have the exact same character set as ASCII). So this should not cause any issues in a standard Python interpreter like CPython or PyPy (regardless whether it's Python 2 or 3).

Are triple quotation marks Unicode characters according to Python?

Technically all ASCII characters are included in Unicode, but what I think you're really asking is "Are triple quotation marks non-ASCII characters?", to which the answer is "No". They're just three QUOTATION MARK (") in a row.

>>> for c in '"""':
...     print('Character:', repr(c))
...
Character: '"'
Character: '"'
Character: '"'

You can also check this pretty easily in Python 3.7+ using the str.isascii method:

>>> '"""'.isascii()
True
>>> '""☺'.isascii()
False

It used to be that to use Unicode literals in your source files you would need to include a special comment in the first or second line of your source files (e.g. # -*- coding: utf-8 -*-), but as of Python 3 source files default to using UTF-8.

ContentLicense: CC BY-SA 4.0


问:
Which Class is missing in the following program?
```<code>class Test
{
int unique_element(int arr[],int n)
{
    int result=0;
    for(int i=0;i<n;i++)
    {
        int sum=0;
        x=(1<<i);
        for(int j=0;j<n;j++)
        {
            if(arr[j]&x)
                sum++;
        }
        if(sum%3)
        {
            result |= x;
            System.out.println(x);
        }
    }
    return(result);
}
public static void main(String[] args){
    int arr[]={3,1,1,9,3,1,3,9,9,5};
    N=arr.length;
    System.out.println(unique_element(arr[],N));
    }
}
</code>```

Program for every element appears 3 times in a given arr except 1 element. Logic is correct but I'm getting error in print statement like .class is expected.

Test.java:28:error: '.class' expected

System.out.println(unique_element(arr[],N));

and i'm getting error in if statement --> if(arr[j] & x){ sum++;}

Test.java:298: error: incompatible types: int cannot be converted to boolean

```<code>      if(arr[j]&x)
</code>```

答:
Although these answers given will get you the correct answer I would opt to take the different approach and actually make unique_element a static method, meaning that there will only ever be one instance of it. A static method is perfect for this because it requires no state, two inputs and one, output.

Example:

```<code>
package org.stackoverflow.thread_safe_account;

public class Test {
    public static int unique_element(int arr[],
                                     int n) {
        int result = 0;
        for (int i = 0; i < n; i++) {
            int sum = 0;
            x = (1 << i);
            for (int j = 0; j < n; j++) {
                if (arr[j] & x)
                    sum++;
            }
            if (sum % 3) {
                result |= x;
                System.out.println(x);
            }
        }
        return (result);
    }

    public static void main(String[] args) {
        int arr[] = {3, 1, 1, 9, 3, 1, 3, 9, 9, 5};
        N = arr.length;
        System.out.println(Test.unique_element(arr[],N));
    }
}
</code>```

Body:
class Test
{
int unique_element(int arr[],int n)
{
    int result=0;
    for(int i=0;i<n;i++)
    {
        int sum=0;
        x=(1<<i);
        for(int j=0;j<n;j++)
        {
            if(arr[j]&x)
                sum++;
        }
        if(sum%3)
        {
            result |= x;
            System.out.println(x);
        }
    }
    return(result);
}
public static void main(String[] args){
    int arr[]={3,1,1,9,3,1,3,9,9,5};
    N=arr.length;
    System.out.println(unique_element(arr[],N));
    }
}

Program for every element appears 3 times in a given arr except 1 element. Logic is correct but I'm getting error in print statement like .class is expected.

Test.java:28:error: '.class' expected

System.out.println(unique_element(arr[],N));

and i'm getting error in if statement --> if(arr[j] & x){ sum++;}

Test.java:298: error: incompatible types: int cannot be converted to boolean

      if(arr[j]&x)

Body:
Although these answers given will get you the correct answer I would opt to take the different approach and actually make unique_element a static method, meaning that there will only ever be one instance of it. A static method is perfect for this because it requires no state, two inputs and one, output.

Example:

package org.stackoverflow.thread_safe_account;

public class Test {
    public static int unique_element(int arr[],
                                     int n) {
        int result = 0;
        for (int i = 0; i < n; i++) {
            int sum = 0;
            x = (1 << i);
            for (int j = 0; j < n; j++) {
                if (arr[j] & x)
                    sum++;
            }
            if (sum % 3) {
                result |= x;
                System.out.println(x);
            }
        }
        return (result);
    }

    public static void main(String[] args) {
        int arr[] = {3, 1, 1, 9, 3, 1, 3, 9, 9, 5};
        N = arr.length;
        System.out.println(Test.unique_element(arr[],N));
    }
}


问:
Angular subscribe property doesnt exist on object
I know I need to make an interface here but the issue is that I'm subscribing so I can't add it. What are my other options?

```<code>login(form: NgForm) {
    this.authService.login(form.value.email, form.value.password).subscribe(
      result => {
        this.authService.setToken(result.token);
        this.authService.setUserId(result.userId);
      },
      error => {
        this.alertService.presentToast(error.error.message);
      }
    );
  }
</code>```

Auth service login function

```<code>login(email: String, password: String) {
    return this.http.post(this.env.API_URL + 'auth/login',
      {email: email, password: password}
    )
  }
</code>```

答:
This one should work as I tried

Service

```<code>login(email: String, password: String)
    {
       return this.http.post(this.env.API_URL + 'auth/login', {email: email, password: password}).pipe(map((response:any)=>{
         const result=response;
         if(result){
            this.setToken(result.token);
            this.setUserId(result.userId);
         }
       }))
    }
</code>```

Component

```<code>login() {
        this.authService.login(form.value.email, form.value.password).subscribe(
          result => {
             //form values should be cleared after login
             form.value.email="";
             form.value.password="";
          },
          error => {
            this.alertService.presentToast(error.error.message);
          }
        );
      }
</code>```

Body:
I know I need to make an interface here but the issue is that I'm subscribing so I can't add it. What are my other options?

login(form: NgForm) {
    this.authService.login(form.value.email, form.value.password).subscribe(
      result => {
        this.authService.setToken(result.token);
        this.authService.setUserId(result.userId);
      },
      error => {
        this.alertService.presentToast(error.error.message);
      }
    );
  }

Auth service login function

login(email: String, password: String) {
    return this.http.post(this.env.API_URL + 'auth/login',
      {email: email, password: password}
    )
  }

Body:
This one should work as I tried

Service

login(email: String, password: String)
    {
       return this.http.post(this.env.API_URL + 'auth/login', {email: email, password: password}).pipe(map((response:any)=>{
         const result=response;
         if(result){
            this.setToken(result.token);
            this.setUserId(result.userId);
         }
       }))
    }

Component

login() {
        this.authService.login(form.value.email, form.value.password).subscribe(
          result => {
             //form values should be cleared after login
             form.value.email="";
             form.value.password="";
          },
          error => {
            this.alertService.presentToast(error.error.message);
          }
        );
      }


问:
How to prevent bottom views pushing up when keyboard opens
There are two edittext on a screen and a button on bottom of the screen, the problem is when I click on edittext and keyboard open ups the button at the bottom appears above the keyboard, I want bottom buton to be at its original place rather than moving up with keyboard. the button is bottom aligned

Thanks

P.S:
I have tried adjust pan, resize etc nothing working

```<code><activity
        android:screenOrientation="portrait"
        android:name=".activities.MainActivity"
        android:windowSoftInputMode="stateUnchanged|adjustResize"
        android:theme="@style/AppTheme"
     />
</code>```

XML:

```<code><androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/text_white"
    android:orientation="vertical"
    android:paddingTop="@dimen/_20sdp"
    android:elevation="5dp"
    tools:context=".fragments.login.LoginFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_welcome"
        android:layout_marginRight="@dimen/_40sdp"
        android:layout_marginStart="@dimen/_20sdp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:maxLines="2"
        style="@style/headingText"
        android:text="Welcome to the World \nof PACKR" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:id="@+id/tv_continue"
        android:visibility="gone"
        app:layout_constraintTop_toBottomOf="@+id/tv_welcome"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="@dimen/_20sdp"
        android:layout_marginStart="@dimen/_20sdp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:text="Sign in to continue" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginTop="@dimen/_20sdp"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_marginStart="@dimen/_20sdp"
        android:layout_marginEnd="@dimen/_20sdp"
        app:layout_constraintTop_toBottomOf="@+id/tv_continue"
        android:id="@+id/phone_layout"
        android:orientation="horizontal">

        <com.hbb20.CountryCodePicker
            android:layout_marginEnd="@dimen/_10sdp"
            android:layout_width="0dp"
            android:layout_weight="0.4"
            android:textSize="@dimen/_12sdp"
            android:id="@+id/countryCode"
            style="@style/smallText"
            android:background="@drawable/edittext_background"
            android:layout_height="match_parent" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="0.6"
            android:hint="Phone Number"
            android:inputType="number"
            style="@style/smallText"
            android:id="@+id/et_phone"
            android:maxLength="11"
            android:padding="@dimen/_10sdp"
            android:drawablePadding="10dp"
            android:drawableStart="@drawable/ic_phone"
            android:background="@drawable/edittext_background"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <EditText
        android:layout_width="match_parent"
        android:layout_marginTop="@dimen/_10sdp"
        android:hint="Password"
        android:singleLine="true"
        android:drawablePadding="10dp"
        android:layout_marginEnd="@dimen/_20sdp"
        android:layout_marginStart="@dimen/_20sdp"
        app:layout_constraintTop_toBottomOf="@+id/phone_layout"
        app:layout_constraintLeft_toLeftOf="parent"
        android:padding="@dimen/_10sdp"
        style="@style/smallText"
        android:inputType="textPassword"
        android:id="@+id/et_password"
        android:drawableStart="@drawable/ic_lock"
        android:background="@drawable/edittext_background"
        android:layout_height="wrap_content" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:id="@+id/forgot_layout"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="@dimen/_15sdp"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/img_"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintRight_toRightOf="@+id/forgot_pass"
            app:layout_constraintLeft_toLeftOf="@+id/forgot_pass"
            android:src="@drawable/forgot_icon"
            android:layout_marginEnd="@dimen/_20sdp"
            android:layout_marginStart="@dimen/_20sdp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAllCaps="false"
            style="@style/smallText"
            android:layout_marginEnd="@dimen/_20sdp"
            android:layout_marginStart="@dimen/_20sdp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/img_"
            android:layout_gravity="right"
            android:padding="@dimen/_5sdp"
            android:textColor="@color/grey_border"
            android:id="@+id/forgot_pass"
            android:layout_marginTop="8dp" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_signin"
        android:textAppearance="@style/textOnButton"
        android:text="Login"
        app:layout_constraintTop_toBottomOf="@+id/et_password"
        android:layout_marginEnd="@dimen/_20sdp"
        android:layout_marginStart="@dimen/_20sdp"
        android:layout_marginTop="@dimen/_30sdp"
        android:paddingLeft="5dp"
        />

        <ProgressBar
            android:id="@+id/pb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minHeight="50dp"
            android:minWidth="50dp"
            android:gravity="center"
            android:indeterminate="true"
            android:elevation="10dp"
            android:visibility="gone"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="@color/orange"
            />

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

答:
Set your XML file like this (make changes as per your need)

```<code>    <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical"
    android:paddingTop="20dp"
    android:elevation="5dp"
    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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_welcome"
        android:layout_marginRight="40dp"
        android:layout_marginStart="20dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:maxLines="2"
        style="App Wep"
        android:text="Welcome to the World \nof PACKR" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:id="@+id/tv_continue"
        android:visibility="gone"
        app:layout_constraintTop_toBottomOf="@+id/tv_welcome"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="20dp"
        android:layout_marginStart="20dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:text="Sign in to continue" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginTop="20dp"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        app:layout_constraintTop_toBottomOf="@+id/tv_continue"
        android:id="@+id/phone_layout"
        android:orientation="horizontal">

        <com.hbb20.CountryCodePicker
            android:layout_marginEnd="10dp"
            android:layout_width="0dp"
            android:layout_weight="0.4"
            android:textSize="12dp"
            android:id="@+id/countryCode"
            android:layout_height="match_parent" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="0.6"
            android:hint="Phone Number"
            android:inputType="number"
            android:id="@+id/et_phone"
            android:maxLength="11"
            android:padding="10dp"
            android:drawablePadding="10dp"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <EditText
        android:layout_width="match_parent"
        android:layout_marginTop="10dp"
        android:hint="Password"
        android:singleLine="true"
        android:drawablePadding="10dp"
        android:layout_marginEnd="20dp"
        android:layout_marginStart="20dp"
        app:layout_constraintTop_toBottomOf="@+id/phone_layout"
        app:layout_constraintLeft_toLeftOf="parent"
        android:padding="10dp"
        android:inputType="textPassword"
        android:id="@+id/et_password"
        android:layout_height="wrap_content" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:id="@+id/forgot_layout"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="15dp"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/img_"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintRight_toRightOf="@+id/forgot_pass"
            app:layout_constraintLeft_toLeftOf="@+id/forgot_pass"
            android:layout_marginEnd="20dp"
            android:layout_marginStart="20dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAllCaps="false"
            android:layout_marginEnd="20dp"
            android:layout_marginStart="20dp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/img_"
            android:layout_gravity="right"
            android:padding="5dp"
            android:id="@+id/forgot_pass"
            android:layout_marginTop="8dp" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_signin"
        android:text="Login"
        app:layout_constraintTop_toBottomOf="@+id/et_password"
        android:layout_marginEnd="20dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="30dp"
        android:paddingLeft="5dp"
        />

    <ProgressBar
        android:id="@+id/pb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="50dp"
        android:minWidth="50dp"
        android:gravity="center"
        android:indeterminate="true"
        android:elevation="10dp"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:indeterminateTintMode="src_atop"
        />

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

And Manifest as this(Example)

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

Remove WindowSoftInput mode.

Body:
There are two edittext on a screen and a button on bottom of the screen, the problem is when I click on edittext and keyboard open ups the button at the bottom appears above the keyboard, I want bottom buton to be at its original place rather than moving up with keyboard. the button is bottom aligned

Thanks

P.S:
I have tried adjust pan, resize etc nothing working

<activity
        android:screenOrientation="portrait"
        android:name=".activities.MainActivity"
        android:windowSoftInputMode="stateUnchanged|adjustResize"
        android:theme="@style/AppTheme"
     />

XML:

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/text_white"
    android:orientation="vertical"
    android:paddingTop="@dimen/_20sdp"
    android:elevation="5dp"
    tools:context=".fragments.login.LoginFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_welcome"
        android:layout_marginRight="@dimen/_40sdp"
        android:layout_marginStart="@dimen/_20sdp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:maxLines="2"
        style="@style/headingText"
        android:text="Welcome to the World \nof PACKR" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:id="@+id/tv_continue"
        android:visibility="gone"
        app:layout_constraintTop_toBottomOf="@+id/tv_welcome"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="@dimen/_20sdp"
        android:layout_marginStart="@dimen/_20sdp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:text="Sign in to continue" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginTop="@dimen/_20sdp"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_marginStart="@dimen/_20sdp"
        android:layout_marginEnd="@dimen/_20sdp"
        app:layout_constraintTop_toBottomOf="@+id/tv_continue"
        android:id="@+id/phone_layout"
        android:orientation="horizontal">

        <com.hbb20.CountryCodePicker
            android:layout_marginEnd="@dimen/_10sdp"
            android:layout_width="0dp"
            android:layout_weight="0.4"
            android:textSize="@dimen/_12sdp"
            android:id="@+id/countryCode"
            style="@style/smallText"
            android:background="@drawable/edittext_background"
            android:layout_height="match_parent" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="0.6"
            android:hint="Phone Number"
            android:inputType="number"
            style="@style/smallText"
            android:id="@+id/et_phone"
            android:maxLength="11"
            android:padding="@dimen/_10sdp"
            android:drawablePadding="10dp"
            android:drawableStart="@drawable/ic_phone"
            android:background="@drawable/edittext_background"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <EditText
        android:layout_width="match_parent"
        android:layout_marginTop="@dimen/_10sdp"
        android:hint="Password"
        android:singleLine="true"
        android:drawablePadding="10dp"
        android:layout_marginEnd="@dimen/_20sdp"
        android:layout_marginStart="@dimen/_20sdp"
        app:layout_constraintTop_toBottomOf="@+id/phone_layout"
        app:layout_constraintLeft_toLeftOf="parent"
        android:padding="@dimen/_10sdp"
        style="@style/smallText"
        android:inputType="textPassword"
        android:id="@+id/et_password"
        android:drawableStart="@drawable/ic_lock"
        android:background="@drawable/edittext_background"
        android:layout_height="wrap_content" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:id="@+id/forgot_layout"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="@dimen/_15sdp"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/img_"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintRight_toRightOf="@+id/forgot_pass"
            app:layout_constraintLeft_toLeftOf="@+id/forgot_pass"
            android:src="@drawable/forgot_icon"
            android:layout_marginEnd="@dimen/_20sdp"
            android:layout_marginStart="@dimen/_20sdp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAllCaps="false"
            style="@style/smallText"
            android:layout_marginEnd="@dimen/_20sdp"
            android:layout_marginStart="@dimen/_20sdp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/img_"
            android:layout_gravity="right"
            android:padding="@dimen/_5sdp"
            android:textColor="@color/grey_border"
            android:id="@+id/forgot_pass"
            android:layout_marginTop="8dp" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_signin"
        android:textAppearance="@style/textOnButton"
        android:text="Login"
        app:layout_constraintTop_toBottomOf="@+id/et_password"
        android:layout_marginEnd="@dimen/_20sdp"
        android:layout_marginStart="@dimen/_20sdp"
        android:layout_marginTop="@dimen/_30sdp"
        android:paddingLeft="5dp"
        />

        <ProgressBar
            android:id="@+id/pb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minHeight="50dp"
            android:minWidth="50dp"
            android:gravity="center"
            android:indeterminate="true"
            android:elevation="10dp"
            android:visibility="gone"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="@color/orange"
            />

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
Set your XML file like this (make changes as per your need)

    <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical"
    android:paddingTop="20dp"
    android:elevation="5dp"
    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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_welcome"
        android:layout_marginRight="40dp"
        android:layout_marginStart="20dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:maxLines="2"
        style="App Wep"
        android:text="Welcome to the World \nof PACKR" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:id="@+id/tv_continue"
        android:visibility="gone"
        app:layout_constraintTop_toBottomOf="@+id/tv_welcome"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="20dp"
        android:layout_marginStart="20dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:text="Sign in to continue" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginTop="20dp"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        app:layout_constraintTop_toBottomOf="@+id/tv_continue"
        android:id="@+id/phone_layout"
        android:orientation="horizontal">

        <com.hbb20.CountryCodePicker
            android:layout_marginEnd="10dp"
            android:layout_width="0dp"
            android:layout_weight="0.4"
            android:textSize="12dp"
            android:id="@+id/countryCode"
            android:layout_height="match_parent" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="0.6"
            android:hint="Phone Number"
            android:inputType="number"
            android:id="@+id/et_phone"
            android:maxLength="11"
            android:padding="10dp"
            android:drawablePadding="10dp"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <EditText
        android:layout_width="match_parent"
        android:layout_marginTop="10dp"
        android:hint="Password"
        android:singleLine="true"
        android:drawablePadding="10dp"
        android:layout_marginEnd="20dp"
        android:layout_marginStart="20dp"
        app:layout_constraintTop_toBottomOf="@+id/phone_layout"
        app:layout_constraintLeft_toLeftOf="parent"
        android:padding="10dp"
        android:inputType="textPassword"
        android:id="@+id/et_password"
        android:layout_height="wrap_content" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:id="@+id/forgot_layout"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="15dp"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/img_"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintRight_toRightOf="@+id/forgot_pass"
            app:layout_constraintLeft_toLeftOf="@+id/forgot_pass"
            android:layout_marginEnd="20dp"
            android:layout_marginStart="20dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAllCaps="false"
            android:layout_marginEnd="20dp"
            android:layout_marginStart="20dp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/img_"
            android:layout_gravity="right"
            android:padding="5dp"
            android:id="@+id/forgot_pass"
            android:layout_marginTop="8dp" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_signin"
        android:text="Login"
        app:layout_constraintTop_toBottomOf="@+id/et_password"
        android:layout_marginEnd="20dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="30dp"
        android:paddingLeft="5dp"
        />

    <ProgressBar
        android:id="@+id/pb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="50dp"
        android:minWidth="50dp"
        android:gravity="center"
        android:indeterminate="true"
        android:elevation="10dp"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:indeterminateTintMode="src_atop"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

And Manifest as this(Example)

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Remove WindowSoftInput mode.


Title: How to transform given dataset in python?

Body:
            1           0.0   6.400000000
            2   6.400000000          27.0
            2          27.0  27.100000000
            2  27.100000000  27.400000000
            2  27.400000000  27.700000000
            2  27.700000000  30.600000000
            1  30.600000000          31.0
            1          31.0  36.600000000
            1  36.600000000  36.900000000
            1  36.900000000  37.100000000
            1  37.100000000  37.100000000
            1  37.100000000  37.300000000
            1  37.300000000  37.800000000
            1  37.800000000  38.900000000
            1  38.900000000  39.200000000
            1  39.200000000  39.300000000
            1  39.300000000  39.500000000
            1  39.500000000  39.700000000
            2  39.700000000  42.600000000
            2  42.600000000  42.600000000
            2  42.600000000  42.800000000
            1  42.800000000  44.900000000
            1  44.900000000  45.600000000
            2  45.600000000          51.0
            1          51.0  51.800000000

            1           0.0   6.400000000
            2   6.400000000  30.600000000
            1  30.600000000  39.500000000
... so on

I want to transform my data in the above format. I tried this with groupBy min and max for column but it seems like it doesn't give me the desirable results.

Body:
From your expected result, it appears that each "group" is based on contiguous id values.  For this, you can use the compare-cumsum-groupby pattern, and then use agg to get the min and max values.

# Sample data.
df = pd.DataFrame(
    {'id': [1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 1],
     'A': [0.0, 6.4, 27.0, 27.1, 27.4, 27.7, 30.6, 31.0, 36.6, 36.9, 37.1, 37.1, 37.3, 37.8, 38.9, 39.2, 39.3, 39.5, 39.7, 42.6, 42.6, 42.8, 44.9, 45.6, 51.0],
     'B': [6.4, 27.0, 27.1, 27.4, 27.7, 30.6, 31.0, 36.6, 36.9, 37.1, 37.1, 37.3, 37.8, 38.9, 39.2, 39.3, 39.5, 39.7, 42.6, 42.6, 42.8, 44.9, 45.6, 51.0, 51.8]}
)

# Solution.
>>> (df
     .groupby(df['id'].ne(df['id'].shift()).cumsum())
     .agg({'id': 'first', 'A': 'min', 'B': 'max'})
     .set_index('id'))
       A     B
id
1    0.0   6.4
2    6.4  30.6
1   30.6  39.7
2   39.7  42.8
1   42.8  45.6
2   45.6  51.0
1   51.0  51.8


问:
refactoring 2 closely coupled methods
Ok so I'm making a mockup of a distributed system.
each instance of  mClass (object) is used by 1 thread. Mutable data can't be passed between mClass objects
This is a example of code analogous to what I have:

```<code>type mClass (mID:id)=
    member this.ID=mID

    let resolve : id->mClass  =... //This function turns IDs into the objects they represnt
    ...
    let managementInfo = ref Some mutableData

    //this should only ever be called by the GiveControl method.
    private member this.TakeControl (frozenData) =
        let defrostedData = ... //a variable that works out the unfrozen version of the frozenData
        managementInfo := Some defrostedData

    ///This is a helper that ensure that when ever someone else is told to take control
    ///that all my internal data and any functions i need to call to tell others are done
    ///And convert the data a nonmutable form
    ///(Mutable data can not be tranfered between different instances of of mClass (objects),
    ///as this is a mockup of a distributed system, where the instances of mClass can't
    ///@param: nID this ID of the object we are giving control to
    ///@param: callbacks: a list of functions to call to tell other objects i've given control
    private member this.GiveControl nID (callbacks: list<id->unit>) =
        let updateInternalData = ... //A function to upate my internal state
        updateInternalData;
        ignore (List.map (fun f-> f nID) callbacks);
        let freezeData data= ... //a function make our mutableData into nonmutable data
        let frozenData = (!managemenInfo).Value|>freezeData
        managemenInfo:=None;
        (nID|>resolve).TakeControl (frozenData)

    ...
</code>```

private member this.GiveControl was originally declared:
let giveControl
but it made the compiler complain about mis-declaring a new type, until i changed it to a private method.

The question is, how can I re factor this code,
to merge the two methods into one. (or atleast make GiveControl only callable from within this object (real private as it were) and TakeControl only callable from GiveControl)

答:
As you said, you orinally had giveControl as a let, this is excactly what you need to do.
things delare with a let are truely private values. they can't be accessed from outside your object.

The it is a requirement of classes in F# that lets are delared before members.
also F# is not single passover for class methods,
thus your let can reference any method you need.

type mClass (mID:id)=
    member this.ID=mID

```<code>let resolve : id->mClass  =... //This function turns IDs into the objects they represnt
...
let managementInfo = ref Some mutableData
let giveControl nID (callbacks: list<id->unit>) =
...

private member this.TakeControl (frozenData) =
    ...
</code>```

This doesn't fix your second problem, however

Title: refactoring 2 closely coupled methods

Body:
Ok so I'm making a mockup of a distributed system.
each instance of  mClass (object) is used by 1 thread. Mutable data can't be passed between mClass objects
This is a example of code analogous to what I have:

type mClass (mID:id)=
    member this.ID=mID

    let resolve : id->mClass  =... //This function turns IDs into the objects they represnt
    ...
    let managementInfo = ref Some mutableData

    //this should only ever be called by the GiveControl method.
    private member this.TakeControl (frozenData) =
        let defrostedData = ... //a variable that works out the unfrozen version of the frozenData
        managementInfo := Some defrostedData

    ///This is a helper that ensure that when ever someone else is told to take control
    ///that all my internal data and any functions i need to call to tell others are done
    ///And convert the data a nonmutable form
    ///(Mutable data can not be tranfered between different instances of of mClass (objects),
    ///as this is a mockup of a distributed system, where the instances of mClass can't
    ///@param: nID this ID of the object we are giving control to
    ///@param: callbacks: a list of functions to call to tell other objects i've given control
    private member this.GiveControl nID (callbacks: list<id->unit>) =
        let updateInternalData = ... //A function to upate my internal state
        updateInternalData;
        ignore (List.map (fun f-> f nID) callbacks);
        let freezeData data= ... //a function make our mutableData into nonmutable data
        let frozenData = (!managemenInfo).Value|>freezeData
        managemenInfo:=None;
        (nID|>resolve).TakeControl (frozenData)

    ...

private member this.GiveControl was originally declared:
let giveControl
but it made the compiler complain about mis-declaring a new type, until i changed it to a private method.

The question is, how can I re factor this code,
to merge the two methods into one. (or atleast make GiveControl only callable from within this object (real private as it were) and TakeControl only callable from GiveControl)

Body:
As you said, you orinally had giveControl as a let, this is excactly what you need to do.
things delare with a let are truely private values. they can't be accessed from outside your object.

The it is a requirement of classes in F# that lets are delared before members.
also F# is not single passover for class methods,
thus your let can reference any method you need.

type mClass (mID:id)=
    member this.ID=mID

let resolve : id->mClass  =... //This function turns IDs into the objects they represnt
...
let managementInfo = ref Some mutableData
let giveControl nID (callbacks: list<id->unit>) =
...

private member this.TakeControl (frozenData) =
    ...

This doesn't fix your second problem, however


问:
Child component height and width is not applying in angular
I am not able to apply height/width to a child component in angular. Please have a look and let me know where and what I am doing wrong

app.component.html

```<code><app-child [width]="10" [height]="10"></app-child>
</code>```

.child.ts

```<code>import { Component, OnInit, Input, ViewEncapsulation, Renderer2, ElementRef } from '@angular/core';

@Component({
  encapsulation: ViewEncapsulation.None,
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor(private renderer: Renderer2, private elRef: ElementRef) { }

  @Input() width
  @Input() height

  ngAfterViewInit() {
    this.renderer.setStyle(this.elRef.nativeElement, 'height', this.height + "%");
    this.renderer.setStyle(this.elRef.nativeElement, 'width', this.width + "%");
  }
}
</code>```

.child.html

```<code><div class="wrapper" [style.width.%]="width" [style.height.%]="height">
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

Issues :
</code>```

app-child component still takes full width and hight it should be 10%
div inside app-child taking correct width but height is still 100%

Example link

https://stackblitz.com/edit/angular-qgobau

答:
This link will help to you : Height percentage not working in CSS

you need to add below code in your child component css

```<code>html, body {
   height: 100%;
}
</code>```

Body:
I am not able to apply height/width to a child component in angular. Please have a look and let me know where and what I am doing wrong

app.component.html

<app-child [width]="10" [height]="10"></app-child>

.child.ts

import { Component, OnInit, Input, ViewEncapsulation, Renderer2, ElementRef } from '@angular/core';

@Component({
  encapsulation: ViewEncapsulation.None,
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor(private renderer: Renderer2, private elRef: ElementRef) { }

  @Input() width
  @Input() height

  ngAfterViewInit() {
    this.renderer.setStyle(this.elRef.nativeElement, 'height', this.height + "%");
    this.renderer.setStyle(this.elRef.nativeElement, 'width', this.width + "%");
  }
}

.child.html

 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Issues :

app-child component still takes full width and hight it should be 10%
div inside app-child taking correct width but height is still 100%

Example link

https://stackblitz.com/edit/angular-qgobau

Body:
This link will help to you : Height percentage not working in CSS

you need to add below code in your child component css

html, body {
   height: 100%;
}


问:
(Numpy) Index list to boolean array
Input:

array length (Integer)

indexes (Set or List)

Output:

A boolean numpy array that has a value 1 for the indexes 0 for the others.

Example:

Input: array_length=10, indexes={2,5,6}

Output:

```<code>[0,0,1,0,0,1,1,0,0,0]
</code>```

Here is a my simple implementation:

```<code>def indexes2booleanvec(size, indexes):
    v = numpy.zeros(size)
    for index in indexes:
        v[index] = 1.0
    return v
</code>```

Is there more elegant way to implement this?

答:
Another way to do it (in one line):

```<code>np.isin(np.arange(array_length), indexes)
</code>```

However this is slower than Zero's solution.

Title: (Numpy) Index list to boolean array

Body:
Input:

array length (Integer)

indexes (Set or List)

Output:

A boolean numpy array that has a value 1 for the indexes 0 for the others.

Example:

Input: array_length=10, indexes={2,5,6}

Output:

[0,0,1,0,0,1,1,0,0,0]

Here is a my simple implementation:

def indexes2booleanvec(size, indexes):
    v = numpy.zeros(size)
    for index in indexes:
        v[index] = 1.0
    return v

Is there more elegant way to implement this?

Body:
Another way to do it (in one line):

np.isin(np.arange(array_length), indexes)

However this is slower than Zero's solution.


问:
PosgreSQL - loop syntax
I have the following loop (simplified for an example):

```<code>DO $$
  DECLARE
    l record;

  BEGIN
    FOR l IN SELECT id, country_id FROM logo LOOP
      WITH cs AS (
        INSERT INTO logo_settings (targeted) VALUES (true)
        RETURNING id
      )
      INSERT INTO logo_settings_targeted (logo_settings_id, country_id)
      VALUES
      ( (SELECT id FROM cs),
        logo.country_id,
      );
    END LOOP;
  END;
END $$;
</code>```

The body of a loop works fine. But if I wrap it into a loop (I would like to make records for all records from logo table) - it shows an error saying:

```<code>ERROR: syntax error at or near "END"
  Position: 712

END;
^
</code>```

meaning the last EnND before END $$; which does not give much sense to me. I do not know what to fix to make it running. Any hints?

答:
There is one end to many. end loop closes the loop body:

```<code>DO $$
  DECLARE
    l record;

  BEGIN
    FOR l IN SELECT id, country_id FROM logo LOOP
      WITH cs AS (
        INSERT INTO logo_settings (targeted) VALUES (true)
        RETURNING id
      )
      INSERT INTO logo_settings_targeted (logo_settings_id, country_id)
      VALUES
      ( (SELECT id FROM cs),
        logo.country_id,
      );
    END LOOP;
  END $$;
</code>```

Title: PosgreSQL - loop syntax

Body:
I have the following loop (simplified for an example):

DO $$
  DECLARE
    l record;

  BEGIN
    FOR l IN SELECT id, country_id FROM logo LOOP
      WITH cs AS (
        INSERT INTO logo_settings (targeted) VALUES (true)
        RETURNING id
      )
      INSERT INTO logo_settings_targeted (logo_settings_id, country_id)
      VALUES
      ( (SELECT id FROM cs),
        logo.country_id,
      );
    END LOOP;
  END;
END $$;

The body of a loop works fine. But if I wrap it into a loop (I would like to make records for all records from logo table) - it shows an error saying:

ERROR: syntax error at or near "END"
  Position: 712

END;
^

meaning the last EnND before END $$; which does not give much sense to me. I do not know what to fix to make it running. Any hints?

Body:
There is one end to many. end loop closes the loop body:

DO $$
  DECLARE
    l record;

  BEGIN
    FOR l IN SELECT id, country_id FROM logo LOOP
      WITH cs AS (
        INSERT INTO logo_settings (targeted) VALUES (true)
        RETURNING id
      )
      INSERT INTO logo_settings_targeted (logo_settings_id, country_id)
      VALUES
      ( (SELECT id FROM cs),
        logo.country_id,
      );
    END LOOP;
  END $$;


问:
What is the best way to share files between Xen VM's?
Is there some built-in way to share files between Xen guests?  I don't currently need to share the actual images, just some data files.</p>

答: You can also try glusterfs or lustre to share files between Xen guests.</p>

OwnerDisplayName: Otto

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Otto

OwnerDisplayName: Waltharius


问:
Javascript Age count from Date of Birth
I'm passing my calendar selected date of birth to following JS function for calculating Age:

```<code>var DOBmdy = date.split("-");
    Bdate = new Date(DOBmdy[2],DOBmdy[0]-1,DOBmdy[1]);
    BDateArr = (''+Bdate).split(' ');
    //document.getElementById('DOW').value = BDateArr[0];
    Cdate = new Date;
    CDateArr = (''+Cdate).split(" ");
    Age = CDateArr[3] - BDateArr[3];
</code>```

Now, lets say, input age is: 2nd Aug 1983 and age count comes: 28, while as August month has not been passed yet, i want to show the current age of 27 and not 28

Any idea, how can i write that logic, to count age 27 perfectly with my JS function.

Thanks !

答:
I just had to write a function to do this and thought'd I'd share.

This is accurate from a human point of view! None of that crazy 365.2425 stuff.

```<code>var ageCheck = function(yy, mm, dd) {
    // validate input
    yy = parseInt(yy,10);
    mm = parseInt(mm,10);
    dd = parseInt(dd,10);
    if(isNaN(dd) || isNaN(mm) || isNaN(yy)) { return 0; }
    if((dd < 1 || dd > 31) || (mm < 1 || mm > 12)) { return 0; }

    // change human inputted month to javascript equivalent
    mm = mm - 1;

    // get today's date
    var today = new Date();
    var t_dd = today.getDate();
    var t_mm = today.getMonth();
    var t_yy = today.getFullYear();

    // We are using last two digits, so make a guess of the century
    if(yy == 0) { yy = "00"; }
    else if(yy < 9) { yy = "0"+yy; }
    yy = (today.getFullYear() < "20"+yy ? "19"+yy : "20"+yy);

    // Work out the age!
    var age = t_yy - yy - 1; // Starting point
    if( mm < t_mm ) { age++;} // If it's past their birth month
    if( mm == t_mm && dd <= t_dd) { age++; } // If it's past their birth day

    return age;
}
</code>```

Title: Javascript Age count from Date of Birth

Body:
I'm passing my calendar selected date of birth to following JS function for calculating Age:

var DOBmdy = date.split("-");
    Bdate = new Date(DOBmdy[2],DOBmdy[0]-1,DOBmdy[1]);
    BDateArr = (''+Bdate).split(' ');
    //document.getElementById('DOW').value = BDateArr[0];
    Cdate = new Date;
    CDateArr = (''+Cdate).split(" ");
    Age = CDateArr[3] - BDateArr[3];

Now, lets say, input age is: 2nd Aug 1983 and age count comes: 28, while as August month has not been passed yet, i want to show the current age of 27 and not 28

Any idea, how can i write that logic, to count age 27 perfectly with my JS function.

Thanks !

Body:
I just had to write a function to do this and thought'd I'd share.

This is accurate from a human point of view! None of that crazy 365.2425 stuff.

var ageCheck = function(yy, mm, dd) {
    // validate input
    yy = parseInt(yy,10);
    mm = parseInt(mm,10);
    dd = parseInt(dd,10);
    if(isNaN(dd) || isNaN(mm) || isNaN(yy)) { return 0; }
    if((dd < 1 || dd > 31) || (mm < 1 || mm > 12)) { return 0; }

    // change human inputted month to javascript equivalent
    mm = mm - 1;

    // get today's date
    var today = new Date();
    var t_dd = today.getDate();
    var t_mm = today.getMonth();
    var t_yy = today.getFullYear();

    // We are using last two digits, so make a guess of the century
    if(yy == 0) { yy = "00"; }
    else if(yy < 9) { yy = "0"+yy; }
    yy = (today.getFullYear() < "20"+yy ? "19"+yy : "20"+yy);

    // Work out the age!
    var age = t_yy - yy - 1; // Starting point
    if( mm < t_mm ) { age++;} // If it's past their birth month
    if( mm == t_mm && dd <= t_dd) { age++; } // If it's past their birth day

    return age;
}


问:
What is inline-view that can be used with LATERAL in Snowflake (not subquery, not table function)?
The Snowflake documentation for Lateral Join mention that in

```<code>SELECT ... FROM <left_hand_table_expression>, LATERAL ( <in_line_view> )
</code>```

The in_line_view could be:

An in-line view (a view defined within the statement, and valid only for the duration of the statement

A subquery select * from d, lateral (select * from e where e.id = d.id)

A table function (either a built-in function such as FLATTEN or a user-defined table function(UDFT)) select * from e, lateral flatten(input => e.x)

I already have used subqueries and table functions in the LATERAL(...) but I wonder what is the the other kind of <in_line_view> (and how it is different from a subquery).

答:
One significant type of inline view is the Common Table Expression, or CTE.

```<code>WITH my_in_line_view AS (SELECT ...)
SELECT * FROM my_in_line_view
</code>```

One major point in having all these different way of expressing similar queries is code clarity.

The SQL optimizer may treat all versions as similar, but when reading your code, it may be much simpler to understand if you use well thought out CTEs.  Or maybe not, it can add to the confusion.

Just like natural language, you have many ways of saying the same thing, but some ways are more easily understood.

Body:
The Snowflake documentation for Lateral Join mention that in

SELECT ... FROM <left_hand_table_expression>, LATERAL ( <in_line_view> )

The in_line_view could be:

An in-line view (a view defined within the statement, and valid only for the duration of the statement

A subquery select * from d, lateral (select * from e where e.id = d.id)

A table function (either a built-in function such as FLATTEN or a user-defined table function(UDFT)) select * from e, lateral flatten(input => e.x)

I already have used subqueries and table functions in the LATERAL(...) but I wonder what is the the other kind of <in_line_view> (and how it is different from a subquery).

Body:
One significant type of inline view is the Common Table Expression, or CTE.

WITH my_in_line_view AS (SELECT ...)
SELECT * FROM my_in_line_view

One major point in having all these different way of expressing similar queries is code clarity.

The SQL optimizer may treat all versions as similar, but when reading your code, it may be much simpler to understand if you use well thought out CTEs.  Or maybe not, it can add to the confusion.

Just like natural language, you have many ways of saying the same thing, but some ways are more easily understood.


问:
List<> to MemoryStream Conversion
Hi I am new to C# and I want to convert List<> type to MemoryStream:

```<code>List<String> listType=new List<String>;
MemoryStream ms=new MemoryStream();
</code>```

and If I am doing like this-

```<code>MemoryStream listToStream=(MemoryStream)listType;
</code>```

it is showing as suspicious cast.
please help!!

答:
If serialization is what you want, then is it to xml or json?

They are pretty much the same in terms of performance: Json and Xml serialization, what is better performance?

A excellent example is the following:http://www.daveoncsharp.com/2009/07/xml-serialization-of-collections/

```<code>using System;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace XMLSerialization
{
    [XmlRoot("CompanyEmployees")]
    public class EmployeeList
    {
        [XmlArray("EmployeeListing")]

        [XmlArrayItem("Employee", typeof(Employee))]
        public List employeeList;

        // Constructor
        public EmployeeList()
        {
            employeeList = new List();
        }

        public void AddEmployee(Employee employee)
        {
            employeeList.Add(employee);
        }
    }
}
</code>```

And actual serialization

```<code>private void SerializeList()
{
    // Create an instance of the EmployeeList class
    EmployeeList employeeList = new EmployeeList();

    // Create a few instances of the Employee class
    Employee emp1 = new Employee();
    emp1.Name = "John";
    emp1.Surname = "Smith";
    emp1.DateOfBirth = new DateTime(1980, 10, 08);
    emp1.Sex = Employee.EmployeeSex.Male;
    emp1.Position = "Software Engineer";

    Employee emp2 = new Employee();
    emp2.Name = "David";
    emp2.Surname = "McGregor";
    emp2.DateOfBirth = new DateTime(1973, 01, 13);
    emp2.Sex = Employee.EmployeeSex.Male;
    emp2.Position = "Product Manager";

    Employee emp3 = new Employee();
    emp3.Name = "Sarah";
    emp3.Surname = "Crow";
    emp3.DateOfBirth = new DateTime(1983, 11, 23);
    emp3.Sex = Employee.EmployeeSex.Female;
    emp3.Position = "Software Tester";

    // Add the employees to the list
    employeeList.AddEmployee(emp1);
    employeeList.AddEmployee(emp2);
    employeeList.AddEmployee(emp3);

    // Create an instance of System.Xml.Serialization.XmlSerializer
    XmlSerializer serializer = new XmlSerializer(employeeList.GetType());

    // Create an instance of System.IO.TextWriter
    // to save the serialized object to disk
    TextWriter textWriter = new StreamWriter("C:\\Employee\\employeeList.xml");

    // Serialize the employeeList object
    serializer.Serialize(textWriter, employeeList);

    // Close the TextWriter
    textWriter.Close();
}
</code>```

Title: List<> to MemoryStream Conversion

Body:
Hi I am new to C# and I want to convert List<> type to MemoryStream:

List<String> listType=new List<String>;
MemoryStream ms=new MemoryStream();

and If I am doing like this-

MemoryStream listToStream=(MemoryStream)listType;

it is showing as suspicious cast.
please help!!

Body:
If serialization is what you want, then is it to xml or json?

They are pretty much the same in terms of performance: Json and Xml serialization, what is better performance?

A excellent example is the following:http://www.daveoncsharp.com/2009/07/xml-serialization-of-collections/

using System;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace XMLSerialization
{
    [XmlRoot("CompanyEmployees")]
    public class EmployeeList
    {
        [XmlArray("EmployeeListing")]

        [XmlArrayItem("Employee", typeof(Employee))]
        public List employeeList;

        // Constructor
        public EmployeeList()
        {
            employeeList = new List();
        }

        public void AddEmployee(Employee employee)
        {
            employeeList.Add(employee);
        }
    }
}

And actual serialization

private void SerializeList()
{
    // Create an instance of the EmployeeList class
    EmployeeList employeeList = new EmployeeList();

    // Create a few instances of the Employee class
    Employee emp1 = new Employee();
    emp1.Name = "John";
    emp1.Surname = "Smith";
    emp1.DateOfBirth = new DateTime(1980, 10, 08);
    emp1.Sex = Employee.EmployeeSex.Male;
    emp1.Position = "Software Engineer";

    Employee emp2 = new Employee();
    emp2.Name = "David";
    emp2.Surname = "McGregor";
    emp2.DateOfBirth = new DateTime(1973, 01, 13);
    emp2.Sex = Employee.EmployeeSex.Male;
    emp2.Position = "Product Manager";

    Employee emp3 = new Employee();
    emp3.Name = "Sarah";
    emp3.Surname = "Crow";
    emp3.DateOfBirth = new DateTime(1983, 11, 23);
    emp3.Sex = Employee.EmployeeSex.Female;
    emp3.Position = "Software Tester";

    // Add the employees to the list
    employeeList.AddEmployee(emp1);
    employeeList.AddEmployee(emp2);
    employeeList.AddEmployee(emp3);

    // Create an instance of System.Xml.Serialization.XmlSerializer
    XmlSerializer serializer = new XmlSerializer(employeeList.GetType());

    // Create an instance of System.IO.TextWriter
    // to save the serialized object to disk
    TextWriter textWriter = new StreamWriter("C:\\Employee\\employeeList.xml");

    // Serialize the employeeList object
    serializer.Serialize(textWriter, employeeList);

    // Close the TextWriter
    textWriter.Close();
}


问:
Show scrollbar while resizing the window
I want to show windows scrollbar when user resizes the window less than a specified width. For that i used min-width but that doesnt work with IE6. Is there any way i can do that using javascript or jquery</p>

答:
try this if it will solve the problem just replace height and width in the css</p>

```<code>div.scroll
{
background-color:#00FFFF;
width:100px;
height:100px;
overflow:scroll;
}
</code>```

Body:
try this if it will solve the problem just replace height and width in the css

div.scroll
{
background-color:#00FFFF;
width:100px;
height:100px;
overflow:scroll;
}


问:
How to set fastlane credentials
I would like to set environmental variables i.e username using a command I tried

```<code>fastlane fastlane-credentials add --username me@myappleaccount.com
</code>```

but I still get a prompt :

```<code>[10:30:31]: To not be asked about this value, you can specify it using 'username'
Your Apple ID Username:
</code>```

I work in a team of developers and I would like to have an ability to for every developer to set there own username without committing the files with different username. Is there a command for that.

答:
I have no experiences using the command you mentioned, but we use dotenv files for all kind of variables and those work like a charm. Some of them are under version control and some are developer specific.

How to use dotenv files is described here. We use both the automatically loaded dotenv files and some manually loaded ones.

Title: How to set fastlane credentials

Body:
I would like to set environmental variables i.e username using a command I tried

fastlane fastlane-credentials add --username me@myappleaccount.com

but I still get a prompt :

[10:30:31]: To not be asked about this value, you can specify it using 'username'
Your Apple ID Username:

I work in a team of developers and I would like to have an ability to for every developer to set there own username without committing the files with different username. Is there a command for that.


问:
How do I extract a certain amount of lines after a pattern in perl?
Lets say I have a text file:

```<code>Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10
</code>```

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

```<code>Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9
</code>```

So far all I have is code to find the target and print it out:

```<code>use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}
</code>```

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

答:
Other variation of previously posted code snippet

```<code>use strict;
use warnings;

my $how_many = 3;
my $pattern = qr/Target Name\d/;

while(<DATA>) {
    next unless /$pattern/;
    print;
    print scalar <DATA> for 1..$how_many;
    print "\n";
}

__DATA__
Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10
</code>```

Output

```<code>Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9
</code>```

Body:
Lets say I have a text file:

Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9

So far all I have is code to find the target and print it out:

use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

Body:
Other variation of previously posted code snippet

use strict;
use warnings;

my $how_many = 3;
my $pattern = qr/Target Name\d/;

while(<DATA>) {
    next unless /$pattern/;
    print;
    print scalar <DATA> for 1..$how_many;
    print "\n";
}

__DATA__
Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10

Output

Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9


问:
Getting difference between virtual address and Offset in an ELF file
readelf -S of a particular binary gives the following output

```<code>Section Headers:
  [Nr] Name              Type             Address           Offset
       Size              EntSize          Flags  Link  Info  Align
  [ 0]                   NULL             0000000000000000  00000000
       0000000000000000  0000000000000000           0     0     0
  [ 1] .interp           PROGBITS         0000000000400238  00000238
       000000000000001c  0000000000000000   A       0     0     1
  [ 2] .note.ABI-tag     NOTE             0000000000400254  00000254
       0000000000000020  0000000000000000   A       0     0     4
  [ 3] .hash             HASH             0000000000400278  00000278
       0000000000000a7c  0000000000000004   A       4     0     8
  [ 4] .dynsym           DYNSYM           0000000000400cf8  00000cf8
.
.
.
</code>```

Difference between virtual address and offset of first section .interp is 0x400000. I am curious as to:

how is this calculated?

Is there a programmatic way of determining this?

答:
how is this calculated?

You just calculated it yourself: 0x400238 - 0x238 == 0x400000. Your question is probably "why is this particular address selected?".

This is the default link-at address for Linux x86_64 position dependent binaries. You can change that address with -Ttext=... linker flag. The default is different for ix86 (32-bit) binaries: it's 0x8048000.

I am not sure why these particular defaults were chosen.

Is there a programmatic way of determining this?

Sure: read the Elf64_Ehdr from the start of the file. It will tell you offset to the start of program headers (.e_phoff). Seek to that offset, and read Elf64_Phdrs. Now iterate over them, and their .p_vaddr and .p_offset will have the same values.

P.S. You are looking at program sections which are not used and are not guaranteed to be present in a fully-linked binary. You should be looking at program segments instead. Use readelf -Wl a.out to examine them.

Body:
readelf -S of a particular binary gives the following output

Section Headers:
  [Nr] Name              Type             Address           Offset
       Size              EntSize          Flags  Link  Info  Align
  [ 0]                   NULL             0000000000000000  00000000
       0000000000000000  0000000000000000           0     0     0
  [ 1] .interp           PROGBITS         0000000000400238  00000238
       000000000000001c  0000000000000000   A       0     0     1
  [ 2] .note.ABI-tag     NOTE             0000000000400254  00000254
       0000000000000020  0000000000000000   A       0     0     4
  [ 3] .hash             HASH             0000000000400278  00000278
       0000000000000a7c  0000000000000004   A       4     0     8
  [ 4] .dynsym           DYNSYM           0000000000400cf8  00000cf8
.
.
.

Difference between virtual address and offset of first section .interp is 0x400000. I am curious as to:

how is this calculated?

Is there a programmatic way of determining this?


问:
How to clear a form?
For example I have a form like this:

```<code><form method='post' action='someaction.php' name='myform'>

<input type='text' name='text1'>
<input type='text' name='text2'>

<input type='checkbox' name="check1">Check Me

<textarea rows="2" cols="20" name='textarea1'></textarea>

<select name='select1'>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<input type='reset' value='Reset' name='reset'>
<input type='submit' value='Submit' name='submit'>

</form>
</code>```

When I press Reset it empties all fields. But if I populate some fields using URL params and then press Reset, it only empties fields which I enter after form reload.

How can I empty all fields whether some fields are already populated at the time of form load.

答:
As others pointed out, I think you should reconsider the need to blank the form.
But, if you really need that functionality, this is one way to do it:

Plain Javascript:

```<code>function resetForm(form) {
    // clearing inputs
    var inputs = form.getElementsByTagName('input');
    for (var i = 0; i<inputs.length; i++) {
        switch (inputs[i].type) {
            // case 'hidden':
            case 'text':
                inputs[i].value = '';
                break;
            case 'radio':
            case 'checkbox':
                inputs[i].checked = false;
        }
    }

    // clearing selects
    var selects = form.getElementsByTagName('select');
    for (var i = 0; i<selects.length; i++)
        selects[i].selectedIndex = 0;

    // clearing textarea
    var text= form.getElementsByTagName('textarea');
    for (var i = 0; i<text.length; i++)
        text[i].innerHTML= '';

    return false;
}
</code>```

Note that I commented out the case in which I clear the hidden inputs. Most of the time, this is not necessary.

For this to work, you need to call the function from the onclick handler of a button (or some other way), e.g. like this:

```<code><input type='reset' value='Reset' name='reset' onclick="return resetForm(this.form);">
</code>```

You can test it all here on jsFiddle.

If you use jQuery in your project, you can do this with much less code (and no need to change the HTML):

```<code>jQuery(function($) { // onDomReady

    // reset handler that clears the form
    $('form[name="myform"] input:reset').click(function () {
        $('form[name="myform"]')
            .find(':radio, :checkbox').removeAttr('checked').end()
            .find('textarea, :text, select').val('')

        return false;
    });

});
</code>```

Also, note that I do not clear the values of hidden inputs, check-boxes and radio buttons.

Play with this here.

Title: How to clear a form?

Body:
For example I have a form like this:

<form method='post' action='someaction.php' name='myform'>

<input type='text' name='text1'>
<input type='text' name='text2'>

<input type='checkbox' name="check1">Check Me

<textarea rows="2" cols="20" name='textarea1'></textarea>

<select name='select1'>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<input type='reset' value='Reset' name='reset'>
<input type='submit' value='Submit' name='submit'>

</form>

When I press Reset it empties all fields. But if I populate some fields using URL params and then press Reset, it only empties fields which I enter after form reload.

How can I empty all fields whether some fields are already populated at the time of form load.

Body:
As others pointed out, I think you should reconsider the need to blank the form.
But, if you really need that functionality, this is one way to do it:

Plain Javascript:

function resetForm(form) {
    // clearing inputs
    var inputs = form.getElementsByTagName('input');
    for (var i = 0; i<inputs.length; i++) {
        switch (inputs[i].type) {
            // case 'hidden':
            case 'text':
                inputs[i].value = '';
                break;
            case 'radio':
            case 'checkbox':
                inputs[i].checked = false;
        }
    }

    // clearing selects
    var selects = form.getElementsByTagName('select');
    for (var i = 0; i<selects.length; i++)
        selects[i].selectedIndex = 0;

    // clearing textarea
    var text= form.getElementsByTagName('textarea');
    for (var i = 0; i<text.length; i++)
        text[i].innerHTML= '';

    return false;
}

Note that I commented out the case in which I clear the hidden inputs. Most of the time, this is not necessary.

For this to work, you need to call the function from the onclick handler of a button (or some other way), e.g. like this:

<input type='reset' value='Reset' name='reset' onclick="return resetForm(this.form);">

You can test it all here on jsFiddle.

If you use jQuery in your project, you can do this with much less code (and no need to change the HTML):

jQuery(function($) { // onDomReady

    // reset handler that clears the form
    $('form[name="myform"] input:reset').click(function () {
        $('form[name="myform"]')
            .find(':radio, :checkbox').removeAttr('checked').end()
            .find('textarea, :text, select').val('')

        return false;
    });

});

Also, note that I do not clear the values of hidden inputs, check-boxes and radio buttons.

Play with this here.


问:
Menu Visibility and MS Edge hack for tab accessable menu
I have a css nav menu that uses focus-within to allow tabbing through the Main nav for handicap accessibility. Edge doesn't support focus-within or allow tabbing into hidden items. I hope to use jquery to change the nested ul visibility as we tab through the nav links, I can't figure out how to change the ul back to hidden when the tab focus moves off of that particular ul's contents. So tab on to something with a ul that is hidden, the UL becomes visible, allowing tabbing in to it's contents. Then after tabbing through all that UL's contents, tab focus moves out of the ul to the next link and the UL is changed back to hidden and repeat for all UL's inside the nav. I don't know much jQuery just seemed like the right way to go until edge supports focus-within. The fiddle is below, Thanks for any help while I continue to attempt a solution.

TLDR; do you know the jquery syntax to change a ul to visibilty:hidden when someone .focusout of the .last item of an individual ul? We don't want to hide the ul when focus has left the ul unless it was the LAST item in the list.

```<code>jQuery(document).ready(function(){
  jQuery('#main  a').focus(function(){
      jQuery(this).next("ul").css('visibility','visible')

  });

});
</code>```

https://jsfiddle.net/joeyjosay/0jxqut74/7/

THIS IS THE SOLUTION I FOUND

```<code>jQuery(document).ready(function(){
  jQuery('#main  a').focus(function(){
      jQuery(this).next("ul").css('visibility','visible')

  });
  jQuery('li ul li:last-child').focusout(function(){
      jQuery(this).parent('ul').css('visibility','hidden')

  });
});
</code>```

答:
I hope to use jquery to change the nested ul visibility as we tab through the nav links

This is not how to make a menu accessible. The problem comes from the fact that if your menu had 15 drop-down items a user would be forced to tab through them all to get to the next 'top level' menu item.

Also how do people access these menu items on a tablet in landscape? As you can't use :hover I would guess you cannot access your sub menus. (nowadays a lot of tablets are 1920*1080 or higher so you can't rely on width CSS in your CSS).

Try the fiddle below (where I added a load more menu items to your example) and select 'main 2' - a total of 19 tab stops are needed to illustrate the frustration automatic drop-downs cause.

jQuery(document).ready(function(){
  jQuery('#main  a').focus(function(){
      jQuery(this).next("ul").css('visibility','visible')

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#main>ul li a{
  display:inline-block;
  float:left;
}
#main li > ul {
  visibility: hidden;

}
#main li:hover > ul{
  visibility: visible;

}</code>```

    main 1

          sub 1

                dubsub1

                dubsub2

                dubsub3

                dubsub4

                dubsub5

                dubsub6

                dubsub7

                dubsub8

                dubsub9

                dubsub10

                dubsub11

                dubsub12

                dubsub13

                dubsub14

                dubsub15

          sub 2

    main 2

          sub 1.1

                dubsub2

          sub 2.1

    main 3

```

What Should you do instead?

Instead you should provide a clickable item in the menu to show the drop-down for keyboard users.

There are several ways to do this. One option is to make the top level menu item for each sub-menu open the sub-menu instead of going to the main page.

If you cannot support this due to site architecture then add a down-arrow next to the top level menu item that when clicked opens the drop-down menu.

A great example to get you started is available at W3C - it shows how to add a separate drop down arrow that is focusable and toggles the sub-menu for keyboard users but also shows the drop-down menu on :hover so it provides the same experience for mouse users as before.

The only thing I would add to the example is if possible make the drop-down target 44px by 44px minimum so that it also complies with minimum touch target sizes according to WCAG. - although this is difficult if you haven't designed for it so just do what you can!

Whichever way you choose the result is that instead of 19 tab stops to reach 'main 2' you instead only have 3 tab stops -> 'main 1' -> 'main 1 drop down' -> 'main 2'.

Final thing, focus-within is great and all but only has 84% browser coverage - see this answer I gave about focus-within for another way to achieve certain things in CSS using the + operator, which may be useful for you as it covers similar theories on how to work with aria-expanded and use it in CSS.

Body:
I have a css nav menu that uses focus-within to allow tabbing through the Main nav for handicap accessibility. Edge doesn't support focus-within or allow tabbing into hidden items. I hope to use jquery to change the nested ul visibility as we tab through the nav links, I can't figure out how to change the ul back to hidden when the tab focus moves off of that particular ul's contents. So tab on to something with a ul that is hidden, the UL becomes visible, allowing tabbing in to it's contents. Then after tabbing through all that UL's contents, tab focus moves out of the ul to the next link and the UL is changed back to hidden and repeat for all UL's inside the nav. I don't know much jQuery just seemed like the right way to go until edge supports focus-within. The fiddle is below, Thanks for any help while I continue to attempt a solution.

TLDR; do you know the jquery syntax to change a ul to visibilty:hidden when someone .focusout of the .last item of an individual ul? We don't want to hide the ul when focus has left the ul unless it was the LAST item in the list.

jQuery(document).ready(function(){
  jQuery('#main  a').focus(function(){
      jQuery(this).next("ul").css('visibility','visible')

  });

});

https://jsfiddle.net/joeyjosay/0jxqut74/7/

THIS IS THE SOLUTION I FOUND

jQuery(document).ready(function(){
  jQuery('#main  a').focus(function(){
      jQuery(this).next("ul").css('visibility','visible')

  });
  jQuery('li ul li:last-child').focusout(function(){
      jQuery(this).parent('ul').css('visibility','hidden')

  });
});

Body:
I hope to use jquery to change the nested ul visibility as we tab through the nav links

This is not how to make a menu accessible. The problem comes from the fact that if your menu had 15 drop-down items a user would be forced to tab through them all to get to the next 'top level' menu item.

Also how do people access these menu items on a tablet in landscape? As you can't use :hover I would guess you cannot access your sub menus. (nowadays a lot of tablets are 1920*1080 or higher so you can't rely on width CSS in your CSS).

Try the fiddle below (where I added a load more menu items to your example) and select 'main 2' - a total of 19 tab stops are needed to illustrate the frustration automatic drop-downs cause.

jQuery(document).ready(function(){
  jQuery('#main  a').focus(function(){
      jQuery(this).next("ul").css('visibility','visible')

  });

});

#main>ul li a{
  display:inline-block;
  float:left;
}
#main li > ul {
  visibility: hidden;

}
#main li:hover > ul{
  visibility: visible;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="main">
  <li>
    <a href="#">main 1</a>
      <ul>
        <li>
          <a href="#">sub 1</a>
            <ul>
              <li>
                <a href="#">dubsub1</a>
              </li>
              <li>
                <a href="#">dubsub2</a>
              </li>
              <li>
                <a href="#">dubsub3</a>
              </li>
              <li>
                <a href="#">dubsub4</a>
              </li>
              <li>
                <a href="#">dubsub5</a>
              </li>
              <li>
                <a href="#">dubsub6</a>
              </li>
              <li>
                <a href="#">dubsub7</a>
              </li>
              <li>
                <a href="#">dubsub8</a>
              </li>
              <li>
                <a href="#">dubsub9</a>
              </li>
              <li>
                <a href="#">dubsub10</a>
              </li>
              <li>
                <a href="#">dubsub11</a>
              </li>
              <li>
                <a href="#">dubsub12</a>
              </li>
              <li>
                <a href="#">dubsub13</a>
              </li>
               <li>
                <a href="#">dubsub14</a>
              </li>
              <li>
                <a href="#">dubsub15</a>
              </li>
            </ul>
          </li>
        <li>
          <a href="#">sub 2</a>
        </li>
      </ul>

  </li>
  <li>
    <a href="#">main 2</a>
      <ul>
        <li>
          <a href="#">sub 1.1</a>
          <ul>
              <li>
                <a href="#">dubsub2</a></li>
            </ul>

          </li>
        <li>
          <a href="#">sub 2.1</a>
        </li>
      </ul>
  </li>
  <li>
    <a href="#">main 3</a>
  </li>
</ul>

What Should you do instead?

Instead you should provide a clickable item in the menu to show the drop-down for keyboard users.

There are several ways to do this. One option is to make the top level menu item for each sub-menu open the sub-menu instead of going to the main page.

If you cannot support this due to site architecture then add a down-arrow next to the top level menu item that when clicked opens the drop-down menu.

A great example to get you started is available at W3C - it shows how to add a separate drop down arrow that is focusable and toggles the sub-menu for keyboard users but also shows the drop-down menu on :hover so it provides the same experience for mouse users as before.

The only thing I would add to the example is if possible make the drop-down target 44px by 44px minimum so that it also complies with minimum touch target sizes according to WCAG. - although this is difficult if you haven't designed for it so just do what you can!

Whichever way you choose the result is that instead of 19 tab stops to reach 'main 2' you instead only have 3 tab stops -> 'main 1' -> 'main 1 drop down' -> 'main 2'.

Final thing, focus-within is great and all but only has 84% browser coverage - see this answer I gave about focus-within for another way to achieve certain things in CSS using the + operator, which may be useful for you as it covers similar theories on how to work with aria-expanded and use it in CSS.


问:
Creating a Master excel file from dynamic CSV output using Python
I am trying to create a repository "Master" excel file from a CSV which will be generated and overwritten every couple of hours. The code below creates a new excel file and writes the content from "combo1.csv" to "master.xlsx". However, whenever the combo1 file is updated, the code basically overwrites the contents in the "master.xlsx" file. I need to append the contents from "combo1" to "Master" without the headers being inserted every time. Can someone help me with this?   </p>

```<code>import pandas as pd

writer = pd.ExcelWriter('master.xlsx', engine='xlsxwriter')
df = pd.read_csv('combo1.csv')
df.to_excel(writer, sheet_name='sheetname')
writer.save()
</code>```

答:
Refer to Append Data at the End of an Excel Sheet section in this medium article:
Using Python Pandas with Excel Sheets

(Credit to Nensi Trambadiya for the article)

Basically you'll have to first read the Excel file and find the number of rows before pushing the new data.

```<code>reader = pd.read_excel(r'master.xlsx')
df.to_excel(writer,index=False,header=False,startrow=len(reader)+1)
</code>```

Body:
I am trying to create a repository "Master" excel file from a CSV which will be generated and overwritten every couple of hours. The code below creates a new excel file and writes the content from "combo1.csv" to "master.xlsx". However, whenever the combo1 file is updated, the code basically overwrites the contents in the "master.xlsx" file. I need to append the contents from "combo1" to "Master" without the headers being inserted every time. Can someone help me with this?

import pandas as pd

writer = pd.ExcelWriter('master.xlsx', engine='xlsxwriter')
df = pd.read_csv('combo1.csv')
df.to_excel(writer, sheet_name='sheetname')
writer.save()

Body:
Refer to Append Data at the End of an Excel Sheet section in this medium article:
Using Python Pandas with Excel Sheets

(Credit to Nensi Trambadiya for the article)

Basically you'll have to first read the Excel file and find the number of rows before pushing the new data.

reader = pd.read_excel(r'master.xlsx')
df.to_excel(writer,index=False,header=False,startrow=len(reader)+1)


问:
Unable to dequeue single cell in collection view
I have come across a very disturbing issue in which I am not able to dequeue only a single cell in collectionView. When there are more than one item in collectionView, it works fine but soon as I have an array with a single item, it doesn't show any cell. I am not able to figure it out what’s wrong with my code.

```<code>extension collectionview: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UICollectionViewCell
        return cell
    }
}
</code>```

答:
Needless to say, collection views work fine with only one cell. Your code is insufficient to manifest the problem you describe.

But here are a few observations/suggestions:

Add breakpoint or debugging log statement in numberOfItemsInSection and make sure it’s getting called. If not, then you likely have one of a variety of different possible problems:

Make sure you set the “data source” for the collection view (either in IB or programmatically). Merely conforming to UICollectionViewDataSource is not sufficient: You actually have to set the data source of the collection view.

Make sure you set the base class for your storyboard scene to be the view controller in question.

Make sure you put these UICollectionViewDataSource methods in the right object.

I notice that you've put these methods as an extension to collectionview.

Class names should, as a matter of convention, always start with upper case letter.

Usually the UICollectionViewDataSource methods are put in the view controller (or, less common, a dedicated object that you'll vend and to which keep your own strong reference). I'm not sure what to make of your class named collectionview.

But, in short, there is no problem having collection views with only one cell. Your problem rests elsewhere.

Body:
I have come across a very disturbing issue in which I am not able to dequeue only a single cell in collectionView. When there are more than one item in collectionView, it works fine but soon as I have an array with a single item, it doesn't show any cell. I am not able to figure it out what’s wrong with my code.

extension collectionview: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UICollectionViewCell
        return cell
    }
}


问:
Force a push with SourceTree
I started using SourceTree a few days ago to manage Mercurial repositories with my Mac. Now I ran into the problem when pushing to my remote repository creates a new head on a new branch and I would like to force it.

However, I am not able to find any specific option in SourceTree which allows me to set the force option for a push. Is it just my inability to find it or is there no possibility to set it?

Thanks in advance
Michael

答:
You can show it on Preferences -> Advanced -> Allow force push

Then force push option would be available.

Title: Force a push with SourceTree


问:
v-list-item-title joining with router link in App.vue
Is there any other way to write this line of code below for better UI interaction?

```<code><v-list-item>
<v-list-item-title>
<router-link to="historicalFigures">Historical Figures </router-link>
</v-list-item-title>
</v-list-item>
</code>```

Im asking this because using the above code, only when i click the link of the navigation bar the results displays.
like so

but when i click the area that's around the link,nothing is showing or responding.

答:
Try placing a 'to' prop on a v-list-item and not nest a router link as your code is written.  Alternatively, you can use a @click on the v-list-item and that method would use this.$router.push('/historicalFigures')</p>

```<code><v-list-item to='historicalFigures'>
    <v-list-item-title>Historical Figures</v-list-item-title>
</v-list-item>
</code>```

Body:
Is there any other way to write this line of code below for better UI interaction?

<v-list-item>
<v-list-item-title>
<router-link to="historicalFigures">Historical Figures </router-link>
</v-list-item-title>
</v-list-item>

Im asking this because using the above code, only when i click the link of the navigation bar the results displays.
like so

but when i click the area that's around the link,nothing is showing or responding.

Body:
Try placing a 'to' prop on a v-list-item and not nest a router link as your code is written.  Alternatively, you can use a @click on the v-list-item and that method would use this.$router.push('/historicalFigures')

<v-list-item to='historicalFigures'>
    <v-list-item-title>Historical Figures</v-list-item-title>
</v-list-item>