问:
Docker doesn't copy assets folder
I don't have a .dockerignore file but Docker doesn't copy assets folder to the images when building.

project:

assets

models

v1

src

venv

Dockerfile

App.py :

```<code>    import numpy as np
    import tensorflow as tf
                                  [...]
    with open('../assets/model/v1/model_architecture_V1.json', 'r') as f:
        model_json = f.read()

    model.load_weights("../assets/model/v1/model_weight_V1.h5")

                                  [...]

    if __name__ == '__main__':
       app.run(host='0.0.0.0', port=4000, debug=True)
</code>```

Dockerfile:

```<code>    FROM python:3

    WORKDIR /app

    COPY requirements.txt ./
    RUN pip install --no-cache-dir -r requirements.txt

    COPY . .

    CMD ["python3","src/app.py"]
</code>```

When I run the project image,Python throws me this error:

When I run the app without Docker there is no problem.

答:
When you test locally set ../assets/.. is valid. But during the Docker build both Dockerfile and assets folders are located at the same level. So, you have to change the file path as assets/... To handle this efficiently in Python check os.path.join.

```<code>    Step 3/6 : COPY . .
    ---> 49a93d46bdde
    Step 4/6 : RUN ls -lah
     ---> Running in f57d57b59dce
    total 24K
    drwxr-xr-x 1 root root 4.0K May 29 21:21 .
    drwxr-xr-x 1 root root 4.0K May 29 21:21 ..
    -rw-r--r-- 1 root root  168 May 29 21:19 Dockerfile
    drwxr-xr-x 3 root root 4.0K May 29 20:53 assests
    drwxr-xr-x 2 root root 4.0K May 29 21:21 src
    drwxr-xr-x 2 root root 4.0K May 29 20:54 venv

    ---

    with open('assests/models/v1/model_architecture_V1.json', 'r') as f:
       model_json = f.read()
</code>```

Sample output

```<code>docker run harik8/app:latest
{
    "glossary": {
        "title": "example glossary",
                "GlossDiv": {
            "title": "S",
                        "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                                        "SortAs": "SGML",
                                        "GlossTerm": "Standard Generalized Markup Language",
                                        "Acronym": "SGML",
                                        "Abbrev": "ISO 8879:1986",
                                        "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                                                "GlossSeeAlso": ["GML", "XML"]
                    },
                                        "GlossSee": "markup"
                }
            }
        }
    }
}
</code>```

Title: Docker doesn't copy assets folder

Body:
I don't have a .dockerignore file but Docker doesn't copy assets folder to the images when building.

project:

assets

models

v1

src

venv

Dockerfile

App.py :

    import numpy as np
    import tensorflow as tf
                                  [...]
    with open('../assets/model/v1/model_architecture_V1.json', 'r') as f:
        model_json = f.read()

    model.load_weights("../assets/model/v1/model_weight_V1.h5")

                                  [...]

    if __name__ == '__main__':
       app.run(host='0.0.0.0', port=4000, debug=True)

Dockerfile:

    FROM python:3

    WORKDIR /app

    COPY requirements.txt ./
    RUN pip install --no-cache-dir -r requirements.txt

    COPY . .

    CMD ["python3","src/app.py"]

When I run the project image,Python throws me this error:

When I run the app without Docker there is no problem.

Body:
When you test locally set ../assets/.. is valid. But during the Docker build both Dockerfile and assets folders are located at the same level. So, you have to change the file path as assets/... To handle this efficiently in Python check os.path.join.

    Step 3/6 : COPY . .
    ---> 49a93d46bdde
    Step 4/6 : RUN ls -lah
     ---> Running in f57d57b59dce
    total 24K
    drwxr-xr-x 1 root root 4.0K May 29 21:21 .
    drwxr-xr-x 1 root root 4.0K May 29 21:21 ..
    -rw-r--r-- 1 root root  168 May 29 21:19 Dockerfile
    drwxr-xr-x 3 root root 4.0K May 29 20:53 assests
    drwxr-xr-x 2 root root 4.0K May 29 21:21 src
    drwxr-xr-x 2 root root 4.0K May 29 20:54 venv

    ---

    with open('assests/models/v1/model_architecture_V1.json', 'r') as f:
       model_json = f.read()

Sample output

docker run harik8/app:latest
{
    "glossary": {
        "title": "example glossary",
                "GlossDiv": {
            "title": "S",
                        "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                                        "SortAs": "SGML",
                                        "GlossTerm": "Standard Generalized Markup Language",
                                        "Acronym": "SGML",
                                        "Abbrev": "ISO 8879:1986",
                                        "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                                                "GlossSeeAlso": ["GML", "XML"]
                    },
                                        "GlossSee": "markup"
                }
            }
        }
    }
}


来源: stackexchange

问:
jenkinsfile - copy files to s3 and make public
I am uploading a website to an s3 bucket for hosting, I upload from a jenkins build job using this in the jenkins file

```<code>withAWS(credentials:'aws-cred') {

             sh 'npm install'
             sh 'ng build --prod'
             s3Upload(
                       file: 'dist/topic-creation',
                       bucket: 'bucketName',
                       acl:'PublicRead'
                     )
        }

</code>```

After this step I go to the s3 bucket and get the URL (I have configured the bucket for hosting), when i go to the endpoint url I get a 403 error. When i go back to bucket and give all the items that got uploaded public access, then the URL brings me to my website.

I don't want to make the bucket public, I want to give the files public access, I thought adding the line acl:'PublicRead' which can be seen above would do this but it does not.

Can anyone tell me how I can upload the files and give public access from a jenkins file?

Thanks

答:
Install S3Publisher plugin on your Jenkins instance: https://plugins.jenkins.io/s3/

In order to upload the local artifacts with public access onto your S3 bucket , use the following command (You can also use the Jenkins Pipeline Syntax):

def identity=awsIdentity();
s3Upload acl: 'PublicRead', bucket: 'NAME_OF_S3_BUCKET', file: 'THE_ARTIFACT_TO_BE_UPLOADED_FROM_JENKINS', path: "PATH_ON_S3_BUCKET", workingDir: '.'```

In case of a Free-style build, here's a sample:

ContentLicense: CC BY-SA 4.0

Body:
I am uploading a website to an s3 bucket for hosting, I upload from a jenkins build job using this in the jenkins file

withAWS(credentials:'aws-cred') {

             sh 'npm install'
             sh 'ng build --prod'
             s3Upload(
                       file: 'dist/topic-creation',
                       bucket: 'bucketName',
                       acl:'PublicRead'
                     )
        }

After this step I go to the s3 bucket and get the URL (I have configured the bucket for hosting), when i go to the endpoint url I get a 403 error. When i go back to bucket and give all the items that got uploaded public access, then the URL brings me to my website.

I don't want to make the bucket public, I want to give the files public access, I thought adding the line acl:'PublicRead' which can be seen above would do this but it does not.

Can anyone tell me how I can upload the files and give public access from a jenkins file?

Thanks

Body:
Install S3Publisher plugin on your Jenkins instance: https://plugins.jenkins.io/s3/

In order to upload the local artifacts with public access onto your S3 bucket , use the following command (You can also use the Jenkins Pipeline Syntax):

def identity=awsIdentity();
s3Upload acl: 'PublicRead', bucket: 'NAME_OF_S3_BUCKET', file: 'THE_ARTIFACT_TO_BE_UPLOADED_FROM_JENKINS', path: "PATH_ON_S3_BUCKET", workingDir: '.'

In case of a Free-style build, here's a sample:


问:
Dicsord.js server info

const Command = require('../../Structures/Command');
const Discord = require('discord.js');

module.exports = class extends Command {

    constructor(...args) {
        super(...args, {
            aliases: ['mi']
        });
    }

    async run(message, presence) {
        let embed = new Discord.MessageEmbed()
                embed.setAuthor(`Your Name: ` + message.author.username)
                embed.setDescription("Your Info")
                embed.setColor("#FF00FF")
                embed.addField("Username", `${message.author.username}#${message.author.discriminator}`)
                embed.addField("ID", message.author.id)
                embed.addField("Created At", message.author.createdAt)
                embed.addField("You Joined the server at", message.member.joinedAt)
                embed.setFooter("Zorek | Userinfo")
                message.channel.send(embed);
    }

};
```

I really need to know how to make it say what the users playing, someone please help!

答:
You can get the first activity and display that:

message.author.presence.activities[0].name
```

