问:
AudioRecord returns some empty data after start
I wrote a standard code for receiving data from microphone by using AudioRecord. Here is my code:

```<code>AudioReceiver() {
    int minHardwareBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE,
            CHANNEL_CONFIG, AUDIO_FORMAT);
    Log.d(TAG, "minHardwareBufferSize = " + minHardwareBufferSize);
    int bufferSizeBytes = (minHardwareBufferSize > MIN_BUFFER_SIZE_BYTES) ?
            minHardwareBufferSize : MIN_BUFFER_SIZE_BYTES;
    bufferSizeShorts = bufferSizeBytes / 2;

    //резервируем буфер с запасом в 2 раза
    audioRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
            SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, bufferSizeBytes * 2);

    testStack = new short[bufferSizeShorts * 4];
    Arrays.fill(testStack, (short) 2000);
}

boolean startReceive() {
    audioRecorder.startRecording();
    isReceiving = true;
    int recordingState = audioRecorder.getRecordingState();
    Log.d(TAG, "recordingState = " + recordingState);
    new Thread(receivingRunnable).start();
    return (recordingState == AudioRecord.RECORDSTATE_RECORDING);
}

boolean stopReceive() {
    isReceiving = false;
    audioRecorder.stop();
    int recordingState = audioRecorder.getRecordingState();
    Log.d(TAG, "recordingState = " + recordingState);
    return (recordingState == AudioRecord.RECORDSTATE_STOPPED);
}

private Runnable receivingRunnable = new Runnable() {
    @Override
    public void run() {
        int readCount = 0;
        short[] dataBuffer = new short[bufferSizeShorts];
        while (isReceiving) {
            testBusy = true;
            for (int j = 0; j < 4; j++) {
                readCount = audioRecorder.read(dataBuffer, 0, dataBuffer.length);
                Log.d(TAG, "receive " + readCount + " bytes");
                System.arraycopy(dataBuffer, 0, testStack, bufferSizeShorts * j, readCount);
            }
            isReceiving = false;
            testBusy = false;
        }
    }
};
</code>```

But I noticed that after the first start of the startReceive function, at the beginning of the testStack buffer, there are empty data (about 1000 samples on the Nexus 4, see data graph).

Between the initialization of AudioReceiver and the launch of startReceive takes a long time. What could be the cause of the problem?

答:
It seems delay is caused when OS takes time to resample the data, and it is difficult to have a one sample rate for all devices. Also mentioned by other posts. So, I instead moved my audio record logic to activity onCreate. When I dont need the audio or it is paused, I just throw away the data.

I did not observe heavy battery drain while always on an audio record. While this might not be the best way to go about fixing this issue, but this definately was an acceptable workaround for me.

Body:
I wrote a standard code for receiving data from microphone by using AudioRecord. Here is my code:

AudioReceiver() {
    int minHardwareBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE,
            CHANNEL_CONFIG, AUDIO_FORMAT);
    Log.d(TAG, "minHardwareBufferSize = " + minHardwareBufferSize);
    int bufferSizeBytes = (minHardwareBufferSize > MIN_BUFFER_SIZE_BYTES) ?
            minHardwareBufferSize : MIN_BUFFER_SIZE_BYTES;
    bufferSizeShorts = bufferSizeBytes / 2;

    //резервируем буфер с запасом в 2 раза
    audioRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
            SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, bufferSizeBytes * 2);

    testStack = new short[bufferSizeShorts * 4];
    Arrays.fill(testStack, (short) 2000);
}

boolean startReceive() {
    audioRecorder.startRecording();
    isReceiving = true;
    int recordingState = audioRecorder.getRecordingState();
    Log.d(TAG, "recordingState = " + recordingState);
    new Thread(receivingRunnable).start();
    return (recordingState == AudioRecord.RECORDSTATE_RECORDING);
}

boolean stopReceive() {
    isReceiving = false;
    audioRecorder.stop();
    int recordingState = audioRecorder.getRecordingState();
    Log.d(TAG, "recordingState = " + recordingState);
    return (recordingState == AudioRecord.RECORDSTATE_STOPPED);
}

private Runnable receivingRunnable = new Runnable() {
    @Override
    public void run() {
        int readCount = 0;
        short[] dataBuffer = new short[bufferSizeShorts];
        while (isReceiving) {
            testBusy = true;
            for (int j = 0; j < 4; j++) {
                readCount = audioRecorder.read(dataBuffer, 0, dataBuffer.length);
                Log.d(TAG, "receive " + readCount + " bytes");
                System.arraycopy(dataBuffer, 0, testStack, bufferSizeShorts * j, readCount);
            }
            isReceiving = false;
            testBusy = false;
        }
    }
};

But I noticed that after the first start of the startReceive function, at the beginning of the testStack buffer, there are empty data (about 1000 samples on the Nexus 4, see data graph).

Between the initialization of AudioReceiver and the launch of startReceive takes a long time. What could be the cause of the problem?


来源: stackexchange

问:
Data mining to find highest paid employee
I have a spreadsheet of data that I am using for this code. It has a long list of employees and their base salary and positions. I am trying to find the highest paid person and print out that information. Instead of giving me that, it gives me the last person on the list. It also only gives me the last number of the salary. Instead of printing '209318' it just prints '8'

```<code>def main():
  my_file = open('IndianaSalaries.csv', 'r')

  list_of_lines = my_file.read().splitlines()

  for i in range(1, len(list_of_lines)):
    one_line = list_of_lines[i]
    line_items = one_line.split(',')
    base_pay = line_items[2]
    highest = max(base_pay)

    first_name = line_items[1]
    last_name = line_items[0]
    university = line_items[3]
    position = line_items[4]

  print("The highest paid person is", first_name, last_name, "with the position of",position,"at",university,"making a base salary of $",highest)

main()
</code>```

Here is example data: Last Name,First Name,Base Pay,University or Office,Position,,,
Aaron, Julia J,97783,Clarion,Chair,,,
Aaron, Paul Neal,23961,Shippensburg,Custodial Worker 1,,,
Aaron, William F,11199,Clarion,Instructor,,,
Abbondanza, Lawrence A. Jr,111099,Edinboro,Instructor, PT Temp,,
Abbott, Ann,107870,West Chester,Chairperson,,,
Abbott, Barbara E.,31687,Edinboro,Fiscal Assistant,,,
Abbott, Kristen Kyle,44795,Clarion,Instructor,,,
Abbott, Mary V,35071,Edinboro,Fiscal Assistant,,,

答:
You are basically just iterating through the data. You are not actually finding the row that has the highest salay.

There are many ways you can solve this. What you can do is have two variables, one to store the max salary (call it, for example, max_pay), and another to store which employee (or row) has that max salary (row_max).

What you can do is:

Initialize max_pay to be a very low number, say 0,

In you for loop, check if the max_pay is lower than the row's base pay. If yes, then you have found a row (or employee) that has a higher pay, and store that row number in row_max. If not, the move on to the next iteration.

After the loop, simply print out the row (or employee) whose row number is in the row_max

ContentLicense: CC BY-SA 3.0

Body:
I have a spreadsheet of data that I am using for this code. It has a long list of employees and their base salary and positions. I am trying to find the highest paid person and print out that information. Instead of giving me that, it gives me the last person on the list. It also only gives me the last number of the salary. Instead of printing '209318' it just prints '8'

def main():
  my_file = open('IndianaSalaries.csv', 'r')

  list_of_lines = my_file.read().splitlines()

  for i in range(1, len(list_of_lines)):
    one_line = list_of_lines[i]
    line_items = one_line.split(',')
    base_pay = line_items[2]
    highest = max(base_pay)

    first_name = line_items[1]
    last_name = line_items[0]
    university = line_items[3]
    position = line_items[4]

  print("The highest paid person is", first_name, last_name, "with the position of",position,"at",university,"making a base salary of $",highest)

main()

Here is example data: Last Name,First Name,Base Pay,University or Office,Position,,,
Aaron, Julia J,97783,Clarion,Chair,,,
Aaron, Paul Neal,23961,Shippensburg,Custodial Worker 1,,,
Aaron, William F,11199,Clarion,Instructor,,,
Abbondanza, Lawrence A. Jr,111099,Edinboro,Instructor, PT Temp,,
Abbott, Ann,107870,West Chester,Chairperson,,,
Abbott, Barbara E.,31687,Edinboro,Fiscal Assistant,,,
Abbott, Kristen Kyle,44795,Clarion,Instructor,,,
Abbott, Mary V,35071,Edinboro,Fiscal Assistant,,,


