问:
jQuery: How to open file open dialog box on click button
How can I make a dialog box open on click of button on swallow rendering.
It can be dynamically repeatable button as it is inside li.

//Code

```<code>var wrapper = $(this).parents(".file-upload-wrapper")[0];
$(wrapper).find('.attachment-button-div')[0].click(function() {
 $(wrapper).find('.attachment-button')[0].trigger('click');

});

$(wrapper).find('.file-upload').change(function() {
 $('input[type=text]').val($(this).val());
});
</code>```

But it is not working as expected . Any suggestion.

答:
you can try this. create buttons and corresponding invisible file input to each button. Add some jQuery to trigger/click  corresponding  invisible file input:

function openfile(a) {
  $(a).trigger('click');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1" onclick='openfile("#file-input3")' class="file-button"> Open</button>
<input id="file-input1" type="file" name="name" style="display: none;" />

<button id="button2" onclick='openfile("#file-input2")' class="file-button"> Open</button>
<input id="file-input2" type="file" name="name" style="display: none;" />

<button id="button3" onclick='openfile("#file-input3")' class="file-button"> Open</button>
<input id="file-input3" type="file" name="name" style="display: none;" /></code>```

Body:
How can I make a dialog box open on click of button on swallow rendering.
It can be dynamically repeatable button as it is inside li.

//Code

var wrapper = $(this).parents(".file-upload-wrapper")[0];
$(wrapper).find('.attachment-button-div')[0].click(function() {
 $(wrapper).find('.attachment-button')[0].trigger('click');

});

$(wrapper).find('.file-upload').change(function() {
 $('input[type=text]').val($(this).val());
});

But it is not working as expected . Any suggestion.

Body:
you can try this. create buttons and corresponding invisible file input to each button. Add some jQuery to trigger/click  corresponding  invisible file input:

function openfile(a) {
  $(a).trigger('click');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1" onclick='openfile("#file-input3")' class="file-button"> Open</button>
<input id="file-input1" type="file" name="name" style="display: none;" />

<button id="button2" onclick='openfile("#file-input2")' class="file-button"> Open</button>
<input id="file-input2" type="file" name="name" style="display: none;" />

<button id="button3" onclick='openfile("#file-input3")' class="file-button"> Open</button>
<input id="file-input3" type="file" name="name" style="display: none;" />


来源: stackexchange

问:
Select a default radio button in angular 6
I am new to Angular. Need some help here. There are two radio buttons for two text fields:

```<code><div class="col-1">
 <label class="radio-container mb-0 mt-1">
   <input id="Page_Color" name="Page_Color" type="radio" [(ngModel)]='Br.Page_IsGraphic'
                      [value]='false' (change)="updateRadioChangeValToObj('Page_IsGraphic','Page_IsGraphic','Page_GraphicName','Page_Color')">
    <span class="checkmark"></span>
 </label>
</div>

<div class="col-1">
   <label class="radio-container mb-0 mt-1">
      <input id="IsGraphic" name="IsGraphic" type="radio" (change)="updateRadioChangeValToObj('Page_IsGraphic','Page_Graphic','Page_GraphicName','PageColor')"
                         [(ngModel)]='Br.Page_IsGraphic' [value]='true'>
     <span class="checkmark"></span>
   </label>
 </div>
</code>```

In [(ngModel)]='Br.Page_IsGraphic' Br.Page_IsGraphic value is either true or false and that is dynamic and based on that the radio button is getting checked i think.
If it's true then the second radio button gets selected and if it's false then the 1st one.
Now the 1st text field had to be removed as per the requirement and I want the second radio button to be always selected by default.
Br.Page_IsGraphic value should be set to true  before theis code gets executed for this to work? or is there another way.
I tried [checked]="true" and that did not work.

答:
I did this and it selected the checkbox by default:</p>

```<code>[(ngModel)]='Br.Page_IsGraphic' [value]='Br.Page_IsGraphic'>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to Angular. Need some help here. There are two radio buttons for two text fields:

   <input id="Page_Color" name="Page_Color" type="radio" [(ngModel)]='Br.Page_IsGraphic'
                      [value]='false' (change)="updateRadioChangeValToObj('Page_IsGraphic','Page_IsGraphic','Page_GraphicName','Page_Color')">

      <input id="IsGraphic" name="IsGraphic" type="radio" (change)="updateRadioChangeValToObj('Page_IsGraphic','Page_Graphic','Page_GraphicName','PageColor')"
                         [(ngModel)]='Br.Page_IsGraphic' [value]='true'>

In [(ngModel)]='Br.Page_IsGraphic' Br.Page_IsGraphic value is either true or false and that is dynamic and based on that the radio button is getting checked i think.
If it's true then the second radio button gets selected and if it's false then the 1st one.
Now the 1st text field had to be removed as per the requirement and I want the second radio button to be always selected by default.
Br.Page_IsGraphic value should be set to true  before theis code gets executed for this to work? or is there another way.
I tried [checked]="true" and that did not work.

Body:
I did this and it selected the checkbox by default:

[(ngModel)]='Br.Page_IsGraphic' [value]='Br.Page_IsGraphic'>


问:
How to comment each change in files so they will be visible for git but hidden in actual files
When I develop a feature I usually need to change non-related files: utils, helpers. But not only those. There are cases when event some repository is not related to the feature but it just contains additional code to allow developing of the main feature.

Initially I just skipped this problem. But now I understand that it is difficult to understand why I changed some files if they are not related to the feature I committed. I need something like usual comments in files but they should be visible just for git: when I browse commit message/history I want to see why I did a specific change. I can not comment each change. The biggest problem is that my change could be not just adding code lines but removing. Nobody need to see comments for the absent lines.

My first idea is to commit changes with comments in files and then do another commit to remove comments. By it is like a workaround. I work in PhpStorm. And I always see git history there. I want to open a file from commit and see why I did some change. I would be very useful for me. Very useful. For me it give the same profit as I have from commit message.

I do not see other solutions. Maybe someone else had such problem.

I also assume that other git GUI programs could have such a feature.

答:
Just a list of ideas to try.

Use github or bitbucket's comments. They are quite nice. The downside is that they are stored in own format of the server and not accessible locally.

Use notes; run git notes add <commit>, then you have an editor where you can insert (partial) diffs and comment them. They are stored in git's database, and would be relatively convenient to use if you can afford command-line. But popular tools are quite behind in their support.

Commit changes to your helper files separately. That way, you have a dedicated place to comment them. But then you will have to not squash your pull-request merges, so that the history is preserved, or make separated PRs.

Consider re-organizing your helpers and make the ones you have to touch internal to your implementations. Indeed, if they have problem specific functionality it is dangerous to have them detached, somebody can start using them to unrelated purpose. So that the changes will look very much less detached.

Do not remove comments in the file. If some operations are not obvious from the function name maybe it is ok to have the  reasoning behind them commented.


问:
Hyphen missing in my Custom Post Type URL Slug
I have created a new Custom Post Type(Earnings Transcripts) in WordPress using the below code. The name of my Custom Post Type is "Earnings Transcripts" which is 2 words. So the slug should be "earnings-transcripts". Instead the URL is "earningstranscripts". What am I missing here?

```<code>function custom_post_type() {

    // Earnings Transcripts
    $labels = array(
        'name'                => _x( 'Earnings Transcripts', 'Post Type General Name', 'twentysixteen' ),
        'singular_name'       => _x( 'Earnings Transcripts', 'Post Type Singular Name', 'twentysixteen' ),
        'menu_name'           => __( 'Earnings Transcripts', 'twentysixteen' ),
        'parent_item_colon'   => __( 'Parent Earnings Transcripts', 'twentysixteen' ),
        'all_items'           => __( 'All Earnings Transcripts', 'twentysixteen' ),
        'view_item'           => __( 'View Earnings Transcripts', 'twentysixteen' ),
        'add_new_item'        => __( 'Add New Earnings Transcripts', 'twentysixteen' ),
        'add_new'             => __( 'Add New', 'twentysixteen' ),
        'edit_item'           => __( 'Edit Earnings Transcripts', 'twentysixteen' ),
        'update_item'         => __( 'Update Earnings Transcripts', 'twentysixteen' ),
        'search_items'        => __( 'Search Earnings Transcripts', 'twentysixteen' ),
        'not_found'           => __( 'Not Found', 'twentysixteen' ),
        'not_found_in_trash'  => __( 'Not found in Trash', 'twentysixteen' ),
    );
    $args = array(
        'label'               => __( 'Earnings Transcripts', 'twentysixteen' ),
        'description'         => __( 'Earnings Transcripts', 'twentysixteen' ),
        'labels'              => $labels,
        'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
        'taxonomies'          => array( 'Earnings Transcripts' ),
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 5,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'page',
    );
    // Registering your Custom Post Type
    register_post_type( 'Earnings Transcripts', $args );

}
add_action( 'init', 'custom_post_type', 0 );
</code>```

答:
```<code>"rewrite" => array( "slug" => "earnings-transcripts", "with_front" => true ),
</code>```

Add this parameter in $args, it will work.

Body:
I have created a new Custom Post Type(Earnings Transcripts) in WordPress using the below code. The name of my Custom Post Type is "Earnings Transcripts" which is 2 words. So the slug should be "earnings-transcripts". Instead the URL is "earningstranscripts". What am I missing here?

function custom_post_type() {

    // Earnings Transcripts
    $labels = array(
        'name'                => _x( 'Earnings Transcripts', 'Post Type General Name', 'twentysixteen' ),
        'singular_name'       => _x( 'Earnings Transcripts', 'Post Type Singular Name', 'twentysixteen' ),
        'menu_name'           => __( 'Earnings Transcripts', 'twentysixteen' ),
        'parent_item_colon'   => __( 'Parent Earnings Transcripts', 'twentysixteen' ),
        'all_items'           => __( 'All Earnings Transcripts', 'twentysixteen' ),
        'view_item'           => __( 'View Earnings Transcripts', 'twentysixteen' ),
        'add_new_item'        => __( 'Add New Earnings Transcripts', 'twentysixteen' ),
        'add_new'             => __( 'Add New', 'twentysixteen' ),
        'edit_item'           => __( 'Edit Earnings Transcripts', 'twentysixteen' ),
        'update_item'         => __( 'Update Earnings Transcripts', 'twentysixteen' ),
        'search_items'        => __( 'Search Earnings Transcripts', 'twentysixteen' ),
        'not_found'           => __( 'Not Found', 'twentysixteen' ),
        'not_found_in_trash'  => __( 'Not found in Trash', 'twentysixteen' ),
    );
    $args = array(
        'label'               => __( 'Earnings Transcripts', 'twentysixteen' ),
        'description'         => __( 'Earnings Transcripts', 'twentysixteen' ),
        'labels'              => $labels,
        'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
        'taxonomies'          => array( 'Earnings Transcripts' ),
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 5,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'page',
    );
    // Registering your Custom Post Type
    register_post_type( 'Earnings Transcripts', $args );

}
add_action( 'init', 'custom_post_type', 0 );

Body:
"rewrite" => array( "slug" => "earnings-transcripts", "with_front" => true ),

Add this parameter in $args, it will work.


问:
Developing API - how to make it secured?
I'm putting together read and write methods to my database and exposing them via URL (I'm using CodeIgniter framework and using URL segments to pass parameters to these methods). The original idea was to have my Ajax script call these methods. However, now I am thinking I could potentially expose these methods to any developer.