Title: Dicsord.js server info

Body:
const Command = require('../../Structures/Command');
const Discord = require('discord.js');

module.exports = class extends Command {

    constructor(...args) {
        super(...args, {
            aliases: ['mi']
        });
    }

    async run(message, presence) {
        let embed = new Discord.MessageEmbed()
                embed.setAuthor(`Your Name: ` + message.author.username)
                embed.setDescription("Your Info")
                embed.setColor("#FF00FF")
                embed.addField("Username", `${message.author.username}#${message.author.discriminator}`)
                embed.addField("ID", message.author.id)
                embed.addField("Created At", message.author.createdAt)
                embed.addField("You Joined the server at", message.member.joinedAt)
                embed.setFooter("Zorek | Userinfo")
                message.channel.send(embed);
    }

};

I really need to know how to make it say what the users playing, someone please help!


问:
How to handle background uploads with Alamofire 5?
There is a chance that background uploads work with some adaption of the alamofire api and URLSession whit this code:

```<code>Alamofire.upload(
                multipartFormData: { multipartFormData in
                    multipartFormData.append(imageData, withName: "photo[image]", fileName: filename, mimeType: "image/jpg")
            },
                usingThreshold: UInt64(0), // force alamofire to always write to file no matter how small the payload is
                to: "http://", // if we give it a real url sometimes alamofire will attempt the first upload. I don't want to let it get to our servers but it fails if I feed it ""
                method: .post,
                headers: headers,
                encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .success(let alamofireUploadTask, _, let url):
                        alamofireUploadTask.suspend()
                        defer { alamofireUploadTask.cancel() }
                        if let alamofireUploadFileUrl = url {
                            var request = URLRequest(url: URL(string: "https://yourserver.com/photoUploadEndpoint")!)
                            request.httpMethod = "POST"
                            for (key, value) in alamofireUploadTask.request!.allHTTPHeaderFields! { // transfer headers from the request made by alamofire
                                request.addValue(value, forHTTPHeaderField: key)
                            }
                            // we want to own the multipart file to avoid alamofire deleting it when we tell it to cancel its task
                            // so copy file on alamofireUploadFileUrl to a file you control
                            // dispatch the request to the background session
                            // don't forget to delete the file when you're done uploading
                        } else {
                            // alamofire failed to encode the request file for some reason
                        }
                    case .failure:
                        // alamofire failed to encode the request file for some reason
                    }
            }
            )
</code>```

Unfortunately this wont work with Alamofire 5, is there a way to adapt this?

答:
Alamofire 5 doesn't support background URLSessionConfigurations, but the code you posted is just a multipart upload, which is still supported just fine.

Your various hackery around the upload should be reevaluated for the new version of Alamofire. It really doesn't make any sense.

Alamofire does work with background tasks, which can give you time to finish uploads. You can read more here.

Body:
There is a chance that background uploads work with some adaption of the alamofire api and URLSession whit this code:

Alamofire.upload(
                multipartFormData: { multipartFormData in
                    multipartFormData.append(imageData, withName: "photo[image]", fileName: filename, mimeType: "image/jpg")
            },
                usingThreshold: UInt64(0), // force alamofire to always write to file no matter how small the payload is
                to: "http://", // if we give it a real url sometimes alamofire will attempt the first upload. I don't want to let it get to our servers but it fails if I feed it ""
                method: .post,
                headers: headers,
                encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .success(let alamofireUploadTask, _, let url):
                        alamofireUploadTask.suspend()
                        defer { alamofireUploadTask.cancel() }
                        if let alamofireUploadFileUrl = url {
                            var request = URLRequest(url: URL(string: "https://yourserver.com/photoUploadEndpoint")!)
                            request.httpMethod = "POST"
                            for (key, value) in alamofireUploadTask.request!.allHTTPHeaderFields! { // transfer headers from the request made by alamofire
                                request.addValue(value, forHTTPHeaderField: key)
                            }
                            // we want to own the multipart file to avoid alamofire deleting it when we tell it to cancel its task
                            // so copy file on alamofireUploadFileUrl to a file you control
                            // dispatch the request to the background session
                            // don't forget to delete the file when you're done uploading
                        } else {
                            // alamofire failed to encode the request file for some reason
                        }
                    case .failure:
                        // alamofire failed to encode the request file for some reason
                    }
            }
            )

Unfortunately this wont work with Alamofire 5, is there a way to adapt this?


问:
Android: CollapsingToolbarLayout centers expanded text but not collapsed text
I have a CollapsingToolbarLayout that is defined to center both in collapsed and in expanded modes:

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="286dp">

<android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsingToolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:collapsedTitleGravity="center"
        app:expandedTitleGravity="center"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <ImageView
                android:id="@+id/backgroundImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:contentDescription="@null"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="pin"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"/>

            <ImageView
                android:id="@+id/someIcon"
                android:layout_width="56dp"
                android:layout_height="wrap_content"
                android:src="@drawable/some_icon"
                android:padding="16dp"
                android:layout_gravity="top|end"
                app:layout_collapseMode="pin"/>
 </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

I define a title for the toolbar but when I collapse it I can see the title moving in a diagonal direction instead of straight up and it aligns itself slightly to the right of the center of the toolbar line. Notice that the width is match_parent and the collapsed gravity is center, so why could this be happening and how should I fix it?

• First screenshot: what it looks like if I use collapse -> center and expanded -> center gravities and then collapse the layout. Notice that it's to the right of the center of the screen.

• Second screenshot: what it looks like if I get rid of collapse -> center gravity but leave expanded -> center gravity and then collapse the layout. Notice that it's aligned left by default.

• Third screenshot: what it looks like expanded

Things that I've tried so far to solve this (without success):

• Getting rid of the collapsedGravity and leaving only the expandedGravity

• Using the default roboto font for the title

• Setting padding and margins to 0 for both the toolbar and the collapsing layout

• setting gravity center_horizontal instead of center

Edit:

The only workaround I've found that makes this work properly is to use a separate textview to hold the title instead of setting the title for the collapsingtoolbarlayout (this makes the title collapse properly to the center). This isn't optimal so I'd appreciate knowing if the CPL has a bug in it or if there's a way to use the default title to do the same thing.

答:
Setting content related properties to 0dp (app:contentInsetLeft="0dp", android:contentInsetLeft="0dp", app:contentInsetStart="0dp", android:contentInsetStart="0dp", app:contentInsetStartWithNavigation="0dp") might help you. Here is my working Toolbar.

```<code><com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:collapsedTitleGravity="center|center_horizontal"
        app:collapsedTitleTextAppearance="@style/CollapsedAppBar"
        app:expandedTitleTextAppearance="@style/ExpandedAppBar"
        app:statusBarScrim="@color/colorPrimaryDark"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleMargin="@dimen/large_padding"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/comImage1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            android:src="@drawable/bg"
            android:fitsSystemWindows="true"
            app:layout_collapseMode="parallax"
            app:layout_collapseParallaxMultiplier="0.7" />

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            app:contentInsetLeft="0dp"
            android:contentInsetLeft="0dp"
            app:contentInsetStartWithNavigation="0dp"
            app:contentInsetStart="0dp"
            android:contentInsetStart="0dp"
            app:theme="@style/ToolbarTheme"
            android:gravity="center_horizontal"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:titleMargin="0dp"/>
    </com.google.android.material.appbar.CollapsingToolbarLayout>
</code>```

Hope it will help :)

ContentLicense: CC BY-SA 3.0

Body:
I have a CollapsingToolbarLayout that is defined to center both in collapsed and in expanded modes:

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="286dp">

<android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsingToolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:collapsedTitleGravity="center"
        app:expandedTitleGravity="center"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <ImageView
                android:id="@+id/backgroundImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:contentDescription="@null"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="pin"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"/>

            <ImageView
                android:id="@+id/someIcon"
                android:layout_width="56dp"
                android:layout_height="wrap_content"
                android:src="@drawable/some_icon"
                android:padding="16dp"
                android:layout_gravity="top|end"
                app:layout_collapseMode="pin"/>
 </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

I define a title for the toolbar but when I collapse it I can see the title moving in a diagonal direction instead of straight up and it aligns itself slightly to the right of the center of the toolbar line. Notice that the width is match_parent and the collapsed gravity is center, so why could this be happening and how should I fix it?

• First screenshot: what it looks like if I use collapse -> center and expanded -> center gravities and then collapse the layout. Notice that it's to the right of the center of the screen.