问:
Cannot access the ADLS account '(accountname)'
I am attempting to use azure data factory v2 to copy data to an Azure data lake store sink.  I have created the data lake store, created an AD web application following the article here, and made sure that the account has access to the data lake store.  However, I receive the following error whenever I try to run a pipeline involving a single copy activity that uses the data lake store as a sink:

Activity Copy (copy activity name) failed: Failed to detect region of linked service 'AzureDataLakeStore' : 'LS_DataLakeStore' with error 'Cannot access the ADLS account '(data lake store account name)'. Please make sure it has been created.', please explicitly specify the location of the integration runtime referred by the connectVia property to avoid region detection if needed.

I have triple checked that the account name is correct.  I've granted the AD application 'Owner' access to the subscription just to make sure it's not a permissions issue.  And I even attempted to create an Adf Integration Runtime so I can specify it via the 'connectVia' property as suggested by the error, all with no luck.

Ideas on why ADF can't seem to see my data lake store?

Here is my Linked Service json:

```<code>{
  "name": "LS_DataLakeStore",
  "properties": {
    "type": "AzureDataLakeStore",
    "typeProperties": {
      "dataLakeStoreUri": "adl://{my adls account name}.azuredatalakestore.net/",
      "servicePrincipalId": "{the application id of the AD account I created}",
      "servicePrincipalKey": {
        "type": "SecureString",
        "value": "{the value of the key for the AD account I generated}"
      },
      "tenant": "{my tenant id (I also tried using the tenant domain name here as well)}",
      "subscriptionId": "{the subscription id in which the ADF and ADLS are located}",
      "resourceGroupName": "{the resource group name in which the ADF and ADLS are located}"
    }
  }
}
</code>```

答:
Thanks for using Azure Data Factory, Andrew.

Based on your attached linked service payload, I think you are using "service principal authentication" for your Azure Data Lake Store followed by the guidance here https://learn.microsoft.com/en-us/azure/data-factory/connector-azure-data-lake-store#using-service-principal-authentication, right?

Generally the error should be caused by that the provided service principal doesn't have the permission to detect the Azure Data Lake Store's region. Please grant at least "Reader" role in account access control (IAM) on the Azure Data Lake Store. Detail steps:

Go to Azure Portal, find the Data Lake Store account

Click “Access Control (IAM)” on the blade of the Data Lake Store

Click "Add" in the blade of "Access Control (IAM)"

Set "Role" to "Reader", and specify the AAD app you created

After that, please try to re-run the Copy Activity.

Body:
I am attempting to use azure data factory v2 to copy data to an Azure data lake store sink.  I have created the data lake store, created an AD web application following the article here, and made sure that the account has access to the data lake store.  However, I receive the following error whenever I try to run a pipeline involving a single copy activity that uses the data lake store as a sink:

Activity Copy (copy activity name) failed: Failed to detect region of linked service 'AzureDataLakeStore' : 'LS_DataLakeStore' with error 'Cannot access the ADLS account '(data lake store account name)'. Please make sure it has been created.', please explicitly specify the location of the integration runtime referred by the connectVia property to avoid region detection if needed.

I have triple checked that the account name is correct.  I've granted the AD application 'Owner' access to the subscription just to make sure it's not a permissions issue.  And I even attempted to create an Adf Integration Runtime so I can specify it via the 'connectVia' property as suggested by the error, all with no luck.

Ideas on why ADF can't seem to see my data lake store?

Here is my Linked Service json:

{
  "name": "LS_DataLakeStore",
  "properties": {
    "type": "AzureDataLakeStore",
    "typeProperties": {
      "dataLakeStoreUri": "adl://{my adls account name}.azuredatalakestore.net/",
      "servicePrincipalId": "{the application id of the AD account I created}",
      "servicePrincipalKey": {
        "type": "SecureString",
        "value": "{the value of the key for the AD account I generated}"
      },
      "tenant": "{my tenant id (I also tried using the tenant domain name here as well)}",
      "subscriptionId": "{the subscription id in which the ADF and ADLS are located}",
      "resourceGroupName": "{the resource group name in which the ADF and ADLS are located}"
    }
  }
}


问:
If an object is passed as an argument in a function, does it create a new instance?
In this code:

```<code>function myFunction(obj) {
  console.log(obj);
}

var obj = {
  key : 'value',
  funct :  function(){},
  elem  :  document.getElementById('navigation').getElementsByTagName('a')
}

myFunction(obj);
</code>```

Is the object "obj" printed in the console inside myFunction the same object i defined or is a new instance?

Also, what if i pass it from myFunction to another function?

答: I believe javascript passes by reference so myFunction will see a reference to the same object.</p>

ContentLicense: CC BY-SA 2.5

Body:
In this code:

function myFunction(obj) {
  console.log(obj);
}

var obj = {
  key : 'value',
  funct :  function(){},
  elem  :  document.getElementById('navigation').getElementsByTagName('a')
}

myFunction(obj);

Is the object "obj" printed in the console inside myFunction the same object i defined or is a new instance?

Also, what if i pass it from myFunction to another function?


问:
How to add scroll bar?
This XML page has some content but these content is some what more so the content is out of the screen. Now I wanna show that content to the user and I do not know how to add  scroll bar.                                                I tried to add <ScrollView> but it gives me an error I do not know why it gives me that error

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.TutorProfile"
    android:background="@color/graylight"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="405dp">

        <LinearLayout
            android:background="@drawable/gradientbackground"
            android:layout_width="match_parent"
            android:layout_height="350dp"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/photospot"
                android:layout_marginTop="45dp"
                android:layout_gravity="center_horizontal"
                android:layout_width="150dp"
                android:layout_height="150dp"
                android:src="@drawable/khalid"/>
            <TextView
                android:id="@+id/textname"
                android:layout_marginTop="10dp"
                android:layout_gravity="center_horizontal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#fff"
                android:textStyle="bold"
                android:textSize="21sp"/>
        </LinearLayout>
        <android.support.v7.widget.CardView
            android:layout_width="400dp"
            android:layout_height="120dp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="275dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:weightSum="3">
                <LinearLayout
                    android:gravity="center"
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="match_parent">
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Photos"
                        android:textSize="20sp"
                        />
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="125"
                        android:textStyle="bold"
                        android:textSize="20sp"
                        android:paddingTop="10dp"
                        android:textColor="@color/startblue"/>

                </LinearLayout>
                <LinearLayout
                    android:gravity="center"
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="match_parent">
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Followers"
                        android:textSize="20sp"
                        />
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="1205"
                        android:textStyle="bold"
                        android:textSize="20sp"
                        android:paddingTop="10dp"
                        android:textColor="@color/startblue"/>

                </LinearLayout>
                <LinearLayout
                    android:gravity="center"
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="match_parent">
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Following"
                        android:textSize="20sp"
                        />
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="360"
                        android:textStyle="bold"
                        android:textSize="20sp"
                        android:paddingTop="10dp"
                        android:textColor="@color/startblue"/>

                </LinearLayout>
            </LinearLayout>

        </android.support.v7.widget.CardView>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="360dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center"
        android:layout_marginTop="45dp">
        <LinearLayout
            android:orientation="horizontal"
            android:paddingLeft="25dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:src="@drawable/ic_email_black_24dp"/>
            <TextView
                android:textStyle="bold"
                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="20dp"
                android:text="Wiliam@gmail.com"/>
        </LinearLayout>
        <LinearLayout
            android:layout_marginTop="25dp"
            android:orientation="horizontal"
            android:paddingLeft="25dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:src="@drawable/ic_phone_black_24dp"/>
            <TextView
                android:textStyle="bold"

                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="20dp"
                android:text="+266 225 225"/>
        </LinearLayout>
        <LinearLayout
            android:layout_marginTop="25dp"
            android:orientation="horizontal"
            android:paddingLeft="25dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:src="@drawable/ic_group_add_black_24dp"/>
            <TextView
                android:textStyle="bold"

                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="20dp"
                android:text="Add to group"/>
        </LinearLayout>
        <LinearLayout
            android:layout_marginTop="25dp"
            android:orientation="horizontal"
            android:paddingLeft="25dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:src="@drawable/ic_forum_black_24dp"/>
            <TextView
                android:textStyle="bold"

                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="20dp"
                android:text="Show all comments"/>
        </LinearLayout>
    </LinearLayout>

    <Button
        android:textColor="#fff"
        android:background="@drawable/buttonstyle"
        android:layout_marginTop="35dp"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Follow Me"/>