What should I do to make sure only authorized developers use my API? I'm thinking they should pass an API key and possibly password to each method call. If I were to provide them with such details, would that be secure enough?

Also, I'm thinking that I should support POST instead of GET as some of the required parameters may not fit in nicely with URL segments. Thoughts?

答:
Maybe you should check out OAuth.  It's An open protocol to allow secure API authorization in a simple and standard method from desktop and web applications.

I haven't tried it myself to be honest but it's the first thing I thought of when you mentioned authorized developers use my API. Just an idea.

ContentLicense: CC BY-SA 3.0


问:
Is it possible to call a variable from string input
I have five Labels in my form.

The names of the label are the following.

```<code>1) labelTeam1Name.Text
1) labelTeam2Name.Text
3) labelTeam3Name.Text
4) labelTeam4Name.Text
5) labelTeam5Name.Text
</code>```

now I want to run a loop and get the text values of the label

```<code>for( int i = 1; i < 6; i++ )
{
    string str = labelTeam(i)Name.Text  // Get the values based on the input i

}
</code>```

I can definitely fill these values in an array or list and then call them in the loop.

is it possible to do something like this labelTeam(i)Name.Text?

答:
You can use the Controls.Find() method:</p>

```<code>for( int i = 1; i < 6; i++ )
{
    string str = ((Label)Controls.Find("labelTeam" + i + "Name",true)[0]).Text  // Get the values based on the input i

}
</code>```

Body:
I have five Labels in my form.

The names of the label are the following.

1) labelTeam1Name.Text
1) labelTeam2Name.Text
3) labelTeam3Name.Text
4) labelTeam4Name.Text
5) labelTeam5Name.Text

now I want to run a loop and get the text values of the label

for( int i = 1; i < 6; i++ )
{
    string str = labelTeam(i)Name.Text  // Get the values based on the input i

}

I can definitely fill these values in an array or list and then call them in the loop.

is it possible to do something like this labelTeam(i)Name.Text?

Body:
You can use the Controls.Find() method:

for( int i = 1; i < 6; i++ )
{
    string str = ((Label)Controls.Find("labelTeam" + i + "Name",true)[0]).Text  // Get the values based on the input i

}


问:
Add click event to datatable cell
I'm trying to add a click event to a dynamically created a datatabe. So this is my js :

```<code>   $('#report-table').dataTable({
        "proccessing": true,
        "serverSide": true,
        "ajax": {
            url: '@Url.Action("Get","Controller")',
            type: 'GET'

        },
       "columns": [
           { "data": "Name" },
                { "data": "Date" }, //lest say I want to add a click event here ???
                { "data": "sName", render: myRender }// I tried render but this is rendered without waiting on click function
        ]

    });
</code>```

and this is my table for example :

```<code><tr role="row" class="odd">
<td class="sorting_1">A Test</td>
<td class="aaaa">2/13/2020 3:34:40 PM</td> //lets say I want to fire a click event when I click the .aaaa class
<td>
    <a  asp-route-fileid="55555555" asp-action="Download5"><img src="img/download.svg" height="30" width="30"></a>
</td>
</code>```

Let's say I want to fire a click event when I click the .aaaa class.

Can anyone please give me an idea? Can I do this?
I'm stucked right here. Any idea would be apprecciated very very much :)

答:
Try this, for more check this forum :</p>
```<code>$('#report-table').on('click', 'td.className', function (e) {
    // your code to do something
});
</code>```

Title: Add click event to datatable cell

Body:
I'm trying to add a click event to a dynamically created a datatabe. So this is my js :

   $('#report-table').dataTable({
        "proccessing": true,
        "serverSide": true,
        "ajax": {
            url: '@Url.Action("Get","Controller")',
            type: 'GET'

        },
       "columns": [
           { "data": "Name" },
                { "data": "Date" }, //lest say I want to add a click event here ???
                { "data": "sName", render: myRender }// I tried render but this is rendered without waiting on click function
        ]

    });

and this is my table for example :

A Test
2/13/2020 3:34:40 PM	 //lets say I want to fire a click event when I click the .aaaa class

Let's say I want to fire a click event when I click the .aaaa class.

Can anyone please give me an idea? Can I do this?
I'm stucked right here. Any idea would be apprecciated very very much :)

Body:
Try this, for more check this forum :

$('#report-table').on('click', 'td.className', function (e) {
    // your code to do something
});


答:
You can use a Label array.</p>

```<code>System.Windows.Forms.Label[] Labels = new System.Windows.Forms.Label[5];

Labels[0] = labelTeam1Name;

Labels[1] = labelTeam2Name;

Labels[2] = labelTeam3Name;

Labels[3] = labelTeam4Name;

Labels[4] = labelTeam5Name;

for( int i = 0; i < Labels.Lenth; i++ )
{
    string str = Labels[i].Text;
}
</code>```

Title: Is it possible to call a variable from string input

Body:
You can use a Label array.

System.Windows.Forms.Label[] Labels = new System.Windows.Forms.Label[5];

Labels[0] = labelTeam1Name;

Labels[1] = labelTeam2Name;

Labels[2] = labelTeam3Name;

Labels[3] = labelTeam4Name;

Labels[4] = labelTeam5Name;

for( int i = 0; i < Labels.Lenth; i++ )
{
    string str = Labels[i].Text;
}


问:
Using client-go to `kubectl apply` against the Kubernetes API directly with multiple types in a single YAML file
I'm using https://github.com/kubernetes/client-go and all works well.

I have a manifest (YAML) for the official Kubernetes Dashboard: https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta4/aio/deploy/recommended.yaml

I want to mimic kubectl apply of this manifest in Go code, using client-go.

I understand that I need to do some (un)marshalling of the YAML bytes into the correct API types defined in package: https://github.com/kubernetes/api

I have successfully Createed single API types to my cluster, but how do I do this for a manifest that contains a list of types that are not the same? Is there a resource kind: List* that supports these different types?

My current workaround is to split the YAML file using csplit with --- as the delimiter

csplit /path/to/recommended.yaml /---/ '{*}' --prefix='dashboard.' --suffix-format='%03d.yaml'
```

Next, I loop over the new (14) parts that were created, read their bytes, switch on the type of the object returned by the UniversalDeserializer's decoder and call the correct API methods using my k8s clientset.

I would like to do this to programmatically to make updates to any new versions of the dashboard into my cluster. I will also need to do this for the Metrics Server and many other resources. The alternative (maybe simpler) method is to ship my code with kubectl installed to the container image and directly call kubectl apply -f -; but that means I also need to write the kube config to disk or maybe pass it inline so that kubectl can use it.

I found this issue to be helpful: https://github.com/kubernetes/client-go/issues/193
The decoder lives here: https://github.com/kubernetes/apimachinery/tree/master/pkg/runtime/serializer

It's exposed in client-go here: https://github.com/kubernetes/client-go/blob/master/kubernetes/scheme/register.go#L69

I've also taken a look at the RunConvert method that is used by kubectl: https://github.com/kubernetes/kubernetes/blob/master/pkg/kubectl/cmd/convert/convert.go#L139 and assume that I can provide my own genericclioptions.IOStreams to get the output?

It looks like RunConvert is on a deprecation path

I've also looked at other questions tagged [client-go] but most use old examples or use a YAML file with a single kind defined, and the API has changed since.

Edit: Because I need to do this for more than one cluster and am creating clusters programmatically (AWS EKS API + CloudFormation/eksctl), I would like to minimize the overhead of creating ServiceAccounts across many cluster contexts, across many AWS accounts. Ideally, the only authentication step involved in creating my clientset is using aws-iam-authenticator to get a token using cluster data (name, region, CA cert, etc). There hasn't been a release of aws-iam-authenticator for a while, but the contents of master allow for the use of a third-party role cross-account role and external ID to be passed. IMO, this is cleaner than using a ServiceAccount (and IRSA) because there are other AWS services the application (the backend API which creates and applies add-ons to these clusters) needs to interact with.

Edit: I have recently found https://github.com/ericchiang/k8s. It's definitely simpler to use than client-go, at a high-level, but doesn't support this behavior.

答:
It sounds like you've figured out how to deserialize YAML files into Kubernetes runtime.Objects, but the problem is dynamically deploying a runtime.Object without writing special code for each Kind.

kubectl achieves this by interacting with the REST API directly. Specifically, via resource.Helper.

In my code, I have something like:

```<code>import (
    meta "k8s.io/apimachinery/pkg/api/meta"
    "k8s.io/cli-runtime/pkg/resource"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
    "k8s.io/client-go/restmapper"
    "k8s.io/apimachinery/pkg/runtime"
)

func createObject(kubeClientset kubernetes.Interface, restConfig rest.Config, obj runtime.Object) error {
    // Create a REST mapper that tracks information about the available resources in the cluster.
    groupResources, err := restmapper.GetAPIGroupResources(kubeClientset.Discovery())
    if err != nil {
        return err
    }
    rm := restmapper.NewDiscoveryRESTMapper(groupResources)

    // Get some metadata needed to make the REST request.
    gvk := obj.GetObjectKind().GroupVersionKind()
    gk := schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}
    mapping, err := rm.RESTMapping(gk, gvk.Version)
    if err != nil {
        return err
    }

    name, err := meta.NewAccessor().Name(obj)
    if err != nil {
        return err
    }

    // Create a client specifically for creating the object.
    restClient, err := newRestClient(restConfig, mapping.GroupVersionKind.GroupVersion())
    if err != nil {
        return err
    }

    // Use the REST helper to create the object in the "default" namespace.
    restHelper := resource.NewHelper(restClient, mapping)
    return restHelper.Create("default", false, obj, &metav1.CreateOptions{})
}