• Second screenshot: what it looks like if I get rid of collapse -> center gravity but leave expanded -> center gravity and then collapse the layout. Notice that it's aligned left by default.

• Third screenshot: what it looks like expanded

Things that I've tried so far to solve this (without success):

• Getting rid of the collapsedGravity and leaving only the expandedGravity

• Using the default roboto font for the title

• Setting padding and margins to 0 for both the toolbar and the collapsing layout

• setting gravity center_horizontal instead of center

Edit:

The only workaround I've found that makes this work properly is to use a separate textview to hold the title instead of setting the title for the collapsingtoolbarlayout (this makes the title collapse properly to the center). This isn't optimal so I'd appreciate knowing if the CPL has a bug in it or if there's a way to use the default title to do the same thing.

Body:
Setting content related properties to 0dp (app:contentInsetLeft="0dp", android:contentInsetLeft="0dp", app:contentInsetStart="0dp", android:contentInsetStart="0dp", app:contentInsetStartWithNavigation="0dp") might help you. Here is my working Toolbar.

<com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:collapsedTitleGravity="center|center_horizontal"
        app:collapsedTitleTextAppearance="@style/CollapsedAppBar"
        app:expandedTitleTextAppearance="@style/ExpandedAppBar"
        app:statusBarScrim="@color/colorPrimaryDark"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleMargin="@dimen/large_padding"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/comImage1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            android:src="@drawable/bg"
            android:fitsSystemWindows="true"
            app:layout_collapseMode="parallax"
            app:layout_collapseParallaxMultiplier="0.7" />

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            app:contentInsetLeft="0dp"
            android:contentInsetLeft="0dp"
            app:contentInsetStartWithNavigation="0dp"
            app:contentInsetStart="0dp"
            android:contentInsetStart="0dp"
            app:theme="@style/ToolbarTheme"
            android:gravity="center_horizontal"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:titleMargin="0dp"/>
    </com.google.android.material.appbar.CollapsingToolbarLayout>

Hope it will help :)


问:
How to add toastr JS notification on application level in Ruby on Rails
I am using toastr gem for my notifications. I am trying to add a toastr notification to my application whenever a method on my application_controller.rb is active.

```<code>rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

    def user_not_authorized
      toastr.info('You cannot access this page.', 'info')
      redirect_to contacts_path
    end
</code>```

As you can see I tried to add toastrfunction on my controller, however this doesn't work. How can I show this toastr notification whenever this method hits or simply whenever a non-admin user access an unathorized page?

答:
toastr is a Javascript library and you can't use it within Ruby code.

However, if you want to show some kind of notifications to a user and define them in the context of a Rails controller, you can make use of Rails Flash Notifications.

In the application_controller.rb file:

```<code>rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

def user_not_authorized
  flash[:notice] = "You cannot access this page."
  redirect_to contacts_path
end
</code>```

And somewhere in your HTML/ERB file, you would render the HTML elements for each one of the the flash notifications set in the controllers:

```<code><html>
  <!-- <head/> -->
  <body>
    <% flash.each do |name, msg| -%>
      <%= content_tag :div, msg, class: name %>
    <% end -%>

    <!-- more content -->
  </body>
</html>
</code>```

You can consult more example of its usage in the link above.

Body:
I am using toastr gem for my notifications. I am trying to add a toastr notification to my application whenever a method on my application_controller.rb is active.

rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

    def user_not_authorized
      toastr.info('You cannot access this page.', 'info')
      redirect_to contacts_path
    end

As you can see I tried to add toastrfunction on my controller, however this doesn't work. How can I show this toastr notification whenever this method hits or simply whenever a non-admin user access an unathorized page?

Body:
toastr is a Javascript library and you can't use it within Ruby code.

However, if you want to show some kind of notifications to a user and define them in the context of a Rails controller, you can make use of Rails Flash Notifications.

In the application_controller.rb file:

rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

def user_not_authorized
  flash[:notice] = "You cannot access this page."
  redirect_to contacts_path
end

And somewhere in your HTML/ERB file, you would render the HTML elements for each one of the the flash notifications set in the controllers:

<html>
  <!-- <head/> -->
  <body>
    <% flash.each do |name, msg| -%>
      <%= content_tag :div, msg, class: name %>
    <% end -%>

    <!-- more content -->
  </body>
</html>

You can consult more example of its usage in the link above.


问:
count(): Parameter must be an array or an object that implements Countable
I'm facing strange case. I face an error in production env not while in dev it's working fine.

Development:
Laravel 5.4.28
PHP 7.0.13
MYSQL 5.7.17

Production:
Laravel 5.4.28
PHP 7.2.1
MYSQL 5.7.20

In implementation code. I used:

```<code>namespace App;
use Illuminate\Support\Facades\Storage;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;

class Artwork extends Model
{
  use Searchable;
</code>```

In development it works fine. But in production it gives me this error:
count(): Parameter must be an array or an object that implements Countable
in Builder.php (line 936)

as you can see in this pic:

Any idea what is the reason behind this? and how to fix?

答:
i ran into the same problem (PHP 7.2 + Laravel 5.3) but i don't see any "good" answers here. For me, the problem occurs when i tried to start a Builder from a scope method on the model: SomeModel::forUser() calls scopeForUser(). Trying to build a new Query, it trips on a count($this->wheres) that gets no initial value (null). Because the magic static call to the scope starts the builder, no other conditions have been placed in the object so the property is still null at that point.

i thought it's worth sharing my solution first, then perspective on why i consider it better than Ben's answer. It's not personal, i just disagree.

Solution

i took a cue from this answer about overriding some of the core Illuminate\Database classes...

Extend Illuminate\Database\Eloquent\Model

Mine is App\Overrides\Database\Eloquent\Model

Extend Illuminate\Database\Eloquent\Builder

Mine is App\Overrides\Database\Eloquent\Builder

Extend Illuminate\Database\Query\Builder

Can you guess? App\Overrides\Database\Query\Builder

Tell Laravel to use YOUR Eloquent\Model:

config/app.php 'aliases' array, replace the 'Eloquent' value

with your Eloquent\Model FQN

My Model:

namespace App\Overrides\Database\Eloquent;

/*
 * Notes:
 * * Using replacement Query\Builder with ALIAS
 * * Use of Builder in this class is MY Eloquent\Builder
 */
use App\Overrides\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Model as EloquentModel;

class Model extends EloquentModel
{
    public function newEloquentBuilder($query)
    {
        return new Builder($query);
    }

    protected function newBaseQueryBuilder()
    {
        $conn = $this->getConnection();

        $grammar = $conn->getQueryGrammar();

        return new QueryBuilder($conn, $grammar, $conn->getPostProcessor());
    }
}
```
<p>My <code>Eloquent\Builder</code>:</p>
<pre class="lang-php prettyprint-override"><code>namespace App\Overrides\Database\Eloquent;

use Illuminate\Database\Eloquent\Builder as EloquentBuilder;

class Builder extends EloquentBuilder
{
    public function __construct($query)
    {
        parent::__construct($query);

        /*
         * FIX #1: Set properties treated AS arrays
         *         to empty arrays on construct.
         */
        $this->wheres = [];
        // Any other properties treated as arrays should also be initialized.
    }
}

</code>```

My Query\Builder:

namespace App\Overrides\Database\Query;

use Illuminate\Database\Query\Builder as QueryBuilder;

class Builder extends QueryBuilder
{
    public function __construct()
    {
        parent::__construct(...func_get_args());

        /*
         * FIX #2: Set properties treated AS arrays
         *         to empty arrays on construct.
         */
        $this->wheres = [];
        // Any other properties treated as arrays should also be initialized.
    }
}