</LinearLayout>
</code>```

答:
```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.TutorProfile"
    android:background="@color/graylight"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="405dp">

                <LinearLayout
                    android:background="@drawable/gradientbackground"
                    android:layout_width="match_parent"
                    android:layout_height="350dp"
                    android:orientation="vertical">

                    <ImageView
                        android:id="@+id/photospot"
                        android:layout_marginTop="45dp"
                        android:layout_gravity="center_horizontal"
                        android:layout_width="150dp"
                        android:layout_height="150dp"
                        android:src="@drawable/khalid"/>
                    <TextView
                        android:id="@+id/textname"
                        android:layout_marginTop="10dp"
                        android:layout_gravity="center_horizontal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="#fff"
                        android:textStyle="bold"
                        android:textSize="21sp"/>
                </LinearLayout>
                <android.support.v7.widget.CardView
                    android:layout_width="400dp"
                    android:layout_height="120dp"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="275dp">
                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:orientation="horizontal"
                        android:weightSum="3">
                        <LinearLayout
                            android:gravity="center"
                            android:orientation="vertical"
                            android:layout_width="0dp"
                            android:layout_weight="1"
                            android:layout_height="match_parent">
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Photos"
                                android:textSize="20sp"
                                />
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="125"
                                android:textStyle="bold"
                                android:textSize="20sp"
                                android:paddingTop="10dp"
                                android:textColor="@color/startblue"/>

                        </LinearLayout>
                        <LinearLayout
                            android:gravity="center"
                            android:orientation="vertical"
                            android:layout_width="0dp"
                            android:layout_weight="1"
                            android:layout_height="match_parent">
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Followers"
                                android:textSize="20sp"
                                />
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="1205"
                                android:textStyle="bold"
                                android:textSize="20sp"
                                android:paddingTop="10dp"
                                android:textColor="@color/startblue"/>

                        </LinearLayout>
                        <LinearLayout
                            android:gravity="center"
                            android:orientation="vertical"
                            android:layout_width="0dp"
                            android:layout_weight="1"
                            android:layout_height="match_parent">
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Following"
                                android:textSize="20sp"
                                />
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="360"
                                android:textStyle="bold"
                                android:textSize="20sp"
                                android:paddingTop="10dp"
                                android:textColor="@color/startblue"/>

                        </LinearLayout>
                    </LinearLayout>

                </android.support.v7.widget.CardView>
            </RelativeLayout>

            <LinearLayout
                android:layout_width="360dp"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_gravity="center"
                android:layout_marginTop="45dp">
                <LinearLayout
                    android:orientation="horizontal"
                    android:paddingLeft="25dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:layout_width="36dp"
                        android:layout_height="36dp"
                        android:src="@drawable/ic_email_black_24dp"/>
                    <TextView
                        android:textStyle="bold"
                        android:layout_gravity="center_vertical"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="20dp"
                        android:text="Wiliam@gmail.com"/>
                </LinearLayout>
                <LinearLayout
                    android:layout_marginTop="25dp"
                    android:orientation="horizontal"
                    android:paddingLeft="25dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:layout_width="36dp"
                        android:layout_height="36dp"
                        android:src="@drawable/ic_phone_black_24dp"/>
                    <TextView
                        android:textStyle="bold"

                        android:layout_gravity="center_vertical"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="20dp"
                        android:text="+266 225 225"/>
                </LinearLayout>
                <LinearLayout
                    android:layout_marginTop="25dp"
                    android:orientation="horizontal"
                    android:paddingLeft="25dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:layout_width="36dp"
                        android:layout_height="36dp"
                        android:src="@drawable/ic_group_add_black_24dp"/>
                    <TextView
                        android:textStyle="bold"

                        android:layout_gravity="center_vertical"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="20dp"
                        android:text="Add to group"/>
                </LinearLayout>
                <LinearLayout
                    android:layout_marginTop="25dp"
                    android:orientation="horizontal"
                    android:paddingLeft="25dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:layout_width="36dp"
                        android:layout_height="36dp"
                        android:src="@drawable/ic_forum_black_24dp"/>
                    <TextView
                        android:textStyle="bold"

                        android:layout_gravity="center_vertical"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="20dp"
                        android:text="Show all comments"/>
                </LinearLayout>
            </LinearLayout>

            <Button
                android:textColor="#fff"
                android:background="@drawable/buttonstyle"
                android:layout_marginTop="35dp"
                android:layout_gravity="center_horizontal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Follow Me"/>

        </LinearLayout>

    </ScrollView>