func newRestClient(restConfig rest.Config, gv schema.GroupVersion) (rest.Interface, error) {
    restConfig.ContentConfig = resource.UnstructuredPlusDefaultContentConfig()
    restConfig.GroupVersion = &gv
    if len(gv.Group) == 0 {
        restConfig.APIPath = "/api"
    } else {
        restConfig.APIPath = "/apis"
    }

    return rest.RESTClientFor(&restConfig)
}

</code>```

Body:
I'm using https://github.com/kubernetes/client-go and all works well.

I have a manifest (YAML) for the official Kubernetes Dashboard: https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta4/aio/deploy/recommended.yaml

I want to mimic kubectl apply of this manifest in Go code, using client-go.

I understand that I need to do some (un)marshalling of the YAML bytes into the correct API types defined in package: https://github.com/kubernetes/api

I have successfully Createed single API types to my cluster, but how do I do this for a manifest that contains a list of types that are not the same? Is there a resource kind: List* that supports these different types?

My current workaround is to split the YAML file using csplit with --- as the delimiter

csplit /path/to/recommended.yaml /---/ '{*}' --prefix='dashboard.' --suffix-format='%03d.yaml'

Next, I loop over the new (14) parts that were created, read their bytes, switch on the type of the object returned by the UniversalDeserializer's decoder and call the correct API methods using my k8s clientset.

I would like to do this to programmatically to make updates to any new versions of the dashboard into my cluster. I will also need to do this for the Metrics Server and many other resources. The alternative (maybe simpler) method is to ship my code with kubectl installed to the container image and directly call kubectl apply -f -; but that means I also need to write the kube config to disk or maybe pass it inline so that kubectl can use it.

I found this issue to be helpful: https://github.com/kubernetes/client-go/issues/193
The decoder lives here: https://github.com/kubernetes/apimachinery/tree/master/pkg/runtime/serializer

It's exposed in client-go here: https://github.com/kubernetes/client-go/blob/master/kubernetes/scheme/register.go#L69

I've also taken a look at the RunConvert method that is used by kubectl: https://github.com/kubernetes/kubernetes/blob/master/pkg/kubectl/cmd/convert/convert.go#L139 and assume that I can provide my own genericclioptions.IOStreams to get the output?

It looks like RunConvert is on a deprecation path

I've also looked at other questions tagged [client-go] but most use old examples or use a YAML file with a single kind defined, and the API has changed since.

Edit: Because I need to do this for more than one cluster and am creating clusters programmatically (AWS EKS API + CloudFormation/eksctl), I would like to minimize the overhead of creating ServiceAccounts across many cluster contexts, across many AWS accounts. Ideally, the only authentication step involved in creating my clientset is using aws-iam-authenticator to get a token using cluster data (name, region, CA cert, etc). There hasn't been a release of aws-iam-authenticator for a while, but the contents of master allow for the use of a third-party role cross-account role and external ID to be passed. IMO, this is cleaner than using a ServiceAccount (and IRSA) because there are other AWS services the application (the backend API which creates and applies add-ons to these clusters) needs to interact with.

Edit: I have recently found https://github.com/ericchiang/k8s. It's definitely simpler to use than client-go, at a high-level, but doesn't support this behavior.

Body:
It sounds like you've figured out how to deserialize YAML files into Kubernetes runtime.Objects, but the problem is dynamically deploying a runtime.Object without writing special code for each Kind.

kubectl achieves this by interacting with the REST API directly. Specifically, via resource.Helper.

In my code, I have something like:

import (
    meta "k8s.io/apimachinery/pkg/api/meta"
    "k8s.io/cli-runtime/pkg/resource"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
    "k8s.io/client-go/restmapper"
    "k8s.io/apimachinery/pkg/runtime"
)

func createObject(kubeClientset kubernetes.Interface, restConfig rest.Config, obj runtime.Object) error {
    // Create a REST mapper that tracks information about the available resources in the cluster.
    groupResources, err := restmapper.GetAPIGroupResources(kubeClientset.Discovery())
    if err != nil {
        return err
    }
    rm := restmapper.NewDiscoveryRESTMapper(groupResources)

    // Get some metadata needed to make the REST request.
    gvk := obj.GetObjectKind().GroupVersionKind()
    gk := schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}
    mapping, err := rm.RESTMapping(gk, gvk.Version)
    if err != nil {
        return err
    }

    name, err := meta.NewAccessor().Name(obj)
    if err != nil {
        return err
    }

    // Create a client specifically for creating the object.
    restClient, err := newRestClient(restConfig, mapping.GroupVersionKind.GroupVersion())
    if err != nil {
        return err
    }

    // Use the REST helper to create the object in the "default" namespace.
    restHelper := resource.NewHelper(restClient, mapping)
    return restHelper.Create("default", false, obj, &metav1.CreateOptions{})
}

func newRestClient(restConfig rest.Config, gv schema.GroupVersion) (rest.Interface, error) {
    restConfig.ContentConfig = resource.UnstructuredPlusDefaultContentConfig()
    restConfig.GroupVersion = &gv
    if len(gv.Group) == 0 {
        restConfig.APIPath = "/api"
    } else {
        restConfig.APIPath = "/apis"
    }

    return rest.RESTClientFor(&restConfig)
}


问:
the table rows is hiding under navbar
I have a table but the top part of the table is hiding under the navbar like shown in the below picture so i had to use br to show it on the page.why it is happening? how should i make it visible without using br,margin and padding.i am trying to figure it out from past few hours. thanks in advance

  .scroll {
    overflow-y: auto !important;
    height: calc(100vh - 54px);

  }

  .search-wrapper{
    flex-grow: 1;
  }

  ::-webkit-scrollbar {
    width: 8px;
   height: 10px;
  }

  ::-webkit-scrollbar-thumb {
    border-radius: 8px;
    background: #c2c9d2;
  }

  .btn-outline-secondary:hover{
    background-color: white;
    font-weight: 500;
    border-bottom: 3px solid #23485B ;
  }

  .btn-outline-secondary{
    color: #23485B;
    border: thin;
  }

  .sidedivtext{
    color: #23485B;
  }

  .alert-dark{
    background-color: #F5F5F5;
  }

  .bg-light{
    background-color: #F5F5F5;
  }

  .text{
    color: #797979;
  }

  .tableicons{
  margin-right:25px;
  opacity:60% ;
  }

  tr:hover .tableicons{
  opacity:100% ;
  }

  .tablename{
  padding-right:10vw;
  }

  .leftalign .tableicons {
    padding-left: 0;
  }

  body{
  padding-top: 60px;
  }

  .btn-primary{
  background-color: #002B42;
  font-size: 12px;
  border-radius: 4px;
  padding:10px;
  }

  .btn-light{
  background-color: transparent;
  border: none;
  color: black;
  font-size: 13px;
  outline: none;
  padding:10px;
  margin-left: 20px;
  }

  @media only screen and (max-width: 768px) {
    body{
        padding-top: 0!important;
    }
    .navbar{
      position: relative;
    }
    .navbar-nav{
      align-items: center;
      margin: 15px 0;
    }
    .nav-item{
      margin:5px 0;
    }
  .navpull{
      margin-right: 10px;
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar navbar-expand-md navbar-light fixed-top bg-light">

  <button class="navbar-toggler mr-5" type="button" data-toggle="collapse" data-target="#my-navbar" aria-controls="my-navbar" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="my-navbar">
      <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <button type="button" class="btn btn-primary"><i class="fa fa-bars" aria-hidden="true">  SAVED LISTS</i></button>
          </li>
          <li class="nav-item navpull">
            <button class="btn btn-light"> <i class="fa fa-filter" aria-hidden="true">  SAVED FILTER</i></button>
          </li>
          <li class="nav-item navpull">
            <button class="btn btn-light"> <i class="fa fa-history" aria-hidden="true">  SEARCH HISTORY</i></button>
          </li>
        </ul>
    </div>

    <div class="my-2 my-md-0 search-wrapper">
      <input class="form-control" name="search" [(ngModel)]="search" type="search" placeholder="Search" />
    </div>
  </nav>
<br><br><br>

<div class="container-fluid">
  <section class="row">
    <div class="col-md-9 col-12 overflow-auto scroll">
      <table class="table table-hover">

        <tr>
          <th class="text">Date</th>
          <th class="text">List Name</th>
          <th class="text text-right">No. of Entities</th>
          <th class="text">Actions</th>
          <th class="text"></th>
      </tr>

        <tbody>

          <tr *ngFor="let items of data | filter: search">
            <td class="text-dark font-weight-bold">
              <span *ngIf="items.date">{{items.date | date:'MMM dd' }}</span>
              <span *ngIf="!items.date"><i class="fa fa-refresh"></i></span>
            </td>

            <td  class=" font-weight-bold tablename {{items.color}}">{{ items.name }}</td>

            <td  class="text-dark font-weight-bold text-right">{{ items.entities }}</td>

            <td class="leftalign">
              <span *ngFor="let x of items.actions.split(',')">
                  <i class="{{x}} tableicons"></i>
              </span>
            </td>
            <td>
              <button type="button" class="btn btn-outline-secondary" (click)="getdetails(items)">
                Details
              </button>
            </td>
          </tr>

        </tbody>
      </table>
    </div>

    <div class="col-md-3 col-12 overflow-auto scroll">
      <div class="alert alert-dark"><span class="text">No description yet</span>
        <span class="font-weight-bold sidedivtext">+Add Description</span>
      </div>
      <p *ngFor="let str of s" class="text-center text-primary">{{str}}</p>
    </div>
  </section>
</div></code>```

stackblitz link

答:
```<code>body{
padding-top:60px;
}
</code>```

will do the thing

Title: the table rows is hiding under navbar