```

This safely preserves the framework's functionality, since the only actual change you're making is initializing properties that should have been in the first place. Everything else will pass instanceof checks used for dynamic loading and dependency injection.

Opinion

While i agree with @ben-harold about every comment he made saying "NEVER edit vendor code," i disagree with the "solution." It's an oversimplification to a much more complex problem.

Upgrade Laravel: to ensure support for PHP 7.2, jumping up several minor versions - if not major releases - is impractical for a lot of teams. As a long term objective, yes of course. As something i can do to get rid of the bug for my deadline? Nope. Upgrading takes a lot of planning and frequently a lot of rewrites as structures, names, and functionality change. It's something to prioritize, but not a need-it-now answer.

Downgrade PHP: same problem. Downgrading into PHP 5.x means A) PHP is EOL, which may be a deal breaker for a lot of customers who have security policies, and B) any usage of PHP 7.x language features have to be scrapped. As with upgrading the framework this is very likely to cause a lot of headaches. It's also an even less useful solution, since walking backward in the language just puts you farther behind and will require more long-term effort.

Body:
I'm facing strange case. I face an error in production env not while in dev it's working fine.

Development:
Laravel 5.4.28
PHP 7.0.13
MYSQL 5.7.17

Production:
Laravel 5.4.28
PHP 7.2.1
MYSQL 5.7.20

In implementation code. I used:

namespace App;
use Illuminate\Support\Facades\Storage;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;

class Artwork extends Model
{
  use Searchable;

In development it works fine. But in production it gives me this error:
count(): Parameter must be an array or an object that implements Countable
in Builder.php (line 936)

as you can see in this pic:

Any idea what is the reason behind this? and how to fix?

Body:
i ran into the same problem (PHP 7.2 + Laravel 5.3) but i don't see any "good" answers here. For me, the problem occurs when i tried to start a Builder from a scope method on the model: SomeModel::forUser() calls scopeForUser(). Trying to build a new Query, it trips on a count($this->wheres) that gets no initial value (null). Because the magic static call to the scope starts the builder, no other conditions have been placed in the object so the property is still null at that point.

i thought it's worth sharing my solution first, then perspective on why i consider it better than Ben's answer. It's not personal, i just disagree.

Solution

i took a cue from this answer about overriding some of the core Illuminate\Database classes...

Extend Illuminate\Database\Eloquent\Model

Mine is App\Overrides\Database\Eloquent\Model

Extend Illuminate\Database\Eloquent\Builder

Mine is App\Overrides\Database\Eloquent\Builder

Extend Illuminate\Database\Query\Builder

Can you guess? App\Overrides\Database\Query\Builder

Tell Laravel to use YOUR Eloquent\Model:

config/app.php 'aliases' array, replace the 'Eloquent' value

with your Eloquent\Model FQN

My Model:

namespace App\Overrides\Database\Eloquent;

/*
 * Notes:
 * * Using replacement Query\Builder with ALIAS
 * * Use of Builder in this class is MY Eloquent\Builder
 */
use App\Overrides\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Model as EloquentModel;

class Model extends EloquentModel
{
    public function newEloquentBuilder($query)
    {
        return new Builder($query);
    }

    protected function newBaseQueryBuilder()
    {
        $conn = $this->getConnection();

        $grammar = $conn->getQueryGrammar();

        return new QueryBuilder($conn, $grammar, $conn->getPostProcessor());
    }
}

My Eloquent\Builder:

namespace App\Overrides\Database\Eloquent;

use Illuminate\Database\Eloquent\Builder as EloquentBuilder;

class Builder extends EloquentBuilder
{
    public function __construct($query)
    {
        parent::__construct($query);

        /*
         * FIX #1: Set properties treated AS arrays
         *         to empty arrays on construct.
         */
        $this->wheres = [];
        // Any other properties treated as arrays should also be initialized.
    }
}

My Query\Builder:

namespace App\Overrides\Database\Query;

use Illuminate\Database\Query\Builder as QueryBuilder;

class Builder extends QueryBuilder
{
    public function __construct()
    {
        parent::__construct(...func_get_args());

        /*
         * FIX #2: Set properties treated AS arrays
         *         to empty arrays on construct.
         */
        $this->wheres = [];
        // Any other properties treated as arrays should also be initialized.
    }
}

This safely preserves the framework's functionality, since the only actual change you're making is initializing properties that should have been in the first place. Everything else will pass instanceof checks used for dynamic loading and dependency injection.

Opinion

While i agree with @ben-harold about every comment he made saying "NEVER edit vendor code," i disagree with the "solution." It's an oversimplification to a much more complex problem.

Upgrade Laravel: to ensure support for PHP 7.2, jumping up several minor versions - if not major releases - is impractical for a lot of teams. As a long term objective, yes of course. As something i can do to get rid of the bug for my deadline? Nope. Upgrading takes a lot of planning and frequently a lot of rewrites as structures, names, and functionality change. It's something to prioritize, but not a need-it-now answer.

Downgrade PHP: same problem. Downgrading into PHP 5.x means A) PHP is EOL, which may be a deal breaker for a lot of customers who have security policies, and B) any usage of PHP 7.x language features have to be scrapped. As with upgrading the framework this is very likely to cause a lot of headaches. It's also an even less useful solution, since walking backward in the language just puts you farther behind and will require more long-term effort.


问:
Cannot read property 'bindingStartIndex' of null | ionic & angular

test1 is my angular library and appOne & appTow is my ionc+angular application. I want to share the test1 library in my all application. but I can't do that. please help me

Error

Workspace structure

this is ionic.config.json of the workspace root directory

```<code>    {
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "test1": [
        "dist/test1/test1",
        "dist/test1"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}
</code>```

this ionic.config.json of the app root directory

```<code>    {
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "test1": [
        "../../dist/test1/test1",
        "../../dist/test1"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}
</code>```

this home module

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { HomePage } from './home.page';

import { HomePageRoutingModule } from './home-routing.module';
import { Test1Module } from 'test1';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    HomePageRoutingModule,
    Test1Module
  ],
  declarations: [HomePage]
})
export class HomePageModule {}
</code>```

this is home component

```<code> <ion-header [translucent]="true">
      <ion-toolbar>
        <ion-title>
          Blank
        </ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content [fullscreen]="true">
      <ion-header collapse="condense">
        <ion-toolbar>
          <ion-title size="large">Blank</ion-title>
        </ion-toolbar>
      </ion-header>

      <div id="container">
        <lib-test1></lib-test1>
        <strong>Ready to create an app?</strong>
        <p>Start with Ionic <a target="_blank" rel="noopener noreferrer"
       href="https://ionicframework.com/docs/components">UI Components</a></p>
      </div>
    </ion-content>
</code>```

please help me

答: if you put it in your app component it will be shared through the entire app. Good Luck!</p>

Body:
test1 is my angular library and appOne & appTow is my ionc+angular application. I want to share the test1 library in my all application. but I can't do that. please help me

Error

Workspace structure

this is ionic.config.json of the workspace root directory

    {
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "test1": [
        "dist/test1/test1",
        "dist/test1"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

this ionic.config.json of the app root directory

    {
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "test1": [
        "../../dist/test1/test1",
        "../../dist/test1"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

this home module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { HomePage } from './home.page';

import { HomePageRoutingModule } from './home-routing.module';
import { Test1Module } from 'test1';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    HomePageRoutingModule,
    Test1Module
  ],
  declarations: [HomePage]
})
export class HomePageModule {}

this is home component

 <ion-header [translucent]="true">
      <ion-toolbar>
        <ion-title>
          Blank
        </ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content [fullscreen]="true">
      <ion-header collapse="condense">
        <ion-toolbar>
          <ion-title size="large">Blank</ion-title>
        </ion-toolbar>
      </ion-header>

        <lib-test1></lib-test1>
        Ready to create an app?

Start with Ionic UI Components

    </ion-content>

please help me


问:
how i can merge words from list to new list that in each index, store k content from old list
i try to do it on pyton, but i am new in this language.

lets say k=3
and we have split array like:

```<code>The, sky, is, blue, and, the, sun, is, bright
</code>```

what i want to get is to put in each index on the new list k words from the original list.

```<code>index 0: The sky is
index 1: blue and the
index 2: sun is bright
</code>```

this is what i do:

```<code>for i in range(len(mylist) - k + 1):
  ren=i+k-1
  for j in range(ren):
     newListWithKLenOfWord.insert(i, mylist[j] + " ")
</code>```

but i dont no why its not work for me.
in java what i think for this problem is:

```<code>for i to n-k
for j+i to i+k
arr[i] =arr[i] + arr[j]
</code>```

thanks.

答:
Try this:

new_words = [' '.join(words[i:i+3]) for i in range(0,len(words), 3)]
```

Body:
i try to do it on pyton, but i am new in this language.

lets say k=3
and we have split array like:

The, sky, is, blue, and, the, sun, is, bright

what i want to get is to put in each index on the new list k words from the original list.

index 0: The sky is
index 1: blue and the
index 2: sun is bright

this is what i do:

for i in range(len(mylist) - k + 1):
  ren=i+k-1
  for j in range(ren):
     newListWithKLenOfWord.insert(i, mylist[j] + " ")

but i dont no why its not work for me.
in java what i think for this problem is:

for i to n-k
for j+i to i+k
arr[i] =arr[i] + arr[j]

thanks.


问:
Google Sheets - Find and replace specific characters in a cell
I need to find some specific characters in a cell and replace them with other characters.
So far I can do that by using :

```<code>=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"★","•",0),"<b>","",0),"</b>","",0),"✔ ","",0)
</code>```

However, this formula will become very long if I need to replace a lot of characters. Is there any way to reduce the duplicate parts, especially when I need to replace some characters with only the other one. Ex: Replace , , ✔ with "" as example above.
Demo sheet: https://docs.google.com/spreadsheets/d/1wX9mEykCMjeotTRTg_jSMcm9Mm7WM0kPTetRwGLzaYU/edit#gid=0

答:
Google Sheets (but not Excel) has a handy formula, REGEXREPLACE, that will let you do what you need:

```<code>=SUBSTITUTE(REGEXREPLACE(A1,"<b>|</b>|✔",""),"★","•")
</code>```

If you need to remove any more characters, just add them after the checkmark, separated by |.

Body:
I need to find some specific characters in a cell and replace them with other characters.
So far I can do that by using :

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"★","•",0),"","",0),"","",0),"✔ ","",0)

However, this formula will become very long if I need to replace a lot of characters. Is there any way to reduce the duplicate parts, especially when I need to replace some characters with only the other one. Ex: Replace , , ✔ with "" as example above.
Demo sheet: https://docs.google.com/spreadsheets/d/1wX9mEykCMjeotTRTg_jSMcm9Mm7WM0kPTetRwGLzaYU/edit#gid=0

Body:
Google Sheets (but not Excel) has a handy formula, REGEXREPLACE, that will let you do what you need:

=SUBSTITUTE(REGEXREPLACE(A1,"<b>|</b>|✔",""),"★","•")

If you need to remove any more characters, just add them after the checkmark, separated by |.


问:
Why do I have to sync a bidirectional relationship even with CascadeType.PERSIST using Spring Data JPA
Here is an example code demonstrating the issue:

The Meal Entity:

@Entity
public class Meal {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @OneToMany(mappedBy = "meal", cascade = CascadeType.PERSIST)
  private Collection<Food> foods;

  public Meal() {
    foods = new HashSet<>();
  }

  public Collection<Food> getFoods() {
    return foods;
  }

  public void addFood(Food food) {
    foods.add(food);
    // without this the `meal_id` column is null
    food.setMeal(this);
  }
}
```