</LinearLayout>
</code>```

Try this. :)

Title: How to add scroll bar?

Body:
This XML page has some content but these content is some what more so the content is out of the screen. Now I wanna show that content to the user and I do not know how to add  scroll bar.                                                I tried to add <ScrollView> but it gives me an error I do not know why it gives me that error

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.TutorProfile"
    android:background="@color/graylight"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="405dp">

        <LinearLayout
            android:background="@drawable/gradientbackground"
            android:layout_width="match_parent"
            android:layout_height="350dp"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/photospot"
                android:layout_marginTop="45dp"
                android:layout_gravity="center_horizontal"
                android:layout_width="150dp"
                android:layout_height="150dp"
                android:src="@drawable/khalid"/>
            <TextView
                android:id="@+id/textname"
                android:layout_marginTop="10dp"
                android:layout_gravity="center_horizontal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#fff"
                android:textStyle="bold"
                android:textSize="21sp"/>
        </LinearLayout>
        <android.support.v7.widget.CardView
            android:layout_width="400dp"
            android:layout_height="120dp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="275dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:weightSum="3">
                <LinearLayout
                    android:gravity="center"
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="match_parent">
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Photos"
                        android:textSize="20sp"
                        />
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="125"
                        android:textStyle="bold"
                        android:textSize="20sp"
                        android:paddingTop="10dp"
                        android:textColor="@color/startblue"/>

                </LinearLayout>
                <LinearLayout
                    android:gravity="center"
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="match_parent">
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Followers"
                        android:textSize="20sp"
                        />
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="1205"
                        android:textStyle="bold"
                        android:textSize="20sp"
                        android:paddingTop="10dp"
                        android:textColor="@color/startblue"/>

                </LinearLayout>
                <LinearLayout
                    android:gravity="center"
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="match_parent">
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Following"
                        android:textSize="20sp"
                        />
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="360"
                        android:textStyle="bold"
                        android:textSize="20sp"
                        android:paddingTop="10dp"
                        android:textColor="@color/startblue"/>

                </LinearLayout>
            </LinearLayout>

        </android.support.v7.widget.CardView>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="360dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center"
        android:layout_marginTop="45dp">
        <LinearLayout
            android:orientation="horizontal"
            android:paddingLeft="25dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:src="@drawable/ic_email_black_24dp"/>
            <TextView
                android:textStyle="bold"
                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="20dp"
                android:text="Wiliam@gmail.com"/>
        </LinearLayout>
        <LinearLayout
            android:layout_marginTop="25dp"
            android:orientation="horizontal"
            android:paddingLeft="25dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:src="@drawable/ic_phone_black_24dp"/>
            <TextView
                android:textStyle="bold"

                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="20dp"
                android:text="+266 225 225"/>
        </LinearLayout>
        <LinearLayout
            android:layout_marginTop="25dp"
            android:orientation="horizontal"
            android:paddingLeft="25dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:src="@drawable/ic_group_add_black_24dp"/>
            <TextView
                android:textStyle="bold"

                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="20dp"
                android:text="Add to group"/>
        </LinearLayout>
        <LinearLayout
            android:layout_marginTop="25dp"
            android:orientation="horizontal"
            android:paddingLeft="25dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:src="@drawable/ic_forum_black_24dp"/>
            <TextView
                android:textStyle="bold"

                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="20dp"
                android:text="Show all comments"/>
        </LinearLayout>
    </LinearLayout>

    <Button
        android:textColor="#fff"
        android:background="@drawable/buttonstyle"
        android:layout_marginTop="35dp"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Follow Me"/>

</LinearLayout>

Body:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.TutorProfile"
    android:background="@color/graylight"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="405dp">

                <LinearLayout
                    android:background="@drawable/gradientbackground"
                    android:layout_width="match_parent"
                    android:layout_height="350dp"
                    android:orientation="vertical">

                    <ImageView
                        android:id="@+id/photospot"
                        android:layout_marginTop="45dp"
                        android:layout_gravity="center_horizontal"
                        android:layout_width="150dp"
                        android:layout_height="150dp"
                        android:src="@drawable/khalid"/>
                    <TextView
                        android:id="@+id/textname"
                        android:layout_marginTop="10dp"
                        android:layout_gravity="center_horizontal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="#fff"
                        android:textStyle="bold"
                        android:textSize="21sp"/>
                </LinearLayout>
                <android.support.v7.widget.CardView
                    android:layout_width="400dp"
                    android:layout_height="120dp"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="275dp">
                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:orientation="horizontal"
                        android:weightSum="3">
                        <LinearLayout
                            android:gravity="center"
                            android:orientation="vertical"
                            android:layout_width="0dp"
                            android:layout_weight="1"
                            android:layout_height="match_parent">
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Photos"
                                android:textSize="20sp"
                                />
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="125"
                                android:textStyle="bold"
                                android:textSize="20sp"
                                android:paddingTop="10dp"
                                android:textColor="@color/startblue"/>

                        </LinearLayout>
                        <LinearLayout
                            android:gravity="center"
                            android:orientation="vertical"
                            android:layout_width="0dp"
                            android:layout_weight="1"
                            android:layout_height="match_parent">
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Followers"
                                android:textSize="20sp"
                                />
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="1205"
                                android:textStyle="bold"
                                android:textSize="20sp"
                                android:paddingTop="10dp"
                                android:textColor="@color/startblue"/>

                        </LinearLayout>
                        <LinearLayout
                            android:gravity="center"
                            android:orientation="vertical"
                            android:layout_width="0dp"
                            android:layout_weight="1"
                            android:layout_height="match_parent">
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Following"
                                android:textSize="20sp"
                                />
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="360"
                                android:textStyle="bold"
                                android:textSize="20sp"
                                android:paddingTop="10dp"
                                android:textColor="@color/startblue"/>

                        </LinearLayout>
                    </LinearLayout>

                </android.support.v7.widget.CardView>
            </RelativeLayout>

            <LinearLayout
                android:layout_width="360dp"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_gravity="center"
                android:layout_marginTop="45dp">
                <LinearLayout
                    android:orientation="horizontal"
                    android:paddingLeft="25dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:layout_width="36dp"
                        android:layout_height="36dp"
                        android:src="@drawable/ic_email_black_24dp"/>
                    <TextView
                        android:textStyle="bold"
                        android:layout_gravity="center_vertical"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="20dp"
                        android:text="Wiliam@gmail.com"/>
                </LinearLayout>
                <LinearLayout
                    android:layout_marginTop="25dp"
                    android:orientation="horizontal"
                    android:paddingLeft="25dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:layout_width="36dp"
                        android:layout_height="36dp"
                        android:src="@drawable/ic_phone_black_24dp"/>
                    <TextView
                        android:textStyle="bold"

                        android:layout_gravity="center_vertical"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="20dp"
                        android:text="+266 225 225"/>
                </LinearLayout>
                <LinearLayout
                    android:layout_marginTop="25dp"
                    android:orientation="horizontal"
                    android:paddingLeft="25dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:layout_width="36dp"
                        android:layout_height="36dp"
                        android:src="@drawable/ic_group_add_black_24dp"/>
                    <TextView
                        android:textStyle="bold"

                        android:layout_gravity="center_vertical"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="20dp"
                        android:text="Add to group"/>
                </LinearLayout>
                <LinearLayout
                    android:layout_marginTop="25dp"
                    android:orientation="horizontal"
                    android:paddingLeft="25dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:layout_width="36dp"
                        android:layout_height="36dp"
                        android:src="@drawable/ic_forum_black_24dp"/>
                    <TextView
                        android:textStyle="bold"

                        android:layout_gravity="center_vertical"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="20dp"
                        android:text="Show all comments"/>
                </LinearLayout>
            </LinearLayout>

            <Button
                android:textColor="#fff"
                android:background="@drawable/buttonstyle"
                android:layout_marginTop="35dp"
                android:layout_gravity="center_horizontal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Follow Me"/>

        </LinearLayout>

    </ScrollView>

</LinearLayout>

Try this. :)


问:
How do I programmatically add attachments to test results during a build in VSTS?
I'm looking for a way to add my own attachments to test results so that I can see them after a build has completed here...

I would like to add these programmatically, during a build and after a test has failed. The attachments will be screenshots.

Is this possible?

I had a quick look at the API reference but this looked to be concerned with adding attachments to existing test 'runs', or on the build, the side was for creating build definitions and triggering them. I may have missed it but I couldn't find how to add attachments from code during or immediately after a test task had completed.

Thanks,

答:
You could get test run of the build first and then retrieve the test result from the test run:

```<code>class Program
{
    static void Main(string[] args)
    {
        string ur = "https://xxxxxxx/";
        TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(ur));
        //Get build information
        BuildHttpClient bhc = ttpc.GetClient<BuildHttpClient>();
        string projectname = "Project";
        int buildId = x;
        Build bui = bhc.GetBuildAsync(projectname,buildId).Result;
        //Get test run for the build
        TestManagementHttpClient ithc = ttpc.GetClient<TestManagementHttpClient>();

        Console.WriteLine(bui.BuildNumber);

        QueryModel qm = new QueryModel("Select * From TestRun Where BuildNumber Contains '" + bui.BuildNumber + "'");

        List<TestRun> testruns = ithc.GetTestRunsByQueryAsync(qm,projectname).Result;
        foreach (TestRun testrun in testruns)
        {

            List<TestCaseResult> testresults = ithc.GetTestResultsAsync(projectname, testrun.Id).Result;
            foreach (TestCaseResult tcr in testresults)
                {
                    Console.WriteLine(tcr.Id);
                    Console.WriteLine(tcr.Outcome);
                }

            Console.ReadLine();
        }
        Console.ReadLine();
    }
}
</code>```

Once you get failed test result id, you could use Rest API to attach a file to test result:

```<code>POST https://{instance}/DefaultCollection/{project}/_apis/test/runs/{run}/results/{result}/attachments?api-version={version}
Content-Type: application/json
{
  "stream": { string },
  "fileName": { string },
  "comment": { string },
  "attachmentType": { string }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You could get test run of the build first and then retrieve the test result from the test run:

class Program
{
    static void Main(string[] args)
    {
        string ur = "https://xxxxxxx/";
        TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(ur));
        //Get build information
        BuildHttpClient bhc = ttpc.GetClient<BuildHttpClient>();
        string projectname = "Project";
        int buildId = x;
        Build bui = bhc.GetBuildAsync(projectname,buildId).Result;
        //Get test run for the build
        TestManagementHttpClient ithc = ttpc.GetClient<TestManagementHttpClient>();

        Console.WriteLine(bui.BuildNumber);

        QueryModel qm = new QueryModel("Select * From TestRun Where BuildNumber Contains '" + bui.BuildNumber + "'");

        List<TestRun> testruns = ithc.GetTestRunsByQueryAsync(qm,projectname).Result;
        foreach (TestRun testrun in testruns)
        {

            List<TestCaseResult> testresults = ithc.GetTestResultsAsync(projectname, testrun.Id).Result;
            foreach (TestCaseResult tcr in testresults)
                {
                    Console.WriteLine(tcr.Id);
                    Console.WriteLine(tcr.Outcome);
                }

            Console.ReadLine();
        }
        Console.ReadLine();
    }
}

Once you get failed test result id, you could use Rest API to attach a file to test result:

POST https://{instance}/DefaultCollection/{project}/_apis/test/runs/{run}/results/{result}/attachments?api-version={version}
Content-Type: application/json
{
  "stream": { string },
  "fileName": { string },
  "comment": { string },
  "attachmentType": { string }
}


问:
How to perform an excel vlookup with dynamic lookup_value using VBA?
I am new to VBA and need to perform a vlookup with a dynamic lookup_value. The reason for this is that the actual lookup_value column can be on different column indices for different input sheets.

The original vlookup formula looks like this:

```<code>"=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'static vlookup
</code>```

What I am trying to accomplish should look like this:

1) Find the actual column index with the lookup_value inside (in the above case it's C2)

```<code>With ws
    Set FindRng = .Rows(1).Find(what:="Column Name") ' should be 3 for C
        FiltCol = FindRng.Column ' get the column number where "Column Name" was found
End With
</code>```

2) Set lookup_value dynamically (in this case C2)

```<code>Dim dynamic_lookup_value as Range
dynamic_lookup_value = ws.Cells(FiltCol, 2) ' should be column C cell 2
</code>```

3) Set dynamic reference to lookup_value to actual vlookup formula (i.e. repalce hardcoded C2 with reference to C2)

```<code>foobar = "=VLOOKUP(dynamic_lookup_value,lookup!$A$2:$B$14,2,FALSE)" 'dynamic vlookup
</code>```

However, (3) yields Run-time error '91' Object variable or With-block variable not set.

How to perform an excel vlookup with dynamic lookup_value using VBA?

答:
first you have the columns and rows reversed here:

ws.Cells(FiltCol, 2)

It should be:

```<code>ws.Cells(2,FiltCol)
</code>```

Second you Set a range:

```<code>Set dynamic_lookup_value = ws.Cells(2,FiltCol)
</code>```

Then you do not put variables inside the quotes but concatenate them with &