Body:
I have a table but the top part of the table is hiding under the navbar like shown in the below picture so i had to use br to show it on the page.why it is happening? how should i make it visible without using br,margin and padding.i am trying to figure it out from past few hours. thanks in advance

  .scroll {
    overflow-y: auto !important;
    height: calc(100vh - 54px);

  }

  .search-wrapper{
    flex-grow: 1;
  }

  ::-webkit-scrollbar {
    width: 8px;
   height: 10px;
  }

  ::-webkit-scrollbar-thumb {
    border-radius: 8px;
    background: #c2c9d2;
  }

  .btn-outline-secondary:hover{
    background-color: white;
    font-weight: 500;
    border-bottom: 3px solid #23485B ;
  }

  .btn-outline-secondary{
    color: #23485B;
    border: thin;
  }

  .sidedivtext{
    color: #23485B;
  }

  .alert-dark{
    background-color: #F5F5F5;
  }

  .bg-light{
    background-color: #F5F5F5;
  }

  .text{
    color: #797979;
  }

  .tableicons{
  margin-right:25px;
  opacity:60% ;
  }

  tr:hover .tableicons{
  opacity:100% ;
  }

  .tablename{
  padding-right:10vw;
  }

  .leftalign .tableicons {
    padding-left: 0;
  }

  body{
  padding-top: 60px;
  }

  .btn-primary{
  background-color: #002B42;
  font-size: 12px;
  border-radius: 4px;
  padding:10px;
  }

  .btn-light{
  background-color: transparent;
  border: none;
  color: black;
  font-size: 13px;
  outline: none;
  padding:10px;
  margin-left: 20px;
  }

  @media only screen and (max-width: 768px) {
    body{
        padding-top: 0!important;
    }
    .navbar{
      position: relative;
    }
    .navbar-nav{
      align-items: center;
      margin: 15px 0;
    }
    .nav-item{
      margin:5px 0;
    }
  .navpull{
      margin-right: 10px;
    }
  }

  <button class="navbar-toggler mr-5" type="button" data-toggle="collapse" data-target="#my-navbar" aria-controls="my-navbar" aria-expanded="false" aria-label="Toggle navigation">

    </button>

            <button type="button" class="btn btn-primary">  SAVED LISTS</button>

            <button class="btn btn-light">   SAVED FILTER</button>

            <button class="btn btn-light">   SEARCH HISTORY</button>

      <input class="form-control" name="search" [(ngModel)]="search" type="search" placeholder="Search" />

          Date
          List Name
          No. of Entities
          Actions

              {{items.date | date:'MMM dd' }}

            {{ items.name }}

            {{ items.entities }}

              <button type="button" class="btn btn-outline-secondary" (click)="getdetails(items)">
                Details
              </button>

No description yet
        +Add Description

{{str}}

stackblitz link

Body:
body{
padding-top:60px;
}

will do the thing


问:
AEM 6.5 WKND repo build issues
I created a maven project in batch mode by typing the following command:

mvn archetype:generate -B -DarchetypeGroupId=com.adobe.granite.archetypes -DarchetypeArtifactId=aem-project-archetype -DarchetypeVersion=22 -DgroupId=com.adobe.aem.guides -Dversion=0.0.1-SNAPSHOT -DappsFolderName=wknd -DartifactId=aem-guides-wknd -Dpackage=com.adobe.aem.guides.wknd -DartifactName="WKND Sites Project" -DcomponentGroupName=WKND -DconfFolderName=wknd -DcontentFolderName=wknd -DcssId=wknd -DisSingleCountryWebsite=n -Dlanguage_country=en_us -DoptionAemVersion=6.5.0 -DoptionDispatcherConfig=none -DoptionIncludeErrorHandler=n -DoptionIncludeExaples=y -DoptionIncludeFrontendModule=y -DpackageGroup=wknd -DsiteName="WKND Site"
```

when I type mvn -PautoInstallSinglePackage clean install

I get the following error:

[ERROR] Failed to execute goal on project aem-guides-wknd.ui.apps: Could not resolve dependencies for project com.adobe.aem.guides:aem-guides-wknd.ui.apps:content-package:0.0.1-SNAPSHOT: Could not find artifact com.adobe.aem.guides:aem-guides-wknd.ui.frontend:zip:0.0.1-SNAPSHOT

From the error I guess and when I searched that there is no such artifactid in maven repository. Can someone please help me out here?

答: If your sole requirement is to build the wknd project, then just download the maven project from git and import it as a maven project in eclipse. After that build it. That should hopefully resolve your issue. </p>

Title: AEM 6.5 WKND repo build issues

Body:
I created a maven project in batch mode by typing the following command:

mvn archetype:generate -B -DarchetypeGroupId=com.adobe.granite.archetypes -DarchetypeArtifactId=aem-project-archetype -DarchetypeVersion=22 -DgroupId=com.adobe.aem.guides -Dversion=0.0.1-SNAPSHOT -DappsFolderName=wknd -DartifactId=aem-guides-wknd -Dpackage=com.adobe.aem.guides.wknd -DartifactName="WKND Sites Project" -DcomponentGroupName=WKND -DconfFolderName=wknd -DcontentFolderName=wknd -DcssId=wknd -DisSingleCountryWebsite=n -Dlanguage_country=en_us -DoptionAemVersion=6.5.0 -DoptionDispatcherConfig=none -DoptionIncludeErrorHandler=n -DoptionIncludeExaples=y -DoptionIncludeFrontendModule=y -DpackageGroup=wknd -DsiteName="WKND Site"

when I type mvn -PautoInstallSinglePackage clean install

I get the following error:

[ERROR] Failed to execute goal on project aem-guides-wknd.ui.apps: Could not resolve dependencies for project com.adobe.aem.guides:aem-guides-wknd.ui.apps:content-package:0.0.1-SNAPSHOT: Could not find artifact com.adobe.aem.guides:aem-guides-wknd.ui.frontend:zip:0.0.1-SNAPSHOT

From the error I guess and when I searched that there is no such artifactid in maven repository. Can someone please help me out here?


问:
Cant add data to databases on Spring Boot using Heroku postgres
I've been trying to get a Rest Repository up and running using Heroku.  However, while the tables I'm using are being added to the datasource, I am unable to upload any rows of data.

Shows that my tables are being added to postgres datasource

I don't get any error messages or issues deploying the service, I just can't add data.

I've looked around the internet for solutions currently application.properties is a mess of different bits of code that I've copied on all the guides for how to get a database running.

```<code>#spring.h2.console.enabled=true
#spring.datasource.url=jdbc:h2:mem:testdb
#spring.datasource.driverClassName=org.h2.Driver
#spring.datasource.username=sa
#spring.datasource.password=
#spring.h2.console.settings.web-allow-others=true

#spring.main.banner-mode=off
#logging.level.org.springframework=ERROR

spring.jpa.hibernate.ddl-auto=update

#spring.datasource.initialization-mode=always
spring.datasource.platform=postgres
#spring.datasource.url=postgres://npwovtbfrmcgap:8cb0a1d61d6608e756d4340bb79926156b43c5d602580ab21884d058b7adf230@ec2-52-23-14-156.compute-1.amazonaws.com:5432/deu5uhuf0in93s
#spring.datasource.url=${JDBC_DATABASE_URL}
#spring.datasource.username=${SPRING_DATABASE_USERNAME}
#spring.datasource.password=${SPRING_DATABASE_PASSWORD}
#spring.jpa.show-sql=true
#spring.jpa.generate-ddl=true
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}
spring.jpa.show-sql=false
spring.jpa.generate-ddl=true
</code>```

For testing I used h2 and that worked fine with no issues.  Even though I've been eyeing using JDBC _DATABASE for it's easy setup, I've made a Database Configuration file.

```<code>package com.example.chess.Config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DatabaseConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource()
    {
        return new org.apache.tomcat.jdbc.pool.DataSource();
    }
}
</code>```

There isn't a whole lot here, but from my understanding I shouldn't need one if I'm using a JDBC Database.

Some ideas that I have...

Heroku could be forcing me to use their guide on preparing a Spring Boot App for production
https://devcenter.heroku.com/articles/preparing-a-spring-boot-app-for-production-on-heroku

I could put better @GeneratedValue typing on the code for tables I have.

```<code>package com.example.chess.Model;

import javax.persistence.*;

@Entity
public class Chat {

    @GeneratedValue
    @Id
    @Column
    private int chatID;

    @Column
    private String chatMsg;

    public int getChatID() {
        return chatID;
    }

    public String getChatMsg() {
        return chatMsg;
    }

    public void setChatID(int chatID) {
        this.chatID = chatID;
    }