<p>The Food Entity:</p>

<pre class="lang-java prettyprint-override"><code>@Entity
public class Food {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @ManyToOne
  private Meal meal;

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public Meal getMeal() {
    return meal;
  }

  public void setMeal(Meal meal) {
    this.meal = meal;
  }
}

</code>```

And here is the code that creates and saves the entities:

Meal meal = new Meal();

for (int i = 0; i < 10; i++) {
  meal.addFood(new Food());
}

mealRepository.save(meal);
```

Both the Meal and the Food entities are persisted thanks to the CascadeType.PERSIST, but the meal_id column stays null if I don't explicitly set the meal field to the Meal entity.

This is not the behavior I'd expect, and I'm wondering why isn't this automatically done for me.

答:
@Entity
public class Meal {

  @OneToMany(mappedBy = "meal", cascade = CascadeType.PERSIST)
  private Collection<Food> foods;

}
```
<p>The <code>mappedBy</code> here means that the value of <code>meal</code> field in <code>Food</code> is used to provide the value for the corresponding database column that link between <code>Food</code> and <code>Meal</code> (i.e. <code>meal_id</code> column in <code>Food</code> table). So if you do not set it, it will always remain NULL.</p>
<p>On the other hand, without <code>mappedBy</code> means that the value of the <code>foods</code> field in <code>Meal</code> is used to provide the value for <code>meal_id</code> column. The reason of manually syncing them is just to have a consistent OOP model to work with.</p>
<p><code>CascadeType.PERSIST</code> is nothing to do with setting the value of the entity. It will never update the value of the entities for you. What it helps is to automatically calling some <code>entityManager</code> methods on the related entities. Without it, you have to call the following to save all Food and Meal:</p>
<pre class="lang-java prettyprint-override"><code>entityManager.persist(meal);
entityManager.persist(food1);
entityManager.persist(food2);
......
entityManager.persist(foodN);
</code>```

With it , you just need to call

entityManager.persist(meal);
```
<p>and the rest of <code>entityManager.persist(foodN)</code> will be 'cascaded' to call automatically.</p>
<p>So in term of spring-data-jpa , instead of calling</p>
<pre class="lang-java prettyprint-override"><code>mealRepository.save(meal);
foodRepository.persist(food1);
foodRepository.persist(food2);
......
foodRepository.persist(foodN);
</code>```

You just need to call

mealRepository.save(meal);
```

Body:
Here is an example code demonstrating the issue:

The Meal Entity:

@Entity
public class Meal {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @OneToMany(mappedBy = "meal", cascade = CascadeType.PERSIST)
  private Collection<Food> foods;

  public Meal() {
    foods = new HashSet<>();
  }

  public Collection<Food> getFoods() {
    return foods;
  }

  public void addFood(Food food) {
    foods.add(food);
    // without this the `meal_id` column is null
    food.setMeal(this);
  }
}

The Food Entity:

@Entity
public class Food {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @ManyToOne
  private Meal meal;

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public Meal getMeal() {
    return meal;
  }

  public void setMeal(Meal meal) {
    this.meal = meal;
  }
}

And here is the code that creates and saves the entities:

Meal meal = new Meal();

for (int i = 0; i < 10; i++) {
  meal.addFood(new Food());
}

mealRepository.save(meal);

Both the Meal and the Food entities are persisted thanks to the CascadeType.PERSIST, but the meal_id column stays null if I don't explicitly set the meal field to the Meal entity.

This is not the behavior I'd expect, and I'm wondering why isn't this automatically done for me.

Body:
@Entity
public class Meal {

  @OneToMany(mappedBy = "meal", cascade = CascadeType.PERSIST)
  private Collection<Food> foods;

}

The mappedBy here means that the value of meal field in Food is used to provide the value for the corresponding database column that link between Food and Meal (i.e. meal_id column in Food table). So if you do not set it, it will always remain NULL.

On the other hand, without mappedBy means that the value of the foods field in Meal is used to provide the value for meal_id column. The reason of manually syncing them is just to have a consistent OOP model to work with.

CascadeType.PERSIST is nothing to do with setting the value of the entity. It will never update the value of the entities for you. What it helps is to automatically calling some entityManager methods on the related entities. Without it, you have to call the following to save all Food and Meal:

entityManager.persist(meal);
entityManager.persist(food1);
entityManager.persist(food2);
......
entityManager.persist(foodN);

With it , you just need to call

entityManager.persist(meal);

and the rest of entityManager.persist(foodN) will be 'cascaded' to call automatically.

So in term of spring-data-jpa , instead of calling

mealRepository.save(meal);
foodRepository.persist(food1);
foodRepository.persist(food2);
......
foodRepository.persist(foodN);

You just need to call

mealRepository.save(meal);


问:
Getting serialization exception for super class - PersistentStateRef while creating custom schema
Hello Corda team/Roger,

I have implemented custom schema based on the example of Yo schema, however i am getting Kyro exception with message Buffer underflow.

I have added @cordaseriliazation annotation in Schema class as well as entity class which extends PersistentStateRef

In Plugin Registry class, I have overriden this method:

```<code>@Override
public boolean customizeSerialization(SerializationCustomization kryo) {
        kryo.addToWhitelist(PersistentStateRef.class);
      return true;
}
</code>```

Here is the stacktrace:

```<code>[ERROR] 2017-07-21T14:52:51,407 [Thread-0 (ActiveMQ-client-global-threads)] core.client.run - AMQ214000: Failed to call onMessage
com.esotericsoftware.kryo.KryoException: Buffer underflow.
    at com.esotericsoftware.kryo.io.Input.require(Input.java:199) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.io.Input.readVarInt(Input.java:373) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.util.DefaultClassResolver.readClass(DefaultClassResolver.java:127) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.Kryo.readClass(Kryo.java:693) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.serializers.DefaultArraySerializers$ObjectArraySerializer.read(DefaultArraySerializers.java:389) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.serializers.DefaultArraySerializers$ObjectArraySerializer.read(DefaultArraySerializers.java:303) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:813) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:134) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:40) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:813) ~[kryo-4.0.0.jar:?]
    at net.corda.core.serialization.KryoKt$deserialize$1$1.execute(Kryo.kt:109) ~[corda-core-0.13.0.jar:?]
    at com.esotericsoftware.kryo.pool.KryoPoolQueueImpl.run(KryoPoolQueueImpl.java:61) ~[kryo-4.0.0.jar:?]
    at net.corda.core.serialization.KryoKt.deserialize(Kryo.kt:109) ~[corda-core-0.13.0.jar:?]
    at net.corda.nodeapi.RPCApi$ClientToServer$Companion.fromClientMessage(RPCApi.kt:124) ~[corda-node-api-0.13.0.jar:?]
    at net.corda.node.services.messaging.RPCServer.clientArtemisMessageHandler(RPCServer.kt:264) ~[corda-node-0.13.0.jar:?]
    at net.corda.node.services.messaging.RPCServer.access$clientArtemisMessageHandler(RPCServer.kt:76) ~[corda-node-0.13.0.jar:?]
    at net.corda.node.services.messaging.RPCServer$createConsumerSessions$1.invoke(RPCServer.kt:190) ~[corda-node-0.13.0.jar:?]
    at net.corda.node.services.messaging.RPCServer$createConsumerSessions$1.invoke(RPCServer.kt:76) ~[corda-node-0.13.0.jar:?]
    at net.corda.node.services.messaging.RPCServerKt$sam$MessageHandler$086628f7.onMessage(RPCServer.kt) ~[corda-node-0.13.0.jar:?]
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.callOnMessage(ClientConsumerImpl.java:997) ~[artemis-core-client-2.1.0.jar:2.1.0]
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.access$400(ClientConsumerImpl.java:49) ~[artemis-core-client-2.1.0.jar:2.1.0]
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl$Runner.run(ClientConsumerImpl.java:1120) [artemis-core-client-2.1.0.jar:2.1.0]
    at org.apache.activemq.artemis.utils.OrderedExecutorFactory$OrderedExecutor$ExecutorTask.run(OrderedExecutorFactory.java:101) [artemis-commons-2.1.0.jar:2.1.0]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_131]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_131]