```<code>foobar = "=VLOOKUP(" & dynamic_lookup_value.Address(0,0) & ",lookup!$A$2:$B$14,2,FALSE)"
</code>```

Another piece of advice:

FiltCol = FindRng.Column

Will error if the value is not found.  Put it in an If statement to check if the value was found or not:

```<code>If  not FindRng is nothing Then
    ...
End IF
</code>```

Body:
I am new to VBA and need to perform a vlookup with a dynamic lookup_value. The reason for this is that the actual lookup_value column can be on different column indices for different input sheets.

The original vlookup formula looks like this:

"=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'static vlookup

What I am trying to accomplish should look like this:

1) Find the actual column index with the lookup_value inside (in the above case it's C2)

With ws
    Set FindRng = .Rows(1).Find(what:="Column Name") ' should be 3 for C
        FiltCol = FindRng.Column ' get the column number where "Column Name" was found
End With

2) Set lookup_value dynamically (in this case C2)

Dim dynamic_lookup_value as Range
dynamic_lookup_value = ws.Cells(FiltCol, 2) ' should be column C cell 2

3) Set dynamic reference to lookup_value to actual vlookup formula (i.e. repalce hardcoded C2 with reference to C2)

foobar = "=VLOOKUP(dynamic_lookup_value,lookup!$A$2:$B$14,2,FALSE)" 'dynamic vlookup

However, (3) yields Run-time error '91' Object variable or With-block variable not set.

How to perform an excel vlookup with dynamic lookup_value using VBA?

Body:
first you have the columns and rows reversed here:

ws.Cells(FiltCol, 2)

It should be:

ws.Cells(2,FiltCol)

Second you Set a range:

Set dynamic_lookup_value = ws.Cells(2,FiltCol)

Then you do not put variables inside the quotes but concatenate them with &

foobar = "=VLOOKUP(" & dynamic_lookup_value.Address(0,0) & ",lookup!$A$2:$B$14,2,FALSE)"

Another piece of advice:

FiltCol = FindRng.Column

Will error if the value is not found.  Put it in an If statement to check if the value was found or not:

If  not FindRng is nothing Then
    ...
End IF


问:
CLR UDF returning Varbinary(MAX)
Is it possible for a SQL CLR User-Defined Function to return the data type varbinary(MAX)?

In the documentation it mentions:

"The input parameters and the type returned from a scalar-valued function can be any of the scalar data types supported by SQL Server, except rowversion, text, ntext, image, timestamp, table, or cursor." - they don't mention varbinary, but I'm not sure...

I have some byte-array data from the .NET side that I need to return to SQL Server from the CLR, and I'm trying to avoid having to do it with an output parameter from a stored procedure (this is how I have it working in test now).

Thanks!

答:
Technically there is no 8000 byte maximum in the interface from SQL Server to CLR code. It is mainly a difference of how the T-SQL wrapper Stored Proc or Function is defined. Meaning, if the T-SQL Proc or Function that calls the CLR code defines the RETURNS as VARBINARY(MAX), then it shall be VARBINARY(MAX), whether or not you specified SqlBytes or SqlBinary as the return type of the CLR code.

Both SqlBytes and SqlBinary can handle the 2 GB limit, BUT the difference is in how the CLR code accepts the data. SqlBinary (just like SqlString) takes the parameter value all at once while SqlBytes (just like SqlChars) provides a streaming interface so it might be more efficient for very large values.

Going back to the issue that you are seeing with the pre-defined SQL Function wrapper, that is was a matter of how Visual Studio (technically SSDT) auto-generatesd the T-SQL. The default for SqlBinary is was VARBINARY(8000) while the default for SqlBytes is was VARBINARY(MAX). In the same manner, the default for SqlString is was NVARCHAR(4000) while the default for SqlChars is was NVARCHAR(MAX). Those were the defaults when this question was asked. Starting in perhaps Visual Studio 2012, the default was changed to use MAX for all 4 of these datatypes. This is not necessarily a good thing since there is a definite performance hit for using the MAX types vs the non-MAX types. So, if you don't need more than 8000 bytes of VARBINARY or 4000 bytes of NVARCHAR, then you will want to override the default using one of the following methods:

You can ALTER the Function or Proc definition after it is generated by Visual Studio, and in this case you can even change the datatypes (of either input parameters or return values) to be any size such as VARBINARY(100) or NVARCHAR(50).

You can use the SqlFacet decorator to tell Visual Studio / SSDT to auto-generate the Function or Proc definitions with the size option that you prefer as opposed to the default. The following example shows specifying the size for both input parameters and the return value (note that -1 = MAX):

[return: SqlFacet(MaxSize = -1)]
[Microsoft.SqlServer.Server.SqlFunction(Name = "FunctionName")]
public static SqlBinary FuncName([SqlFacet(MaxSize = 50)] SqlString InputParam)
```

Using either of these two methods you can make either SqlBinary or SqlBytes map to either VARBINARY(1 - 8000) or VARBINARY(MAX). Likewise, you can make either SqlString or SqlChars map to eithert NVARCHAR(1 - 4000) or NVARCHAR(MAX).

Title: CLR UDF returning Varbinary(MAX)

Body:
Technically there is no 8000 byte maximum in the interface from SQL Server to CLR code. It is mainly a difference of how the T-SQL wrapper Stored Proc or Function is defined. Meaning, if the T-SQL Proc or Function that calls the CLR code defines the RETURNS as VARBINARY(MAX), then it shall be VARBINARY(MAX), whether or not you specified SqlBytes or SqlBinary as the return type of the CLR code.

Both SqlBytes and SqlBinary can handle the 2 GB limit, BUT the difference is in how the CLR code accepts the data. SqlBinary (just like SqlString) takes the parameter value all at once while SqlBytes (just like SqlChars) provides a streaming interface so it might be more efficient for very large values.

Going back to the issue that you are seeing with the pre-defined SQL Function wrapper, that is was a matter of how Visual Studio (technically SSDT) auto-generatesd the T-SQL. The default for SqlBinary is was VARBINARY(8000) while the default for SqlBytes is was VARBINARY(MAX). In the same manner, the default for SqlString is was NVARCHAR(4000) while the default for SqlChars is was NVARCHAR(MAX). Those were the defaults when this question was asked. Starting in perhaps Visual Studio 2012, the default was changed to use MAX for all 4 of these datatypes. This is not necessarily a good thing since there is a definite performance hit for using the MAX types vs the non-MAX types. So, if you don't need more than 8000 bytes of VARBINARY or 4000 bytes of NVARCHAR, then you will want to override the default using one of the following methods:

You can ALTER the Function or Proc definition after it is generated by Visual Studio, and in this case you can even change the datatypes (of either input parameters or return values) to be any size such as VARBINARY(100) or NVARCHAR(50).

You can use the SqlFacet decorator to tell Visual Studio / SSDT to auto-generate the Function or Proc definitions with the size option that you prefer as opposed to the default. The following example shows specifying the size for both input parameters and the return value (note that -1 = MAX):

[return: SqlFacet(MaxSize = -1)]
[Microsoft.SqlServer.Server.SqlFunction(Name = "FunctionName")]
public static SqlBinary FuncName([SqlFacet(MaxSize = 50)] SqlString InputParam)

Using either of these two methods you can make either SqlBinary or SqlBytes map to either VARBINARY(1 - 8000) or VARBINARY(MAX). Likewise, you can make either SqlString or SqlChars map to eithert NVARCHAR(1 - 4000) or NVARCHAR(MAX).


问:
How do I get my hp to work with my phone's micro sim
I have a Verizon phone (Droid turbo) and an HP elitebook 8470p that has a Sim slot. I have already bought an adapter for micro SIM to regular sim. but i can't seem to find the correct drivers for it and for all I can tell, my laptop doesn't seem to detect it. how would i know if it detects it and what drivers would I need to use Verizon's network?
i have done a bit of research online, but nothing seems to work</p>

答:
I highly doubt your Verizon sim will work with your laptop. The WWAN modules on your laptop don't support network of Verizon. They use 700 as primary band and 1900,1700 for support in densely populated areas but your laptop module supports just 1900, which I'm afraid might not be enough. Other possibility is that they might have simply not added your IMEI number to their whitelist.
I'd recommend you to test it out with a different sim (possibly a data only sim from a random MVNO).

Source: https://support.hp.com/us-en/document/c03374369


问:
Access index in pandas.Series.apply
Lets say I have a MultiIndex Series s:

```<code>>>> s
     values
a b
1 2  0.1
3 6  0.3
4 4  0.7
</code>```

and I want to apply a function which uses the index of the row:

```<code>def f(x):
   # conditions or computations using the indexes
   if x.index[0] and ...:
   other = sum(x.index) + ...
   return something