    public void setChatMsg(String chatMsg) {
        this.chatMsg = chatMsg;
    }
}
</code>```

Past that I'm not really sure what to do.  Any feedback is appreciated.

Thanks for all the help, however I still havent gotten it working.  I used heroku logs to find more data.  I also used spring.database.platform and spring.datasource.driver-class-name.  the code for application properties has been updated.

```<code>2020-02-18T02:22:38.000000+00:00 app[api]: Build succeeded
2020-02-18T02:22:41.021726+00:00 app[web.1]: 2020-02-18 02:22:41.017  INFO 4 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$28f59fce] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-02-18T02:22:41.264675+00:00 app[web.1]:
2020-02-18T02:22:41.264732+00:00 app[web.1]: .   ____          _            __ _ _
2020-02-18T02:22:41.264786+00:00 app[web.1]: /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
2020-02-18T02:22:41.264849+00:00 app[web.1]: ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
2020-02-18T02:22:41.264905+00:00 app[web.1]: \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
2020-02-18T02:22:41.264972+00:00 app[web.1]: '  |____| .__|_| |_|_| |_\__, | / / / /
2020-02-18T02:22:41.265009+00:00 app[web.1]: =========|_|==============|___/=/_/_/_/
2020-02-18T02:22:41.265886+00:00 app[web.1]: :: Spring Boot ::        (v2.1.7.RELEASE)
2020-02-18T02:22:41.265938+00:00 app[web.1]:
2020-02-18T02:22:41.335856+00:00 app[web.1]: 2020-02-18 02:22:41.335  INFO 4 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
2020-02-18T02:22:41.566210+00:00 app[web.1]: 2020-02-18 02:22:41.565  INFO 4 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Connect Timeout Exception on Url - http://localhost:8888. Will be trying the next url if available
2020-02-18T02:22:41.566423+00:00 app[web.1]: 2020-02-18 02:22:41.566  WARN 4 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/application/default": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)
2020-02-18T02:22:41.570798+00:00 app[web.1]: 2020-02-18 02:22:41.570  INFO 4 --- [           main] com.example.chess.ChessApplication       : No active profile set, falling back to default profiles: default
2020-02-18T02:22:42.945648+00:00 app[web.1]: 2020-02-18 02:22:42.943  INFO 4 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2020-02-18T02:22:43.135659+00:00 app[web.1]: 2020-02-18 02:22:43.135  INFO 4 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 157ms. Found 4 repository interfaces.
2020-02-18T02:22:43.711365+00:00 app[web.1]: 2020-02-18 02:22:43.711  INFO 4 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=de70dafe-40e0-316f-93ef-ef4b324ee017
2020-02-18T02:22:43.965692+00:00 app[web.1]: 2020-02-18 02:22:43.965  INFO 4 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$cdb9cd1] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-02-18T02:22:44.025903+00:00 app[web.1]: 2020-02-18 02:22:44.025  INFO 4 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$28f59fce] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-02-18T02:22:44.561043+00:00 app[web.1]: 2020-02-18 02:22:44.560  INFO 4 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 37710 (http)
2020-02-18T02:22:44.670131+00:00 app[web.1]: 2020-02-18 02:22:44.669  INFO 4 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-02-18T02:22:44.670471+00:00 app[web.1]: 2020-02-18 02:22:44.670  INFO 4 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.22]
2020-02-18T02:22:45.421352+00:00 app[web.1]: 2020-02-18 02:22:45.421  INFO 4 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-02-18T02:22:45.421626+00:00 app[web.1]: 2020-02-18 02:22:45.421  INFO 4 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3826 ms
2020-02-18T02:22:45.859027+00:00 app[web.1]: 2020-02-18 02:22:45.858  INFO 4 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-02-18T02:22:46.292693+00:00 app[web.1]: 2020-02-18 02:22:46.292  INFO 4 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-02-18T02:22:46.414129+00:00 app[web.1]: 2020-02-18 02:22:46.413  INFO 4 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
2020-02-18T02:22:46.414131+00:00 app[web.1]: name: default
2020-02-18T02:22:46.414131+00:00 app[web.1]: ...]
2020-02-18T02:22:46.563652+00:00 app[web.1]: 2020-02-18 02:22:46.563  INFO 4 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.10.Final}
2020-02-18T02:22:46.566628+00:00 app[web.1]: 2020-02-18 02:22:46.566  INFO 4 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2020-02-18T02:22:46.824490+00:00 app[web.1]: 2020-02-18 02:22:46.824  INFO 4 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2020-02-18T02:22:47.331763+00:00 app[web.1]: 2020-02-18 02:22:47.331  INFO 4 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2020-02-18T02:22:47.616894+00:00 app[web.1]: 2020-02-18 02:22:47.616  INFO 4 --- [           main] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
2020-02-18T02:22:47.624236+00:00 app[web.1]: 2020-02-18 02:22:47.623  INFO 4 --- [           main] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@37e4d7bb
2020-02-18T02:22:48.869877+00:00 app[web.1]: 2020-02-18 02:22:48.869  INFO 4 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-02-18T02:22:49.329464+00:00 app[web.1]: 2020-02-18 02:22:49.329  INFO 4 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2020-02-18T02:22:50.308149+00:00 app[web.1]: 2020-02-18 02:22:50.307  INFO 4 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-02-18T02:22:50.411820+00:00 app[web.1]: 2020-02-18 02:22:50.409  WARN 4 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-02-18T02:22:50.461378+00:00 app[web.1]: 2020-02-18 02:22:50.461  INFO 4 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]
2020-02-18T02:22:51.073701+00:00 heroku[web.1]: State changed from starting to up
2020-02-18T02:22:50.863588+00:00 app[web.1]: 2020-02-18 02:22:50.863  INFO 4 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 37710 (http) with context path ''
2020-02-18T02:22:50.865846+00:00 app[web.1]: 2020-02-18 02:22:50.865  INFO 4 --- [           main] com.example.chess.ChessApplication       : Started ChessApplication in 12.027 seconds (JVM running for 12.976)
</code>```

答: Try adding dialect , driver-class name and database-platform as you have commented those.</p>

Body:
I've been trying to get a Rest Repository up and running using Heroku.  However, while the tables I'm using are being added to the datasource, I am unable to upload any rows of data.

Shows that my tables are being added to postgres datasource

I don't get any error messages or issues deploying the service, I just can't add data.

I've looked around the internet for solutions currently application.properties is a mess of different bits of code that I've copied on all the guides for how to get a database running.

#spring.h2.console.enabled=true
#spring.datasource.url=jdbc:h2:mem:testdb
#spring.datasource.driverClassName=org.h2.Driver
#spring.datasource.username=sa
#spring.datasource.password=
#spring.h2.console.settings.web-allow-others=true

#spring.main.banner-mode=off
#logging.level.org.springframework=ERROR

spring.jpa.hibernate.ddl-auto=update

#spring.datasource.initialization-mode=always
spring.datasource.platform=postgres
#spring.datasource.url=postgres://npwovtbfrmcgap:8cb0a1d61d6608e756d4340bb79926156b43c5d602580ab21884d058b7adf230@ec2-52-23-14-156.compute-1.amazonaws.com:5432/deu5uhuf0in93s
#spring.datasource.url=${JDBC_DATABASE_URL}
#spring.datasource.username=${SPRING_DATABASE_USERNAME}
#spring.datasource.password=${SPRING_DATABASE_PASSWORD}
#spring.jpa.show-sql=true
#spring.jpa.generate-ddl=true
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}
spring.jpa.show-sql=false
spring.jpa.generate-ddl=true

For testing I used h2 and that worked fine with no issues.  Even though I've been eyeing using JDBC _DATABASE for it's easy setup, I've made a Database Configuration file.

package com.example.chess.Config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DatabaseConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource()
    {
        return new org.apache.tomcat.jdbc.pool.DataSource();
    }
}

There isn't a whole lot here, but from my understanding I shouldn't need one if I'm using a JDBC Database.

Some ideas that I have...

Heroku could be forcing me to use their guide on preparing a Spring Boot App for production
https://devcenter.heroku.com/articles/preparing-a-spring-boot-app-for-production-on-heroku

I could put better @GeneratedValue typing on the code for tables I have.

package com.example.chess.Model;

import javax.persistence.*;

@Entity
public class Chat {

    @GeneratedValue
    @Id
    @Column
    private int chatID;

    @Column
    private String chatMsg;

    public int getChatID() {
        return chatID;
    }

    public String getChatMsg() {
        return chatMsg;
    }

    public void setChatID(int chatID) {
        this.chatID = chatID;
    }

    public void setChatMsg(String chatMsg) {
        this.chatMsg = chatMsg;
    }
}

Past that I'm not really sure what to do.  Any feedback is appreciated.

Thanks for all the help, however I still havent gotten it working.  I used heroku logs to find more data.  I also used spring.database.platform and spring.datasource.driver-class-name.  the code for application properties has been updated.

2020-02-18T02:22:38.000000+00:00 app[api]: Build succeeded
2020-02-18T02:22:41.021726+00:00 app[web.1]: 2020-02-18 02:22:41.017  INFO 4 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$28f59fce] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-02-18T02:22:41.264675+00:00 app[web.1]:
2020-02-18T02:22:41.264732+00:00 app[web.1]: .   ____          _            __ _ _
2020-02-18T02:22:41.264786+00:00 app[web.1]: /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
2020-02-18T02:22:41.264849+00:00 app[web.1]: ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
2020-02-18T02:22:41.264905+00:00 app[web.1]: \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
2020-02-18T02:22:41.264972+00:00 app[web.1]: '  |____| .__|_| |_|_| |_\__, | / / / /
2020-02-18T02:22:41.265009+00:00 app[web.1]: =========|_|==============|___/=/_/_/_/
2020-02-18T02:22:41.265886+00:00 app[web.1]: :: Spring Boot ::        (v2.1.7.RELEASE)
2020-02-18T02:22:41.265938+00:00 app[web.1]:
2020-02-18T02:22:41.335856+00:00 app[web.1]: 2020-02-18 02:22:41.335  INFO 4 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
2020-02-18T02:22:41.566210+00:00 app[web.1]: 2020-02-18 02:22:41.565  INFO 4 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Connect Timeout Exception on Url - http://localhost:8888. Will be trying the next url if available
2020-02-18T02:22:41.566423+00:00 app[web.1]: 2020-02-18 02:22:41.566  WARN 4 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/application/default": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)
2020-02-18T02:22:41.570798+00:00 app[web.1]: 2020-02-18 02:22:41.570  INFO 4 --- [           main] com.example.chess.ChessApplication       : No active profile set, falling back to default profiles: default
2020-02-18T02:22:42.945648+00:00 app[web.1]: 2020-02-18 02:22:42.943  INFO 4 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2020-02-18T02:22:43.135659+00:00 app[web.1]: 2020-02-18 02:22:43.135  INFO 4 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 157ms. Found 4 repository interfaces.
2020-02-18T02:22:43.711365+00:00 app[web.1]: 2020-02-18 02:22:43.711  INFO 4 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=de70dafe-40e0-316f-93ef-ef4b324ee017
2020-02-18T02:22:43.965692+00:00 app[web.1]: 2020-02-18 02:22:43.965  INFO 4 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$cdb9cd1] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-02-18T02:22:44.025903+00:00 app[web.1]: 2020-02-18 02:22:44.025  INFO 4 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$28f59fce] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-02-18T02:22:44.561043+00:00 app[web.1]: 2020-02-18 02:22:44.560  INFO 4 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 37710 (http)
2020-02-18T02:22:44.670131+00:00 app[web.1]: 2020-02-18 02:22:44.669  INFO 4 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-02-18T02:22:44.670471+00:00 app[web.1]: 2020-02-18 02:22:44.670  INFO 4 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.22]
2020-02-18T02:22:45.421352+00:00 app[web.1]: 2020-02-18 02:22:45.421  INFO 4 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-02-18T02:22:45.421626+00:00 app[web.1]: 2020-02-18 02:22:45.421  INFO 4 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3826 ms
2020-02-18T02:22:45.859027+00:00 app[web.1]: 2020-02-18 02:22:45.858  INFO 4 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-02-18T02:22:46.292693+00:00 app[web.1]: 2020-02-18 02:22:46.292  INFO 4 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-02-18T02:22:46.414129+00:00 app[web.1]: 2020-02-18 02:22:46.413  INFO 4 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
2020-02-18T02:22:46.414131+00:00 app[web.1]: name: default
2020-02-18T02:22:46.414131+00:00 app[web.1]: ...]
2020-02-18T02:22:46.563652+00:00 app[web.1]: 2020-02-18 02:22:46.563  INFO 4 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.10.Final}
2020-02-18T02:22:46.566628+00:00 app[web.1]: 2020-02-18 02:22:46.566  INFO 4 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2020-02-18T02:22:46.824490+00:00 app[web.1]: 2020-02-18 02:22:46.824  INFO 4 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2020-02-18T02:22:47.331763+00:00 app[web.1]: 2020-02-18 02:22:47.331  INFO 4 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2020-02-18T02:22:47.616894+00:00 app[web.1]: 2020-02-18 02:22:47.616  INFO 4 --- [           main] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
2020-02-18T02:22:47.624236+00:00 app[web.1]: 2020-02-18 02:22:47.623  INFO 4 --- [           main] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@37e4d7bb
2020-02-18T02:22:48.869877+00:00 app[web.1]: 2020-02-18 02:22:48.869  INFO 4 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-02-18T02:22:49.329464+00:00 app[web.1]: 2020-02-18 02:22:49.329  INFO 4 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2020-02-18T02:22:50.308149+00:00 app[web.1]: 2020-02-18 02:22:50.307  INFO 4 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-02-18T02:22:50.411820+00:00 app[web.1]: 2020-02-18 02:22:50.409  WARN 4 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-02-18T02:22:50.461378+00:00 app[web.1]: 2020-02-18 02:22:50.461  INFO 4 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]
2020-02-18T02:22:51.073701+00:00 heroku[web.1]: State changed from starting to up
2020-02-18T02:22:50.863588+00:00 app[web.1]: 2020-02-18 02:22:50.863  INFO 4 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 37710 (http) with context path ''
2020-02-18T02:22:50.865846+00:00 app[web.1]: 2020-02-18 02:22:50.865  INFO 4 --- [           main] com.example.chess.ChessApplication       : Started ChessApplication in 12.027 seconds (JVM running for 12.976)


问:
Stop people uploading malicious PHP files via forms
I have an upload form created in php on my website where people are able to upload a zip file. The zip file is then extracted and all file locations are added to a database. The upload form is for people to upload pictures only, obviously, with the files being inside the zip folder I cant check what files are being uploaded until the file has been extracted. I need a piece of code which will delete all the files which aren't image formats (.png, .jpeg, etc). I'm really worried about people being able to upload malicious php files, big security risk! I also need to be aware of people changing the extensions of php files trying to get around this security feature.

This is the original script I used http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/

This is the code which actually extracts the .zip file:

```<code>function openZip($file_to_open) {
    global $target;

    $zip = new ZipArchive();
    $x = $zip->open($file_to_open);
    if($x === true) {
        $zip->extractTo($target);
        $zip->close();

        unlink($file_to_open);
    } else {
        die("There was a problem. Please try again!");
    }
}
</code>```

Thanks, Ben.

答:
Now you are relying on your harddrive space for extracting. You can check fileheaders to determine what kind of files they are. there probably libraries for that.

offtopic: isnt it better to let the user select couple of images instead of uploading a zip file. Better for people that don't know what zip is (yes they exist)

OwnerDisplayName: Ben McRae

Body:
I have an upload form created in php on my website where people are able to upload a zip file. The zip file is then extracted and all file locations are added to a database. The upload form is for people to upload pictures only, obviously, with the files being inside the zip folder I cant check what files are being uploaded until the file has been extracted. I need a piece of code which will delete all the files which aren't image formats (.png, .jpeg, etc). I'm really worried about people being able to upload malicious php files, big security risk! I also need to be aware of people changing the extensions of php files trying to get around this security feature.

This is the original script I used http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/

This is the code which actually extracts the .zip file:

function openZip($file_to_open) {
    global $target;

    $zip = new ZipArchive();
    $x = $zip->open($file_to_open);
    if($x === true) {
        $zip->extractTo($target);
        $zip->close();

        unlink($file_to_open);
    } else {
        die("There was a problem. Please try again!");
    }
}

Thanks, Ben.

LastEditorDisplayName: gs

OwnerDisplayName: PoweRoy

ContentLicense: CC BY-SA 2.5


问:
Xamarin iOS webview underlap behind navigation bar
I am using xamarin custom webview to load my page in app. But facing issue that title of webpage hides behind navigation bar . Or sometimes bottom of page not shown. I have tried adding scrollbar to my layout but still facing issue. Same works perfectly on android. Is it due to custom webview? I just want my webview to start below navigation bar and load completely according to device size.

my custom webview code :

```<code>public class CustomWebView : WebView
    {
        public static readonly BindableProperty UriProperty = BindableProperty.Create(
        propertyName: "Uri",
        returnType: typeof(string),
        declaringType: typeof(CustomWebView),
        defaultValue: default(string));

        public string Uri
        {
            get { return (string)GetValue(UriProperty); }
            set { SetValue(UriProperty, value); }
        }
    }