</code>```

答:
This definitely seems like it was an issue in the corda flow processing given it was presenting AMQP errors.

I'd take another look at what's happening when you run flows that use this schema in the latest version of corda and see if they give similar issues.

If you continue to face it it's probably a Corda bug and not you, you can report issues to corda on here: https://github.com/corda/corda/issues

Body:
Hello Corda team/Roger,

I have implemented custom schema based on the example of Yo schema, however i am getting Kyro exception with message Buffer underflow.

I have added @cordaseriliazation annotation in Schema class as well as entity class which extends PersistentStateRef

In Plugin Registry class, I have overriden this method:

@Override
public boolean customizeSerialization(SerializationCustomization kryo) {
        kryo.addToWhitelist(PersistentStateRef.class);
      return true;
}

Here is the stacktrace:

[ERROR] 2017-07-21T14:52:51,407 [Thread-0 (ActiveMQ-client-global-threads)] core.client.run - AMQ214000: Failed to call onMessage
com.esotericsoftware.kryo.KryoException: Buffer underflow.
    at com.esotericsoftware.kryo.io.Input.require(Input.java:199) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.io.Input.readVarInt(Input.java:373) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.util.DefaultClassResolver.readClass(DefaultClassResolver.java:127) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.Kryo.readClass(Kryo.java:693) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.serializers.DefaultArraySerializers$ObjectArraySerializer.read(DefaultArraySerializers.java:389) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.serializers.DefaultArraySerializers$ObjectArraySerializer.read(DefaultArraySerializers.java:303) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:813) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:134) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:40) ~[kryo-4.0.0.jar:?]
    at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:813) ~[kryo-4.0.0.jar:?]
    at net.corda.core.serialization.KryoKt$deserialize$1$1.execute(Kryo.kt:109) ~[corda-core-0.13.0.jar:?]
    at com.esotericsoftware.kryo.pool.KryoPoolQueueImpl.run(KryoPoolQueueImpl.java:61) ~[kryo-4.0.0.jar:?]
    at net.corda.core.serialization.KryoKt.deserialize(Kryo.kt:109) ~[corda-core-0.13.0.jar:?]
    at net.corda.nodeapi.RPCApi$ClientToServer$Companion.fromClientMessage(RPCApi.kt:124) ~[corda-node-api-0.13.0.jar:?]
    at net.corda.node.services.messaging.RPCServer.clientArtemisMessageHandler(RPCServer.kt:264) ~[corda-node-0.13.0.jar:?]
    at net.corda.node.services.messaging.RPCServer.access$clientArtemisMessageHandler(RPCServer.kt:76) ~[corda-node-0.13.0.jar:?]
    at net.corda.node.services.messaging.RPCServer$createConsumerSessions$1.invoke(RPCServer.kt:190) ~[corda-node-0.13.0.jar:?]
    at net.corda.node.services.messaging.RPCServer$createConsumerSessions$1.invoke(RPCServer.kt:76) ~[corda-node-0.13.0.jar:?]
    at net.corda.node.services.messaging.RPCServerKt$sam$MessageHandler$086628f7.onMessage(RPCServer.kt) ~[corda-node-0.13.0.jar:?]
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.callOnMessage(ClientConsumerImpl.java:997) ~[artemis-core-client-2.1.0.jar:2.1.0]
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.access$400(ClientConsumerImpl.java:49) ~[artemis-core-client-2.1.0.jar:2.1.0]
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl$Runner.run(ClientConsumerImpl.java:1120) [artemis-core-client-2.1.0.jar:2.1.0]
    at org.apache.activemq.artemis.utils.OrderedExecutorFactory$OrderedExecutor$ExecutorTask.run(OrderedExecutorFactory.java:101) [artemis-commons-2.1.0.jar:2.1.0]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_131]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_131]


问:
Commit type before feature is done
Conventional Commits defines several types for commit messages like feat, fix, chore, ci etc.

My question is about the workflow if I'm working on a feature whose scope spans several days of work. As a good developer I want to commit early and often but the feature in the sense of Conventional Commits is defined as:

feat: a commit of the type feat introduces a new feature to the
  codebase  (this correlates with MINOR in semantic versioning).

So this type of commit should only be used once (otherwise, a CHANGELOG generated from these commits would list a lot of features which indeed are only parts of a particular feature).

I'm wondering whats the common workflow to solve commit (and push) early and often using Conventional Commits?

Does everybody squash their commits into a feat: ... type commit?
Are there other workflows?

Which type of messages are used until the squashing feat commit?

答:
You should only be worried about making atomic commits.

An atomic commit is a set of changes that is releasable on its own. It requires a lot of discipline but the ROI is immense:

You can release or rollback to any commit

You can use git bisect effectively

You can target and revert unnecessary changes with more accuracy

You can use your Git history effectively to find patterns in your codebase

The Conventional Commits specification doesn't dictate workflow, it's a specification for commit messages that tools can use to automate processes: generating change logs and bumping packages versions for example.

It is also worth noting that squashing unrelated commits completely defeats the point of using the Conventional Commits specification in the first place.

Imagine that you must implement a logout button and by the way all buttons are now a few pixels larger which introduces a breaking change. You actually have two pieces of work:

feat: make all buttons larger. BREAKING CHANGE

feat: implement a logout button

If you squash these two unrelated changesets into a single commit, you run the risk of releasing a breaking change in a minor release.

What if you didn't need to make these buttons larger in the end? If you didn't squash these two commits, you could simply revert the first commit.

It's not impossible that as you work on a task, you may end up creating a few refactoring commits before fixing a bug or implementing a feature. Perhaps the fix or the feature won't be needed anymore but is that the case for your refactoring commits? These may be valuable changes that you actually needed regardless of the fix or the feature.

There's no good reason for squashing unrelated commits. You may as well keep amending the first and only commit in your codebase yet you wouldn't do that.

Title: Commit type before feature is done


问:
How to `git submodule add` Existing sub Repository?

The Question

How to add existing sub repository as a submodule in git?

The Why

I have a private codespace supermodule with submodules scattered randomly:

```<code>codespace (git repo, private)
├── Archived_projects (git repos)
└── Projects
    ├── project-foo (git repo)
    └── project-bar (git repo)