</code>```

How can I do s.apply(f) for such a function? What is the recommended way to make this kind of operations? I expect to obtain a new Series with the values resulting from this function applied on each row and the same MultiIndex.

答:
Convert to DataFrame and apply along row. You can access the index as x.name. x is also a Series now with 1 value

```<code>s.to_frame(0).apply(f, axis=1)[0]
</code>```

Title: Access index in pandas.Series.apply

Body:
Lets say I have a MultiIndex Series s:

>>> s
     values
a b
1 2  0.1
3 6  0.3
4 4  0.7

and I want to apply a function which uses the index of the row:

def f(x):
   # conditions or computations using the indexes
   if x.index[0] and ...:
   other = sum(x.index) + ...
   return something

How can I do s.apply(f) for such a function? What is the recommended way to make this kind of operations? I expect to obtain a new Series with the values resulting from this function applied on each row and the same MultiIndex.

Body:
Convert to DataFrame and apply along row. You can access the index as x.name. x is also a Series now with 1 value

s.to_frame(0).apply(f, axis=1)[0]


问:
Potential issue with file saving?
I am trying to accomplish a script where a user uploads an image and inputs a piece of text where from this Imagick will overlay said text over said uploaded image then output the file as an image download. This is my first project with PHP, I have taken a base source and I am attempting to alter it to fit my needs, I believe I have most portions working including the download part. After diagnosing the issue I believe that the $new_image is not saving to the disk before the image download has taken place.

As of now its partially working, I will remove all instances of image files from the target directory, fill in the form and press submit, the PHP script takes place but the output file is corrupt (nothing), I will then go ahead and submit the form again and it will behave as intended, this leads me to believe that the file is not saving correctly.

```<code><?php
function clean($name, $max) {
// Remove everything except letters numbers . and @ in the variable
preg_replace("/[^A-Za-z0-9.\-_@]/","",$name);

// Do not allow excessively long entries - length set in function call
// Could use a word wrap here - add a \\n after a certain amount of characters
$name = substr($name, 0, $max);
return $name;
}

// If the form has been submitted do this
if(isset($_FILES['filename']['tmp_name'])) {

// Temporary upload image name
$original_image = $_FILES['filename']['tmp_name'];

// Name to save the image as - in this case the same as the original
// The same folder as the code
$new_image = $_FILES['filename']['name'];

// Cleanup the text.
$text_submitted = clean ( $_POST['text_submitted'], 18 );

// Build the imagemagick command - using rgba so the opacity of the text can be set
$cmd = "$original_image -pointsize 50 -font /var/www/html/static/fonts/arial.ttf -fill rgba\(0,0,0,0.4\) ".
" -gravity center -annotate +0+0 \"$text_submitted\" ";

//save image
// I believe I need to save the file here????

//dl image
header("Content-type: image/jpeg");
header("Content-disposition: attachment; filename=\"".basename($new_image)."\"");
while (ob_get_level()) {
    ob_end_clean();
}
readfile($new_image);

// Coment out to display the command - good for debugging
//echo $cmd;

// Setup the array for the error reporting
$array = array();

// The array is to hold any errors you may get
// Coment out the if function after debugging
exec("convert $cmd  $new_image 2>&1", $array);
if ( !empty($array) ){
echo "<br >There were some errors during the Imagemagick conversion:<br >
```
".print_r($array)."
";
echo "```";
}
            }