</code>```

Xaml Page :

```<code><StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand">
            <StackLayout>
                <Label x:Name="type" Text="Loading..." FontSize="Medium"/>
            </StackLayout>
            <StackLayout  VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                <ScrollView Orientation="Vertical" FlowDirection="MatchParent" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand" Visual="Material" VerticalScrollBarVisibility="Always">
                    <OnPlatform x:TypeArguments="View">
                        <On Platform="Android">
                            <WebView  x:Name="dashboard_android"  HeightRequest="1000" WidthRequest="1000"  />
                        </On>
                        <On Platform="iOS">
                            <local:CustomWebView  x:Name="dashboard_ios" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand"  WidthRequest="1000"  HeightRequest="1000"/>
                        </On>
                    </OnPlatform>
                </ScrollView>

            </StackLayout>
        </StackLayout>
</code>```

code behind :

```<code>dashboard_android.Source = url;
  dashboard_ios.Uri = url;
</code>```

Following are solutions i have tried but no success

Solution 1 :
I have tried adding two properties, but no use

```<code>this.EdgesForExtendedLayout = UIRectEdge.None;

   this.ExtendedLayoutIncludesOpaqueBars = false;
</code>```

Solution 2 :

Tried enabling this unsafe area property , still no success

```<code>ios:Page.UseSafeArea="true"
</code>```

Solution 3 :

Tried setting webview height on content size dynamically , but no success

```<code> public override async void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
        {
            // base.DidFinishNavigation(webView, navigation);

            var wv = _webViewRenderer.Element as CustomWebView;
            if (wv != null)
            {
                await System.Threading.Tasks.Task.Delay(100); // wait here till content is rendered
                wv.HeightRequest = (double)webView.Frame.Size.Height; // ScrollView.ContentSize.Height;
            }

        }
</code>```

Updated Xaml Code :

```<code> <StackLayout  VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
 <local:CustomWebView  x:Name="dashboard"  HeightRequest="1000" WidthRequest="1000" />
</StackLayout>
</code>```

Updated Code behind :

```<code>public partial class DashboardView : ContentPage
    {
        string url;
        public DashboardView()
        {
            InitializeComponent();
            url= ""; //adding url to load here
           dashboard.Uri = url;

      }
    }
</code>```

Custom WebView Renderer

```<code>    [assembly: ExportRenderer(typeof(CustomWebView), typeof(MyCustomWebViewRenderer))]
    namespace Report.iOS
    {

        public class MyCustomWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
        {
            WKWebView webView;
            protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
            {
                base.OnElementChanged(e);

                if (Control == null)
                {
                    webView = new WKWebView(Frame, new WKWebViewConfiguration());

                    webView.NavigationDelegate = new WebViewDelegate();

                    SetNativeControl(webView);

                }
                if (e.NewElement != null)
                {

                   Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Uri)));

                }
            }

    }

    public  class WebViewDelegate : WKNavigationDelegate, INSUrlConnectionDataDelegate
    {
        string uname = null;
        string pass = null;

        public override async void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            try
            {
                uname = Xamarin.Forms.Application.Current.Properties.ContainsKey("Username") ? Convert.ToString(Xamarin.Forms.Application.Current.Properties["Username"]) : null;
                pass = await SecureStorage.GetAsync("Password");
            }
            catch (Exception ex)
            {

            }
            completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, new NSUrlCredential(uname, pass, NSUrlCredentialPersistence.ForSession));

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

Screenshot of webview screen :