</code>```

Sometimes submodules have commits not ready to be pushed. But I want them to be saved while pushing supermodule codespace.

codespace is a repo cloned to c9.io workspace or other places.

What I Do

linus@machine /cygdrive/f/__Storage__/Workspace
$ git clone https://github.com/octocat/Spoon-Knife.git
Cloning into 'Spoon-Knife'...
$ cd Spoon-Knife/
$ git clone https://github.com/octocat/Spoon-Knife.git ./foo/bar
Cloning into './foo/bar'...
$ git add .
```

<p>From <strong>cmd.exe</strong></p>

<pre class="lang-console prettyprint-override"><code>> git submodule add https://github.com/octocat/Spoon-Knife.git ./foo/bar
'foo/bar' already exists in the index
> cat .gitmodules
cat: .gitmodules: No such file or directory
</code>```

From cygwin.exe (bash)

$ git submodule add https://github.com/octocat/Spoon-Knife.git ./foo/bar
': not a valid identifier/Git/mingw64/bin/gettext.sh: line 89: export: `sm_path
'' already exists in the index
$ cat .gitmodules
cat: .gitmodules: No such file or directory
```

<h3>Reference</h3>

<pre class="lang-console prettyprint-override"><code>git submodule [--quiet] add [-b <branch>] [-f|--force] [--name <name>]
              [--reference <repository>] [--depth <depth>] [--] <repository> [<path>]

<repository> is the URL of the new submodule’s origin repository.

<path> is the relative location for the cloned submodule to exist in the superproject. If <path> does not exist, then the
submodule is created by cloning from the named URL. If <path> does exist and is already a valid Git repository, then this is
added to the changeset without cloning. This second form is provided to ease creating a new submodule from scratch, and
presumes the user will later push the submodule to the given URL.

In either case, the given URL is recorded into .gitmodules for use by subsequent users cloning the superproject. If the URL
is given relative to the superproject’s repository, the presumption is the superproject and submodule repositories will be
kept together in the same relative location, and only the superproject’s URL needs to be provided: git-submodule will
correctly locate the submodule using the relative URL in .gitmodules.
</code>```

If <path> does exist and is already a valid Git repository, then this is added to the changeset without cloning.

Why this doesn't work in my case?

答:
remove files from index foo/bar: git rm -f --cached foo/bar

git submodule add https://github.com/octocat/Spoon-Knife.git ./foo/bar

Body:
The Question

How to add existing sub repository as a submodule in git?

The Why

I have a private codespace supermodule with submodules scattered randomly:

codespace (git repo, private)
├── Archived_projects (git repos)
└── Projects
    ├── project-foo (git repo)
    └── project-bar (git repo)

Sometimes submodules have commits not ready to be pushed. But I want them to be saved while pushing supermodule codespace.

codespace is a repo cloned to c9.io workspace or other places.

What I Do

linus@machine /cygdrive/f/__Storage__/Workspace
$ git clone https://github.com/octocat/Spoon-Knife.git
Cloning into 'Spoon-Knife'...
$ cd Spoon-Knife/
$ git clone https://github.com/octocat/Spoon-Knife.git ./foo/bar
Cloning into './foo/bar'...
$ git add .

From cmd.exe

> git submodule add https://github.com/octocat/Spoon-Knife.git ./foo/bar
'foo/bar' already exists in the index
> cat .gitmodules
cat: .gitmodules: No such file or directory

From cygwin.exe (bash)

$ git submodule add https://github.com/octocat/Spoon-Knife.git ./foo/bar
': not a valid identifier/Git/mingw64/bin/gettext.sh: line 89: export: `sm_path
'' already exists in the index
$ cat .gitmodules
cat: .gitmodules: No such file or directory

Reference

git submodule [--quiet] add [-b <branch>] [-f|--force] [--name <name>]
              [--reference <repository>] [--depth <depth>] [--] <repository> [<path>]

<repository> is the URL of the new submodule’s origin repository.

<path> is the relative location for the cloned submodule to exist in the superproject. If <path> does not exist, then the
submodule is created by cloning from the named URL. If <path> does exist and is already a valid Git repository, then this is
added to the changeset without cloning. This second form is provided to ease creating a new submodule from scratch, and
presumes the user will later push the submodule to the given URL.

In either case, the given URL is recorded into .gitmodules for use by subsequent users cloning the superproject. If the URL
is given relative to the superproject’s repository, the presumption is the superproject and submodule repositories will be
kept together in the same relative location, and only the superproject’s URL needs to be provided: git-submodule will
correctly locate the submodule using the relative URL in .gitmodules.

If <path> does exist and is already a valid Git repository, then this is added to the changeset without cloning.

Why this doesn't work in my case?


问:
When/why to prefix variables with "$" when using jQuery?

Possible Duplicate:

  Why would a javascript variable start with a dollar sign?

I see people using the dollar sign in front of variables when using jQuery. Is there any reason behind this? I'm I missing something basic or is it just a common practice?

答: Dollar signs in code that uses JQuery commonly means that the variable in question is a jQuery variable (an object wrapped by jquery).</p>


问:
SQLite Ordering Whole Numbers
I am fairly aware that ORDER BY in SQLite puts the number in Ascending order unless DESC is at the end. But I realized that it only worked for the starting numbers.

```<code>i.e
INT
14
78
357
2999
57
888

ORDER BY INT

Gives
14
2999
357
57
78
888
</code>```

Is it possible to use the ORDER BY function where the whole numbers are in ascending Order?

```<code>As such
14
57
78
357
888
2999
</code>```

答:
```<code>select (INT * 1)  as "int_number" from mytable order by 1
</code>```

<p>or as someone points out in the link: </p>

```<code>select INT from mytable order by (cast INT as Integer)
</code>```

Title: SQLite Ordering Whole Numbers

Body:
I am fairly aware that ORDER BY in SQLite puts the number in Ascending order unless DESC is at the end. But I realized that it only worked for the starting numbers.

i.e
INT
14
78
357
2999
57
888

ORDER BY INT

Gives
14
2999
357
57
78
888

Is it possible to use the ORDER BY function where the whole numbers are in ascending Order?

As such
14
57
78
357
888
2999

Body:
select (INT * 1)  as "int_number" from mytable order by 1

or as someone points out in the link:

select INT from mytable order by (cast INT as Integer)


问:
Reduce NPM Memory use
I'm running npm install on a server and it's running out of memory.  The server has 2GB of RAM, which is less than Node's default 4GB limit.  I'm watching memory profiling and it's using all of the server's RAM before dying.  I have a pretty small package.json file; we're talking around a dozen packages, and it seems pretty dumb to have to set up a swap just to do a handful of NPM installs.

Is there any way to get NPM to use less memory when running installs?

答:
The max_old_space_size option appears to fix this:

NODE_OPTIONS=--max_old_space_size=1000; npm install

Title: Reduce NPM Memory use


问:
XSLT to remove an element but not its children?
Input:

```<code><req>
  <element>
   <field1>abcd</field1>
   <field2>05/05/2020</field2>
  </element>
</req>
</code>```

Expected Output:

```<code><req>
  <field1>abcd</field1>
  <field2>05/05/2020</field2>
</req>
</code>```

So my requirement is to remove element from the input XML.

答:
Think identity transform when you see such problems:

This XSLT,

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- Indent output: -->
  <xsl:output indent="yes"/>

  <!-- Cleanup extra whitespace in output: -->
  <xsl:strip-space elements="*"/>

  <!-- If not overridden, copy node as-is: -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- Override to treat element specially: Just like identity
       template but omit xsl:copy: -->
  <xsl:template match="element">
    <xsl:apply-templates select="@*|node()"/>
  </xsl:template>
</xsl:stylesheet>
</code>```

applied to your input XML,

```<code><req>
  <element>
    <field1>abcd</field1>
    <field2>05/05/2020</field2>
  </element>
</req>
</code>```

produces your output XML,

```<code><?xml version="1.0" encoding="UTF-8"?>
<req>
   <field1>abcd</field1>
   <field2>05/05/2020</field2>
</req>
</code>```

as requested.

Body:
Input:

<req>
  <element>
   <field1>abcd</field1>
   <field2>05/05/2020</field2>
  </element>
</req>

Expected Output:

<req>
  <field1>abcd</field1>
  <field2>05/05/2020</field2>
</req>

So my requirement is to remove element from the input XML.

Body:
Think identity transform when you see such problems:

This XSLT,

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- Indent output: -->
  <xsl:output indent="yes"/>

  <!-- Cleanup extra whitespace in output: -->
  <xsl:strip-space elements="*"/>

  <!-- If not overridden, copy node as-is: -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- Override to treat element specially: Just like identity
       template but omit xsl:copy: -->
  <xsl:template match="element">
    <xsl:apply-templates select="@*|node()"/>
  </xsl:template>
</xsl:stylesheet>

applied to your input XML,

<req>
  <element>
    <field1>abcd</field1>
    <field2>05/05/2020</field2>
  </element>
</req>

produces your output XML,

<?xml version="1.0" encoding="UTF-8"?>
<req>
   <field1>abcd</field1>
   <field2>05/05/2020</field2>
</req>

as requested.


问:
React hook query not updating on state change
I have a React component with two select inputs; Select A lets you select a size and then, based on what is selected, that size is passed into a React hook (getPackageBySize) that does a GET query that returns the option list of that size for Select B. So:

```<code>Select A = 100 should return options ['A','B','C']
Select A = 50 should return options ['X','Y','Z']
</code>```

When the component loads with an initial size value of '100' it loads the correct options for Select B (['A','B','C']). However, if I then pick a new size from Select A, it does not update the options in Select B to ['X','Y','Z']. Here is the hook:

```<code>  const [
    options,
    refetchOptions,
  ] = getPackageBySize(
    props.size
  );
</code>```

And a useEffect hook that calls the first hook again any time the size changes:

```<code>  useEffect(() => {
    refetchOptions(
      props.size
    );
  }, [props.size]);
</code>```

And 'getPackageBySize' is:

```<code>export default (size: string) => {
  const dispatch = useDispatch();
  const [fetch, reFetch] = useAxios({
    options: {
      method: 'get',
      headers: {
        Authorization: getAuthToken(),
        'Content-Type': 'application/json',
      url:
        `${routes.search.api.ROOT}` +
        '?q=TYPE:"package" AND =size:"' +
        size +
        '"',
    },
    forceDispatch: () => true,

    handler: (error: any, response: any) => {
      if (error) {
        dispatch(
          addToast({
            labels: {
              heading: 'Error',
              details: `${error.message}`,
            },
            variant: 'error',
          })
        );
      }
      if (response) {
        return console.log('Response: ', response);
      }
    },
  });
  return [fetch, reFetch];
};
</code>```

So on initial load it looks up the default size 100 and returns ['A', 'B', 'C']. When I change Select A to 50 I can see that getPackageBySize gets the correct size arg of '50'. It plugs it into the URL and the query is processed however when I get the response, I can see that the URL in the response is still using the original size:

```<code>url: "http://localhost:4001/http://site.local:8080/search/content?q=TYPE:"package" AND =size:"100""
</code>```

If I leave the page and then return, it runs the query with the correct value of 50 and I get ['X', 'Y', 'Z'] back.

Does anyone know how to ensure the URL updates without having to leave the page and return?

答: If I understand well, you are not using a state to store the results returned by your axios call. If i'm right then it's normal. You need to update a state or a prop to trigger a re-rendering of your component (And so update your select value).</p>

Body:
I have a React component with two select inputs; Select A lets you select a size and then, based on what is selected, that size is passed into a React hook (getPackageBySize) that does a GET query that returns the option list of that size for Select B. So:

Select A = 100 should return options ['A','B','C']
Select A = 50 should return options ['X','Y','Z']

When the component loads with an initial size value of '100' it loads the correct options for Select B (['A','B','C']). However, if I then pick a new size from Select A, it does not update the options in Select B to ['X','Y','Z']. Here is the hook:

  const [
    options,
    refetchOptions,
  ] = getPackageBySize(
    props.size
  );

And a useEffect hook that calls the first hook again any time the size changes:

  useEffect(() => {
    refetchOptions(
      props.size
    );
  }, [props.size]);

And 'getPackageBySize' is:

export default (size: string) => {
  const dispatch = useDispatch();
  const [fetch, reFetch] = useAxios({
    options: {
      method: 'get',
      headers: {
        Authorization: getAuthToken(),
        'Content-Type': 'application/json',
      url:
        `${routes.search.api.ROOT}` +
        '?q=TYPE:"package" AND =size:"' +
        size +
        '"',
    },
    forceDispatch: () => true,

    handler: (error: any, response: any) => {
      if (error) {
        dispatch(
          addToast({
            labels: {
              heading: 'Error',
              details: `${error.message}`,
            },
            variant: 'error',
          })
        );
      }
      if (response) {
        return console.log('Response: ', response);
      }
    },
  });
  return [fetch, reFetch];
};

So on initial load it looks up the default size 100 and returns ['A', 'B', 'C']. When I change Select A to 50 I can see that getPackageBySize gets the correct size arg of '50'. It plugs it into the URL and the query is processed however when I get the response, I can see that the URL in the response is still using the original size:

url: "http://localhost:4001/http://site.local:8080/search/content?q=TYPE:"package" AND =size:"100""

If I leave the page and then return, it runs the query with the correct value of 50 and I get ['X', 'Y', 'Z'] back.

Does anyone know how to ensure the URL updates without having to leave the page and return?


问:
Set Height of separator between Tab widget and FrameLayout
I'm using TabHost in my app and i want to increase the thickness of the strip between tab widget and framelayout.

```<code> <TabHost android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:id="@android:id/tabhost">
 <LinearLayout android:orientation="vertical"
 android:layout_width="fill_parent" android:layout_height="fill_parent">

 <TabWidget android:id="@android:id/tabs"
 android:layout_height="wrap_content" android:layout_width="fill_parent">
 </TabWidget>
 <FrameLayout android:id="@android:id/tabcontent"
 android:layout_height="wrap_content" android:layout_width="fill_parent"                         android:background="#FF0000">
<LinearLayout android:orientation="vertical" android:layout_height="wrap_content"    android:layout_width="wrap_content">
<TextView android:text="TravelApplication1" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication2" android:layout_height="70dip"       android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication3" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication4" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</code>```

Kindly suggest me to increse the thickness between tabWidget and FrameLayout.

Regards
Deepak Goel

答: Have you tried using android:paddingTop/paddingBottom on the tab widget or frame layouts?</p>

Body:
I'm using TabHost in my app and i want to increase the thickness of the strip between tab widget and framelayout.

 <TabHost android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:id="@android:id/tabhost">
 <LinearLayout android:orientation="vertical"
 android:layout_width="fill_parent" android:layout_height="fill_parent">

 <TabWidget android:id="@android:id/tabs"
 android:layout_height="wrap_content" android:layout_width="fill_parent">
 </TabWidget>
 <FrameLayout android:id="@android:id/tabcontent"
 android:layout_height="wrap_content" android:layout_width="fill_parent"                         android:background="#FF0000">
<LinearLayout android:orientation="vertical" android:layout_height="wrap_content"    android:layout_width="wrap_content">
<TextView android:text="TravelApplication1" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication2" android:layout_height="70dip"       android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication3" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication4" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
</LinearLayout>
</FrameLayout>
</LinearLayout>

Kindly suggest me to increse the thickness between tabWidget and FrameLayout.

Regards
Deepak Goel


答:
Try: </p>

```<code>>>> mylist =["The", "sky", "is", "blue", "and", "the", "sun", "is", "bright"]
>>> arr = [mylist[i:i+3] for i in range(0, len(mylist), 3)]
>>> arr
[['The', 'sky', 'is'], ['blue', 'and', 'the'], ['sun', 'is', 'bright']]
>>> arr = [" ".join(l) for l in arr]
>>> arr
['The sky is', 'blue and the', 'sun is bright']
</code>```

Title: how i can merge words from list to new list that in each index, store k content from old list

Body:
Try:

>>> mylist =["The", "sky", "is", "blue", "and", "the", "sun", "is", "bright"]
>>> arr = [mylist[i:i+3] for i in range(0, len(mylist), 3)]
>>> arr
[['The', 'sky', 'is'], ['blue', 'and', 'the'], ['sun', 'is', 'bright']]
>>> arr = [" ".join(l) for l in arr]
>>> arr
['The sky is', 'blue and the', 'sun is bright']