else {
?>
</code>```

答:
Resolved, I moved the download file portion;

```<code>//dl image
header("Content-type: image/jpeg");
header("Content-disposition: attachment; filename=\"".basename($new_image)."\"");
while (ob_get_level()) {
    ob_end_clean();
}
readfile($new_image);
</code>```

Under where it saves the image;

```<code>exec("convert $cmd  $new_image 2>&1", $array);
if ( !empty($array) ){
echo "<br >There were some errors during the Imagemagick conversion:<br >
```
".print_r($array)."
";
echo "```";
}
</code>```

I am retarded, thanks anyway.

Title: Potential issue with file saving?

Body:
I am trying to accomplish a script where a user uploads an image and inputs a piece of text where from this Imagick will overlay said text over said uploaded image then output the file as an image download. This is my first project with PHP, I have taken a base source and I am attempting to alter it to fit my needs, I believe I have most portions working including the download part. After diagnosing the issue I believe that the $new_image is not saving to the disk before the image download has taken place.

As of now its partially working, I will remove all instances of image files from the target directory, fill in the form and press submit, the PHP script takes place but the output file is corrupt (nothing), I will then go ahead and submit the form again and it will behave as intended, this leads me to believe that the file is not saving correctly.

<?php
function clean($name, $max) {
// Remove everything except letters numbers . and @ in the variable
preg_replace("/[^A-Za-z0-9.\-_@]/","",$name);

// Do not allow excessively long entries - length set in function call
// Could use a word wrap here - add a \\n after a certain amount of characters
$name = substr($name, 0, $max);
return $name;
}

// If the form has been submitted do this
if(isset($_FILES['filename']['tmp_name'])) {

// Temporary upload image name
$original_image = $_FILES['filename']['tmp_name'];

// Name to save the image as - in this case the same as the original
// The same folder as the code
$new_image = $_FILES['filename']['name'];

// Cleanup the text.
$text_submitted = clean ( $_POST['text_submitted'], 18 );

// Build the imagemagick command - using rgba so the opacity of the text can be set
$cmd = "$original_image -pointsize 50 -font /var/www/html/static/fonts/arial.ttf -fill rgba\(0,0,0,0.4\) ".
" -gravity center -annotate +0+0 \"$text_submitted\" ";

//save image
// I believe I need to save the file here????

//dl image
header("Content-type: image/jpeg");
header("Content-disposition: attachment; filename=\"".basename($new_image)."\"");
while (ob_get_level()) {
    ob_end_clean();
}
readfile($new_image);

// Coment out to display the command - good for debugging
//echo $cmd;

// Setup the array for the error reporting
$array = array();

// The array is to hold any errors you may get
// Coment out the if function after debugging
exec("convert $cmd  $new_image 2>&1", $array);
if ( !empty($array) ){
echo "
There were some errors during the Imagemagick conversion:

".print_r($array)."
";
echo "
";
}
            }
else {
?>

Body:
Resolved, I moved the download file portion;

//dl image
header("Content-type: image/jpeg");
header("Content-disposition: attachment; filename=\"".basename($new_image)."\"");
while (ob_get_level()) {
    ob_end_clean();
}
readfile($new_image);

Under where it saves the image;

exec("convert $cmd  $new_image 2>&1", $array);
if ( !empty($array) ){
echo "<br >There were some errors during the Imagemagick conversion:<br >
<pre><br >".print_r($array)."<br>";
echo "</pre>";
}

I am retarded, thanks anyway.


问:
Dynamic Function Memory? C++
I've been reading through some books, and when it comes to Class/Functions using Pointers/Dynamic Memory (or heap or w/e they call it) I start to get confused.

Does anyone have a simple....like easy example they can show, because the books im using are using overly complex examples (large classes or multiple functions) and it makes it hard to follow. Pointers have always been my weak point anyways but I understand BASIC pointers, just classes/functions using them is a little bit confusing.

Also.....when would you use them is another question.

答:
I think this is what you're asking about:

Basically C++ doesn't allow variable-sized arrays.  Any array in C++ has to be given a very specific size.  But you can use pointers to work around that.  Consider the following code:

```<code>int *arry = new int[10];
</code>```

That just created an array of ints with 10 elements, and is pretty much the same exact thing as this:

```<code>int arry[] = int[10];
</code>```

The only difference is that each one will use a different set of syntax.  However imagine trying to do this:

```<code>Class class:
{
public:
    void initArry(int size);

private:
    int arry[];
};

void class::initArry(int size)
{
    arry = int[size]; // bad code
}
</code>```

For whatever reason C++ was designed to not allow regular arrays to be assigned sizes that are determined at runtime.  Instead they have to be assigned sizes upon being coded.  However the other way to make an array in C++ - using pointers - does not have this problem:

```<code>Class class:
{
public:
    ~class();
    void initArry(int size);

private:
    int *arry;
};

class::~class()
{
    delete []arry;
}

void class::initArry(int size)
{
    arry = new int[size]; // good code
}
</code>```

You have to do some memory cleanup in the second example, hence why I included the destructor, but by using pointers that way you can size the array at runtime (with a variable size).  This is called a dynamic array, and it is said that memory here is allocated dynamically.  The other kind is a static array.

As far as 2-dimensional arrays go, you can handle it kind of like this:

```<code>Class class:
{
public:
    ~class();
    void initArrays(int size1, int size2);

private:
    int **arry;
};

class::~class()
{
    delete [] arry[0];
    delete [] arry[1];
    delete [] arry;
}

void class::initArrays(int size1, int size2)
{
    arry = new int*[2];
    arry[0] = new int[size1];
    arry[1] = new int[size2];
}
</code>```

Disclaimer though:  I haven't done much with this language in a while, so I may be slightly incorrect on some of the syntax.

Title: Dynamic Function Memory? C++

Body:
I think this is what you're asking about:

Basically C++ doesn't allow variable-sized arrays.  Any array in C++ has to be given a very specific size.  But you can use pointers to work around that.  Consider the following code:

int *arry = new int[10];

That just created an array of ints with 10 elements, and is pretty much the same exact thing as this:

int arry[] = int[10];

The only difference is that each one will use a different set of syntax.  However imagine trying to do this:

Class class:
{
public:
    void initArry(int size);

private:
    int arry[];
};

void class::initArry(int size)
{
    arry = int[size]; // bad code
}

For whatever reason C++ was designed to not allow regular arrays to be assigned sizes that are determined at runtime.  Instead they have to be assigned sizes upon being coded.  However the other way to make an array in C++ - using pointers - does not have this problem:

Class class:
{
public:
    ~class();
    void initArry(int size);

private:
    int *arry;
};

class::~class()
{
    delete []arry;
}

void class::initArry(int size)
{
    arry = new int[size]; // good code
}

You have to do some memory cleanup in the second example, hence why I included the destructor, but by using pointers that way you can size the array at runtime (with a variable size).  This is called a dynamic array, and it is said that memory here is allocated dynamically.  The other kind is a static array.

As far as 2-dimensional arrays go, you can handle it kind of like this:

Class class:
{
public:
    ~class();
    void initArrays(int size1, int size2);

private:
    int **arry;
};

class::~class()
{
    delete [] arry[0];
    delete [] arry[1];
    delete [] arry;
}

void class::initArrays(int size1, int size2)
{
    arry = new int*[2];
    arry[0] = new int[size1];
    arry[1] = new int[size2];
}

Disclaimer though:  I haven't done much with this language in a while, so I may be slightly incorrect on some of the syntax.


问:
Showing an unknown type in Haskell (basic)
i'm currently learning Haskell and I have difficulties with a task.

I have a non-empty Binary Tree which looks like this

```<code>data STree a = BinS (STree a) a (STree a) | LeftS (STree a) a | RightS a (STree a) | LeafS a
</code>```

All I try to do right now is understanding how to output this tree.

As for the beginning I just want to output the case for LeafS a

I tried this

```<code>instance Show (STree a) where
show (LeafS b) = show b
</code>```

I just dont know how to convert this unknown type a to a String that I can output. I tried show, print, everything i can think of but nothing works.

The tree will only contain integers later on, but I have to do it with type a...

This is what I want: LeafS 2 ~> "2"
LeafS "100" ~> "100"

答:
Not every type can be shown in Haskell. Some types cannot be shown inherently - e.g. type Int -> Int - how do you show that? But some types just don't yet have an implementation of show. So in general, if you have some type a about which you know nothing, you cannot assume that it can be shown.

In order to use the function show on your type a, you need to ask the compiler to make sure that type a has an instance of Show a. To do that, you add a constraint to your instance, like this:

```<code>instance Show a => Show (STree a) where
    show (LeafS b) = show b
    ...
</code>```

Because you have specified Show a =>, the compiler knows that a given type STree a is an instance of the Show class if and only if the type a itself is. This allows the compiler to call show b and be sure that, when all types become known, this call will be possible. On the flip side, anyone who tries to show an instance of STree a will need to make sure that there exists an instance Show a, and the compiler will check that and issue an error if that is not so.

Body:
i'm currently learning Haskell and I have difficulties with a task.

I have a non-empty Binary Tree which looks like this

data STree a = BinS (STree a) a (STree a) | LeftS (STree a) a | RightS a (STree a) | LeafS a

All I try to do right now is understanding how to output this tree.

As for the beginning I just want to output the case for LeafS a

I tried this

instance Show (STree a) where
show (LeafS b) = show b

I just dont know how to convert this unknown type a to a String that I can output. I tried show, print, everything i can think of but nothing works.

The tree will only contain integers later on, but I have to do it with type a...

This is what I want: LeafS 2 ~> "2"
LeafS "100" ~> "100"

Body:
Not every type can be shown in Haskell. Some types cannot be shown inherently - e.g. type Int -> Int - how do you show that? But some types just don't yet have an implementation of show. So in general, if you have some type a about which you know nothing, you cannot assume that it can be shown.

In order to use the function show on your type a, you need to ask the compiler to make sure that type a has an instance of Show a. To do that, you add a constraint to your instance, like this:

instance Show a => Show (STree a) where
    show (LeafS b) = show b
    ...

Because you have specified Show a =>, the compiler knows that a given type STree a is an instance of the Show class if and only if the type a itself is. This allows the compiler to call show b and be sure that, when all types become known, this call will be possible. On the flip side, anyone who tries to show an instance of STree a will need to make sure that there exists an instance Show a, and the compiler will check that and issue an error if that is not so.


问:
How to fill area under curve in seaborn distribution plot
I have two variables

```<code>x = [1.883830, 7.692308,8.791209, 9.262166]
y = [5.337520, 4.866562, 2.825746, 6.122449]
</code>```

And I want to fit a Gaussian distribution using the seaborn wrapped for matplotlib. It seems like the sns.distplot function is the best way to do this, but I can't figure out how to fill in the area under the curve. Help?

```<code>fig, ax = plt.subplots(1)
sns.distplot(x,kde_kws={"shade":True}, kde=False, fit=stats.gamma, hist=None, color="red", label="2016", fit_kws={'color':'red'});
sns.distplot(y,kde_kws={"shade":True}, kde=False, fit=stats.gamma, hist=None, color="blue", label="2017", fit_kws={'color':'blue'})
</code>```

I think the "shade" argument could be part of the fit_kws argument but I haven't gotten this to work.

Another option would be to use ax.fill()?

答:
Yes, the shade argument is not supported for fit_kws unlike for the kde_kws. But as you guessed, we can fill the area under the two curves using ax.fill_between(). We will have to get the lines from the ax object and their x-y data and then use that to fill the area under the curves. Here is an example.

```<code>import numpy as np
import seaborn as sns
import scipy.stats as stats
import matplotlib.pyplot as plt

x = [1.883830, 7.692308,8.791209, 9.262166]
y = [5.337520, 4.866562, 2.825746, 6.122449]
ax = sns.distplot(x, fit_kws={"color":"red"}, kde=False,
        fit=stats.gamma, hist=None, label="label 1");
ax = sns.distplot(y, fit_kws={"color":"blue"}, kde=False,
        fit=stats.gamma, hist=None, label="label 2");

# Get the two lines from the axes to generate shading
l1 = ax.lines[0]
l2 = ax.lines[1]

# Get the xy data from the lines so that we can shade
x1 = l1.get_xydata()[:,0]
y1 = l1.get_xydata()[:,1]
x2 = l2.get_xydata()[:,0]
y2 = l2.get_xydata()[:,1]
ax.fill_between(x1,y1, color="red", alpha=0.3)
ax.fill_between(x2,y2, color="blue", alpha=0.3)

plt.show(block=False)
</code>```

The result is shown below:

Body:
I have two variables

x = [1.883830, 7.692308,8.791209, 9.262166]
y = [5.337520, 4.866562, 2.825746, 6.122449]

And I want to fit a Gaussian distribution using the seaborn wrapped for matplotlib. It seems like the sns.distplot function is the best way to do this, but I can't figure out how to fill in the area under the curve. Help?

fig, ax = plt.subplots(1)
sns.distplot(x,kde_kws={"shade":True}, kde=False, fit=stats.gamma, hist=None, color="red", label="2016", fit_kws={'color':'red'});
sns.distplot(y,kde_kws={"shade":True}, kde=False, fit=stats.gamma, hist=None, color="blue", label="2017", fit_kws={'color':'blue'})

I think the "shade" argument could be part of the fit_kws argument but I haven't gotten this to work.

Another option would be to use ax.fill()?

Body:
Yes, the shade argument is not supported for fit_kws unlike for the kde_kws. But as you guessed, we can fill the area under the two curves using ax.fill_between(). We will have to get the lines from the ax object and their x-y data and then use that to fill the area under the curves. Here is an example.

import numpy as np
import seaborn as sns
import scipy.stats as stats
import matplotlib.pyplot as plt

x = [1.883830, 7.692308,8.791209, 9.262166]
y = [5.337520, 4.866562, 2.825746, 6.122449]
ax = sns.distplot(x, fit_kws={"color":"red"}, kde=False,
        fit=stats.gamma, hist=None, label="label 1");
ax = sns.distplot(y, fit_kws={"color":"blue"}, kde=False,
        fit=stats.gamma, hist=None, label="label 2");

# Get the two lines from the axes to generate shading
l1 = ax.lines[0]
l2 = ax.lines[1]

# Get the xy data from the lines so that we can shade
x1 = l1.get_xydata()[:,0]
y1 = l1.get_xydata()[:,1]
x2 = l2.get_xydata()[:,0]
y2 = l2.get_xydata()[:,1]
ax.fill_between(x1,y1, color="red", alpha=0.3)
ax.fill_between(x2,y2, color="blue", alpha=0.3)

plt.show(block=False)

The result is shown below:


问:
How to fill `EditText` items with different colors?
Could I fill different color in an EditText items like this?

Sure, I'm able to use two EditText but I curious that it is able to use an EditText.

答:
Yes you can, you have to use the Spannable class.

```<code>final String yourText = "Your text to be filled";
final int length_you_want = 5;
Spannable modifiedText = new SpannableString(yourText);
modifiedText.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.green)), 0, length_you_want, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(modifiedText);
</code>```

Body:
Yes you can, you have to use the Spannable class.

final String yourText = "Your text to be filled";
final int length_you_want = 5;
Spannable modifiedText = new SpannableString(yourText);
modifiedText.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.green)), 0, length_you_want, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(modifiedText);


问:
Gitignore - ignore a specific file from a specific folder
I am new here and I need some help.
I have a website with this structure:

folder1

folder2

folder3

folder4

folder5

index.php

.gitignore

In folder2 there is a config.php file. How can I ignore that file?
I tried to edit .gitignore file and I add folder2/config.php but git doesn't ignore it.

I also tried from Terminal and Source Tree but without success?

Can you please tell me how can I ignore a specific file from a folder?

Many thanks in advance guys!

答:
If you already have a file checked in, Git will not ignore the file if you add a rule later. You must untrack the file first, by running the following command in your terminal:

git rm --cached FILENAME

git commit -m "Any message"

After that you will not see any changes on that file from git diff or git status.


问:
How can I do paging with @OneToMany collections
Suppose I have a Post entity and a Comment entity and a one to many relationship:

```<code>@Entity class Post {
    ...
    @OneToMany
    List<Comment> comments;
    ...
}
</code>```

How can I achieve paging like this:

```<code>Post post = //Find the post.
return post.getComments().fetch(100, 10); // Find the 11th page (page size 10);
</code>```

Is it possible to emulate dynamic paging with @OneToMany collections on top of JPA,
or do we have to rewrite the association mechanism of JPA totally ? (e.g. create a PersistentList collection type that could manage the paging, sorting and searching).

P.S.: I recently found the Play! framework uses a very interesting lib on top of JPA: Siena. Siena is very easy to use, and is a good abstraction on top of JPA/Hibernate. But I can't find how to do paging with its associations.

Update:

Play framework has a query syntax similar to Django:

```<code>Post.findAll().from(100).fetch(10);  // paging
</code>```

where

```<code>Post.findAll()
</code>```

will return a JPAQuery object, a customized query type in Play.

But with associated collections, e.g.:

```<code>Post.comments
</code>```

will just return a List, which doesn't support paging or other queries.

I was wondering how to extend it, so that

```<code>Post.comments
</code>```

will also return a JPAQuery object or similar, then you can query on the "query" collection:

```<code>Post.comments.from(100).fetch(10);
</code>```

or insert a new Comment without actually fetching any of the comments:

```<code>Post.comments.add(new Comment(...));
</code>```

On my first thought, we could create a subclass of List, then the Post class would become:

```<code>@Entity class Post {
    ...
    @OneToMany
    QueryList<Comment> comments;
    ...
}
</code>```

and QueryList will have fetch(), from() methods that indirect to JPAQuery's.

But I don't know whether Hibernate/JPA will recognize this, or interfere with it.

答:
I think the "right" way might be more like:

```<code>@Entity
class Post {
    ...