Here i am loading this webpage(https://learn.microsoft.com/en-us/xamarin/essentials/device-display?tabs=android). As you can see half of footer is hidden and i am not able to scroll it.

Screenshot of app

答:
The reason for it quite simple actually you have added the WebView inside a scrollView which is, in turn, causing the issue webview has its own scroll so all you have to do is something like:

```<code>        <StackLayout  VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
           <local:CustomWebView  x:Name="dashboard" />
        </StackLayout>
</code>```

Also, you do not need the on the platform you can directly use the below and the custom renderer you have created.

The Height/Width request & layout options are not needed Webview by default will capture the whole viewport, You could actually even remove the StackLayouts, But that's on you.

Also, you might wanna read more about the webview

Good luck

Feel free to get back if you have queries

Body:
I am using xamarin custom webview to load my page in app. But facing issue that title of webpage hides behind navigation bar . Or sometimes bottom of page not shown. I have tried adding scrollbar to my layout but still facing issue. Same works perfectly on android. Is it due to custom webview? I just want my webview to start below navigation bar and load completely according to device size.

my custom webview code :

public class CustomWebView : WebView
    {
        public static readonly BindableProperty UriProperty = BindableProperty.Create(
        propertyName: "Uri",
        returnType: typeof(string),
        declaringType: typeof(CustomWebView),
        defaultValue: default(string));

        public string Uri
        {
            get { return (string)GetValue(UriProperty); }
            set { SetValue(UriProperty, value); }
        }
    }

Xaml Page :

<StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand">
            <StackLayout>

            </StackLayout>
            <StackLayout  VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                <ScrollView Orientation="Vertical" FlowDirection="MatchParent" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand" Visual="Material" VerticalScrollBarVisibility="Always">
                    <OnPlatform x:TypeArguments="View">
                        <On Platform="Android">
                            <WebView  x:Name="dashboard_android"  HeightRequest="1000" WidthRequest="1000"  />
                        </On>
                        <On Platform="iOS">
                            <local:CustomWebView  x:Name="dashboard_ios" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand"  WidthRequest="1000"  HeightRequest="1000"/>
                        </On>
                    </OnPlatform>
                </ScrollView>

            </StackLayout>
        </StackLayout>

code behind :

dashboard_android.Source = url;
  dashboard_ios.Uri = url;

Following are solutions i have tried but no success

Solution 1 :
I have tried adding two properties, but no use

this.EdgesForExtendedLayout = UIRectEdge.None;

   this.ExtendedLayoutIncludesOpaqueBars = false;

Solution 2 :

Tried enabling this unsafe area property , still no success

ios:Page.UseSafeArea="true"

Solution 3 :

Tried setting webview height on content size dynamically , but no success

 public override async void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
        {
            // base.DidFinishNavigation(webView, navigation);

            var wv = _webViewRenderer.Element as CustomWebView;
            if (wv != null)
            {
                await System.Threading.Tasks.Task.Delay(100); // wait here till content is rendered
                wv.HeightRequest = (double)webView.Frame.Size.Height; // ScrollView.ContentSize.Height;
            }

        }

Updated Xaml Code :

 <StackLayout  VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
 <local:CustomWebView  x:Name="dashboard"  HeightRequest="1000" WidthRequest="1000" />
</StackLayout>

Updated Code behind :

public partial class DashboardView : ContentPage
    {
        string url;
        public DashboardView()
        {
            InitializeComponent();
            url= ""; //adding url to load here
           dashboard.Uri = url;

      }
    }

Custom WebView Renderer

    [assembly: ExportRenderer(typeof(CustomWebView), typeof(MyCustomWebViewRenderer))]
    namespace Report.iOS
    {

        public class MyCustomWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
        {
            WKWebView webView;
            protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
            {
                base.OnElementChanged(e);

                if (Control == null)
                {
                    webView = new WKWebView(Frame, new WKWebViewConfiguration());

                    webView.NavigationDelegate = new WebViewDelegate();

                    SetNativeControl(webView);

                }
                if (e.NewElement != null)
                {

                   Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Uri)));

                }
            }

    }

    public  class WebViewDelegate : WKNavigationDelegate, INSUrlConnectionDataDelegate
    {
        string uname = null;
        string pass = null;

        public override async void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            try
            {
                uname = Xamarin.Forms.Application.Current.Properties.ContainsKey("Username") ? Convert.ToString(Xamarin.Forms.Application.Current.Properties["Username"]) : null;
                pass = await SecureStorage.GetAsync("Password");
            }
            catch (Exception ex)
            {

            }
            completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, new NSUrlCredential(uname, pass, NSUrlCredentialPersistence.ForSession));

            return;
        }
    }
}

Screenshot of webview screen :

Here i am loading this webpage(https://learn.microsoft.com/en-us/xamarin/essentials/device-display?tabs=android). As you can see half of footer is hidden and i am not able to scroll it.

Screenshot of app

Body:
The reason for it quite simple actually you have added the WebView inside a scrollView which is, in turn, causing the issue webview has its own scroll so all you have to do is something like:

        <StackLayout  VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
           <local:CustomWebView  x:Name="dashboard" />
        </StackLayout>

Also, you do not need the on the platform you can directly use the below and the custom renderer you have created.

The Height/Width request & layout options are not needed Webview by default will capture the whole viewport, You could actually even remove the StackLayouts, But that's on you.

Also, you might wanna read more about the webview

Good luck

Feel free to get back if you have queries


问:
How to set image transparent for non-transparent part from another image?
I have two images: img1 and img2, and img2 is transparent except for one part of the image.

Using Pillow, how to crop the non-transparent part of img2 from img1? As a result, I would like to get img1 with transparent part, where img2 is non-transparent.

img1 and img2 are the same size.

答:
You can convert your Pillow images to NumPy arrays and make use of vectorized operations to speed up your processing.

Having img1.png (fully opaque random pixels)

and img2.png (fully transparent background pixels, fully opaque red pixels)

one could use this approach to achieve the described behaviour:

import numpy as np
from PIL import Image

# Open images via Pillow
img1 = Image.open('img1.png')
img2 = Image.open('img2.png')

# Convert images to NumPy arrays
img1_np = np.array(img1)
img2_np = np.array(img2)

# Get (only full) opaque pixels in img2 as mask
mask = img2_np[:, :, 3] == 255

# Make pixels in img1 within mask transparent
img1_np[mask, 3] = 0

# Convert image back to Pillow
img1 = Image.fromarray(img1_np)

# Save image
img1.save('img1_mod.png')
```

<p>The modified <code>img1_mod.png</code> would look like this (fully opaque random background pixels, transparent pixels where there's the red square in <code>img2.png</code>):</p>

<p><img src="https://i.stack.imgur.com/mG0Z6.png" alt="img1_mod"></p>

<p>If you have "smooth" transparency, i.e. your alpha channel has values from the whole range of <code>[0 ... 255]</code>, we could modify the code. Having such an <code>img2_smooth.png</code></p>

<p><img src="https://i.stack.imgur.com/1NEhM.png" alt="img2_smooth"></p>

<p>that'd be the modified code:</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
from PIL import Image

# Open images via Pillow
img1 = Image.open('img1.png')
img2 = Image.open('img2_smooth.png')

# Convert images to NumPy arrays
img1_np = np.array(img1)
img2_np = np.array(img2)

# Get (also partially) opaque pixels in img2 as mask         # <--
mask = img2_np[:, :, 3] > 0                                  # <--

# Make pixels in img1 within mask (partially) transparent    # <--
img1_np[mask, 3] = 255 - img2_np[mask, 3]                    # <--

# Convert image back to Pillow
img1 = Image.fromarray(img1_np)

# Save image
img1.save('img1_smooth_mod.png')
</code>```

And that'd be new output img1_smooth_mod.png:

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
Pillow:      7.0.0
----------------------------------------
```

Body:
You can convert your Pillow images to NumPy arrays and make use of vectorized operations to speed up your processing.

Having img1.png (fully opaque random pixels)

and img2.png (fully transparent background pixels, fully opaque red pixels)

one could use this approach to achieve the described behaviour:

import numpy as np
from PIL import Image

# Open images via Pillow
img1 = Image.open('img1.png')
img2 = Image.open('img2.png')

# Convert images to NumPy arrays
img1_np = np.array(img1)
img2_np = np.array(img2)

# Get (only full) opaque pixels in img2 as mask
mask = img2_np[:, :, 3] == 255

# Make pixels in img1 within mask transparent
img1_np[mask, 3] = 0

# Convert image back to Pillow
img1 = Image.fromarray(img1_np)

# Save image
img1.save('img1_mod.png')

The modified img1_mod.png would look like this (fully opaque random background pixels, transparent pixels where there's the red square in img2.png):

If you have "smooth" transparency, i.e. your alpha channel has values from the whole range of [0 ... 255], we could modify the code. Having such an img2_smooth.png

that'd be the modified code:

import numpy as np
from PIL import Image

# Open images via Pillow
img1 = Image.open('img1.png')
img2 = Image.open('img2_smooth.png')

# Convert images to NumPy arrays
img1_np = np.array(img1)
img2_np = np.array(img2)

# Get (also partially) opaque pixels in img2 as mask         # <--
mask = img2_np[:, :, 3] > 0                                  # <--

# Make pixels in img1 within mask (partially) transparent    # <--
img1_np[mask, 3] = 255 - img2_np[mask, 3]                    # <--

# Convert image back to Pillow
img1 = Image.fromarray(img1_np)

# Save image
img1.save('img1_smooth_mod.png')

And that'd be new output img1_smooth_mod.png:

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
Pillow:      7.0.0
----------------------------------------


答:
You have to change the

```<code>// Registering your Custom Post Type
register_post_type( 'Earnings Transcripts', $args );
</code>```

A change like this:

```<code>register_post_type('earnings-transcripts', $args);
</code>```

The below function will remove the slug from the permalink

```<code> function rf_remove_slug( $post_link, $post, $leavename ) {
  if ( 'earnings-transcripts' != $post->post_type || 'publish' != $post->post_status ) {
    return $post_link;
  }
  $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
  return $post_link;
}
add_filter( 'post_type_link', 'rf_remove_slug', 10, 3 );
</code>```

The below function will fix the issue of showing the 404 Not found error on the detailed post pages under this custom post type

```<code> function rf_parse_request( $query ) {
  if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
    return;
  }
  if ( ! empty( $query->query['name'] ) ) {
    $query->set( 'post_type', array( 'post', 'earnings-transcripts', 'page' ) );
  }
}
add_action( 'pre_get_posts', 'rf_parse_request' );
</code>```

Title: Hyphen missing in my Custom Post Type URL Slug

Body:
I have created a new Custom Post Type(Earnings Transcripts) in WordPress using the below code. The name of my Custom Post Type is "Earnings Transcripts" which is 2 words. So the slug should be "earnings-transcripts". Instead the URL is "earningstranscripts". What am I missing here?

function custom_post_type() {

    // Earnings Transcripts
    $labels = array(
        'name'                => _x( 'Earnings Transcripts', 'Post Type General Name', 'twentysixteen' ),
        'singular_name'       => _x( 'Earnings Transcripts', 'Post Type Singular Name', 'twentysixteen' ),
        'menu_name'           => __( 'Earnings Transcripts', 'twentysixteen' ),
        'parent_item_colon'   => __( 'Parent Earnings Transcripts', 'twentysixteen' ),
        'all_items'           => __( 'All Earnings Transcripts', 'twentysixteen' ),
        'view_item'           => __( 'View Earnings Transcripts', 'twentysixteen' ),
        'add_new_item'        => __( 'Add New Earnings Transcripts', 'twentysixteen' ),
        'add_new'             => __( 'Add New', 'twentysixteen' ),
        'edit_item'           => __( 'Edit Earnings Transcripts', 'twentysixteen' ),
        'update_item'         => __( 'Update Earnings Transcripts', 'twentysixteen' ),
        'search_items'        => __( 'Search Earnings Transcripts', 'twentysixteen' ),
        'not_found'           => __( 'Not Found', 'twentysixteen' ),
        'not_found_in_trash'  => __( 'Not found in Trash', 'twentysixteen' ),
    );
    $args = array(
        'label'               => __( 'Earnings Transcripts', 'twentysixteen' ),
        'description'         => __( 'Earnings Transcripts', 'twentysixteen' ),
        'labels'              => $labels,
        'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
        'taxonomies'          => array( 'Earnings Transcripts' ),
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 5,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'page',
    );
    // Registering your Custom Post Type
    register_post_type( 'Earnings Transcripts', $args );

}
add_action( 'init', 'custom_post_type', 0 );

Body:
You have to change the

// Registering your Custom Post Type
register_post_type( 'Earnings Transcripts', $args );

A change like this:

register_post_type('earnings-transcripts', $args);

The below function will remove the slug from the permalink

 function rf_remove_slug( $post_link, $post, $leavename ) {
  if ( 'earnings-transcripts' != $post->post_type || 'publish' != $post->post_status ) {
    return $post_link;
  }
  $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
  return $post_link;
}
add_filter( 'post_type_link', 'rf_remove_slug', 10, 3 );

The below function will fix the issue of showing the 404 Not found error on the detailed post pages under this custom post type

 function rf_parse_request( $query ) {
  if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
    return;
  }
  if ( ! empty( $query->query['name'] ) ) {
    $query->set( 'post_type', array( 'post', 'earnings-transcripts', 'page' ) );
  }
}
add_action( 'pre_get_posts', 'rf_parse_request' );


问:
AngularJS Filter array with a nested ng-repeat
I have this nested list that I would like to filter based in searchKey Input that contain a array of strings (kendo multiselector). The filter field should be the  {{ child.name }} field and the filter result should be applied to the main element on the first ng-repeat item in colection.items

I have no idea how can I filter this array of values against the array of keywords from the kendo input.
I try this similar case but with no success. AngularJS filter based on array of strings?.
Any help will be appreciated.

        <input id="searchKey" type="text" placeholder="Search keys" ng-model="listSearch" />

 0"
            class="block-grid-item">

{{ item.fileFormatIdentifier }}

                            {{ child.name }}

i

```

答:
Given I've got your problem statement correctly, it doesn't really matter what you filter on, as long as you can somehow inspect an item (and, look into its categories) and tell if it's a match for you.
As the answer you found points out, you can make a filter (for clarity call it multiSelectFilter)

        <select kendo-multi-select k-options="selectOptions" k-ng-model="listSearch"></select>

 0"
            class="block-grid-item">

{{ item.fileFormatIdentifier }}

                            {{ child.name }}

i

```

<pre class="lang-js prettyprint-override"><code>var app = angular.module('ngApp', ['kendo.directives']);

app.controller("ngAppController", function($scope){
      $scope.listItems = [{name:'Baseball'}, {name:'Basketball'}, {name:'Cricket'}, {name:'Field Hockey'}, {name:'Football'}, {name:'Table Tennis'}, {name:'Tennis'}, {name:'Volleyball'}];
      $scope.colection = {items: [
       {id:0, thumb: '0', fileFormatIdentifier :'1', categories: [{name:'Baseball'}, {name:'Basketball'}]},
        {id:1, thumb: '1', fileFormatIdentifier :'2', categories: [{name:'Cricket'}]},
        {id:2, thumb: '2', fileFormatIdentifier :'3', categories: [{name:'Field Hockey'}, {name:'Football'}]},
        {id:3, thumb: '3', fileFormatIdentifier :'4', categories: [{name:'Tennis'}, {name:'Volleyball'}]},
      ]
                          };
      $scope.listSearch = [];
      $scope.selectOptions = {
            placeholder: "Select products...",
            valuePrimitive: true,
            dataTextField: "name",
            dataValueField: "name",
            autoBind: false,
            dataSource: $scope.listItems
        };
});

app.filter('multiSelectFilter', function() {
    return function(items, listSearch) {
        return items.filter(function(item) {
            if(listSearch.length === 0)
              return true; // suppose we don't want to filter if no condition was set
            var result = false
            result = item.categories.some((child) => {
              return listSearch.some((listSearchItem) => {
                return (child.name === listSearchItem); // return true if we've got a match
            });
            });
          return result;
        });
    };
});
</code>```

Here's the working code pen: https://codepen.io/timur_kh/pen/xxGVzLv.

Body:
Given I've got your problem statement correctly, it doesn't really matter what you filter on, as long as you can somehow inspect an item (and, look into its categories) and tell if it's a match for you.
As the answer you found points out, you can make a filter (for clarity call it multiSelectFilter)

<div ng-app="ngApp">
<div ng-controller="ngAppController">
    <div id="filtering">
        <select kendo-multi-select k-options="selectOptions" k-ng-model="listSearch"></select> <!-- note custom kendo directives. See more documentation here: https://demos.telerik.com/kendo-ui/multiselect/angular  -->
    </div>
    <ul id="allItems">
        <li ng-repeat="item in colection.items | multiSelectFilter:listSearch"
            ng-show="colection.items.length > 0"
            class="block-grid-item">
            <a href="javascript: void(0);" data-detail="{{ item.Id }}">
                <div class="imageWrap" style="background-image:url({{ item.thumb }});">

                    <div class="filetypeContainer"><span>{{ item.fileFormatIdentifier }}</span></div>
                    <ul>
                        <li ng-repeat="child in item.categories" style="list-style: none; display: inline-block;">
                            <code style="font-size:11px;">{{ child.name }} </code>
                        </li>
                    </ul>
                    <div class="infoContainer">i</div>
                </div>
            </a>
        </li>
    </ul>
  </div>
</div>

var app = angular.module('ngApp', ['kendo.directives']);

app.controller("ngAppController", function($scope){
      $scope.listItems = [{name:'Baseball'}, {name:'Basketball'}, {name:'Cricket'}, {name:'Field Hockey'}, {name:'Football'}, {name:'Table Tennis'}, {name:'Tennis'}, {name:'Volleyball'}];
      $scope.colection = {items: [
       {id:0, thumb: '0', fileFormatIdentifier :'1', categories: [{name:'Baseball'}, {name:'Basketball'}]},
        {id:1, thumb: '1', fileFormatIdentifier :'2', categories: [{name:'Cricket'}]},
        {id:2, thumb: '2', fileFormatIdentifier :'3', categories: [{name:'Field Hockey'}, {name:'Football'}]},
        {id:3, thumb: '3', fileFormatIdentifier :'4', categories: [{name:'Tennis'}, {name:'Volleyball'}]},
      ]
                          };
      $scope.listSearch = [];
      $scope.selectOptions = {
            placeholder: "Select products...",
            valuePrimitive: true,
            dataTextField: "name",
            dataValueField: "name",
            autoBind: false,
            dataSource: $scope.listItems
        };
});

app.filter('multiSelectFilter', function() {
    return function(items, listSearch) {
        return items.filter(function(item) {
            if(listSearch.length === 0)
              return true; // suppose we don't want to filter if no condition was set
            var result = false
            result = item.categories.some((child) => {
              return listSearch.some((listSearchItem) => {
                return (child.name === listSearchItem); // return true if we've got a match
            });
            });
          return result;
        });
    };
});

Here's the working code pen: https://codepen.io/timur_kh/pen/xxGVzLv.


问:
HTML a href alignment
Currently, this is my code:

```<code>@media (max-width: 500px) {
  a {
    text-align: left;
    font-size: 90%;
    float: left;
  }
}
</code>```

How do I align my hyperlink to the right side?

Currently, if I am using float:left, it will be stacked with my other element.

Example

Fixed with the code > "clear: both" .

答:
In in order to make the anchor tag go the right you would need to use float right instead of float left. You can also align the text to the left

.linkright a {
  text-align: left;
  font-size: 2rem;
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="linkright">
   click me!
</div></code>```

Title: HTML a href alignment

Body:
Currently, this is my code:

@media (max-width: 500px) {
  a {
    text-align: left;
    font-size: 90%;
    float: left;
  }
}

How do I align my hyperlink to the right side?

Currently, if I am using float:left, it will be stacked with my other element.

Example

Fixed with the code > "clear: both" .

Body:
In in order to make the anchor tag go the right you would need to use float right instead of float left. You can also align the text to the left

.linkright a {
  text-align: left;
  font-size: 2rem;
  float: right;
}

<div class="linkright">
  <a href="#"> click me! </a>
</div>


问:
How can i search a json response to see if a value exists using linq?
I have the following json response

```<code>{
  "Id": "1234",
  "Name": "Test",
  "Orders": [
    {
      "OrderId": "87654",
      "OrderDetails": {
        "OrdId": "1234",
        "Name": "Desk"
      }
    },
    {
      "OrderId": "54213",
      "OrderDetails": {
        "OrdId": "4321",
        "Name": "Table"
      }
    }
  ]
}
</code>```

I want to search the list of orders to see if there is an OrderId of 87654.
I can do with an array , but how can I do it with Linq ?

答:
Demo on dotnet fiddle

You can use Newtonsoft to achieve it

```<code>var jsonData = "{ 'Id': '1234', 'Name': 'Test', 'Orders': [ {'OrderId': '87654', 'OrderDetails': { 'OrdId': '1234', 'Name': 'Desk' } }, { 'OrderId': '54213', 'OrderDetails': { 'OrdId': '4321','Name': 'Table' }}]}";

 var desirializedData = JsonConvert.DeserializeObject<MyObject>(jsonData);
 var result = desirializedData.Orders.Where(p => p.OrderId == 87654);
        foreach(var master in result)
        {
            Console.WriteLine(master.OrderId + " " + master.OrderDetails.Name);
        }
</code>```

Body:
I have the following json response

{
  "Id": "1234",
  "Name": "Test",
  "Orders": [
    {
      "OrderId": "87654",
      "OrderDetails": {
        "OrdId": "1234",
        "Name": "Desk"
      }
    },
    {
      "OrderId": "54213",
      "OrderDetails": {
        "OrdId": "4321",
        "Name": "Table"
      }
    }
  ]
}

I want to search the list of orders to see if there is an OrderId of 87654.
I can do with an array , but how can I do it with Linq ?

Body:
Demo on dotnet fiddle

You can use Newtonsoft to achieve it

var jsonData = "{ 'Id': '1234', 'Name': 'Test', 'Orders': [ {'OrderId': '87654', 'OrderDetails': { 'OrdId': '1234', 'Name': 'Desk' } }, { 'OrderId': '54213', 'OrderDetails': { 'OrdId': '4321','Name': 'Table' }}]}";

 var desirializedData = JsonConvert.DeserializeObject<MyObject>(jsonData);
 var result = desirializedData.Orders.Where(p => p.OrderId == 87654);
        foreach(var master in result)
        {
            Console.WriteLine(master.OrderId + " " + master.OrderDetails.Name);
        }