    public GenericModel.JPAQuery getComments() {
        return Comment.find("post_id = ?", post_id);
    }
}
</code>```

and then use one of the fetch methods in JPAQuery:

```<code>// fetch first page of results, 25 results per page
post.getComments().fetch(1,25);
</code>```

Body:
Suppose I have a Post entity and a Comment entity and a one to many relationship:

@Entity class Post {
    ...
    @OneToMany
    List<Comment> comments;
    ...
}

How can I achieve paging like this:

Post post = //Find the post.
return post.getComments().fetch(100, 10); // Find the 11th page (page size 10);

Is it possible to emulate dynamic paging with @OneToMany collections on top of JPA,
or do we have to rewrite the association mechanism of JPA totally ? (e.g. create a PersistentList collection type that could manage the paging, sorting and searching).

P.S.: I recently found the Play! framework uses a very interesting lib on top of JPA: Siena. Siena is very easy to use, and is a good abstraction on top of JPA/Hibernate. But I can't find how to do paging with its associations.

Update:

Play framework has a query syntax similar to Django:

Post.findAll().from(100).fetch(10);  // paging

where

Post.findAll()

will return a JPAQuery object, a customized query type in Play.

But with associated collections, e.g.:

Post.comments

will just return a List, which doesn't support paging or other queries.

I was wondering how to extend it, so that

Post.comments

will also return a JPAQuery object or similar, then you can query on the "query" collection:

Post.comments.from(100).fetch(10);

or insert a new Comment without actually fetching any of the comments:

Post.comments.add(new Comment(...));

On my first thought, we could create a subclass of List, then the Post class would become:

@Entity class Post {
    ...
    @OneToMany
    QueryList<Comment> comments;
    ...
}

and QueryList will have fetch(), from() methods that indirect to JPAQuery's.

But I don't know whether Hibernate/JPA will recognize this, or interfere with it.

Body:
I think the "right" way might be more like:

@Entity
class Post {
    ...

    public GenericModel.JPAQuery getComments() {
        return Comment.find("post_id = ?", post_id);
    }
}

and then use one of the fetch methods in JPAQuery:

// fetch first page of results, 25 results per page
post.getComments().fetch(1,25);


问:
How do I define a swagger spec for 2 apis with same base path but different request structures?
Example:

This is the first definition:

```<code>/**
 * @swagger
 * /a/b/items:
 *   get:
 *     description: Get all the items
 *     responses:
 *      200:
 *          Returns an array of items
 */
</code>```

This is the 2nd definition:

```<code>/**
 * @swagger
 * /a/b/items:
 *   get:
 *     description: Get items by ids
 *     parameters:
 *      - name: ids
 *        in: query
 *        required: true
 *        schema:
 *          $ref: '#/definitions/itemIds'
 *
 *     responses:
 *      200:
 *          description: Returns an array of items, given the itemIds
 */
</code>```

It is clear that, the difference here lies in the request structure.
Note that, for the second definition, I wanna pass the parameter ids in query.

The first definition is a simple get request without any path parameters or query parameters.

The second definition is a get request with same base path but with query params.

When I define these two in succession, the second definition over writes the first one and the Swagger UI shows the second one only.

It's highly desirable to have these two definitions as unique ones.

Any solutions/thoughts/ways to accomplish the uniqueness?

Changing the apis to support documentation is simply a "No go"!

Any help will be much appreciated.
Thanks in advance!

答:
I believe the endpoint in the 2nd definition needs to be changed to:</p>

```<code>/a/b/items/{ids}:
</code>```

Body:
Example:

This is the first definition:

/**
 * @swagger
 * /a/b/items:
 *   get:
 *     description: Get all the items
 *     responses:
 *      200:
 *          Returns an array of items
 */

This is the 2nd definition:

/**
 * @swagger
 * /a/b/items:
 *   get:
 *     description: Get items by ids
 *     parameters:
 *      - name: ids
 *        in: query
 *        required: true
 *        schema:
 *          $ref: '#/definitions/itemIds'
 *
 *     responses:
 *      200:
 *          description: Returns an array of items, given the itemIds
 */

It is clear that, the difference here lies in the request structure.
Note that, for the second definition, I wanna pass the parameter ids in query.

The first definition is a simple get request without any path parameters or query parameters.

The second definition is a get request with same base path but with query params.

When I define these two in succession, the second definition over writes the first one and the Swagger UI shows the second one only.

It's highly desirable to have these two definitions as unique ones.

Any solutions/thoughts/ways to accomplish the uniqueness?

Changing the apis to support documentation is simply a "No go"!

Any help will be much appreciated.
Thanks in advance!

Body:
I believe the endpoint in the 2nd definition needs to be changed to:

/a/b/items/{ids}: