问:
Fetching data from function into <View> component inside the render method
I tried to fetch the data from function inside render, when I use alert() it works, but when I try to return real text it not shown any thing

the code I work with:

```<code>export default class App extends Component {
    renderResualts(){
        db.find({}, function (err, docs) {
           return docs.map(function(d){
              return(
                <Text>{d.name}</Text>
              )
           })
        })
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResualts() }
      </View>
    );
  }
}

</code>```

--
UPDATED CODE:

```<code>

export default class App extends Component {

    constructor(props){
        super(props)
        this.state = {graves:[]}
    }
    componentDidMount(){
        db.find({}, function (err, docs) {
            this.setState({graves:docs})
        })
    }

    renderResults(){
        return this.state.graves.map(grave =>
            <Text>{grave.name}</Text>
        )
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResults() }
      </View>
    );
  }
}

</code>```

It should be shown these data :

{
    _id: 1,
    name: 'Parturient',
    year: 2017
}, {
    _id: 2,
    name: 'Dapibus',
    year: 2017
}

inside text like so: ParturientDapibus

答:
By passing the data to State like so:</p>

```<code>
export default class App extends Component {

    constructor(props){
        super(props)
        this.state = {graves:[]}
    }
    componentDidMount(){
        db.find({}, (err, docs)=> {
            this.setState({graves:docs})
        })
    }

    renderResults(){
        return this.state.graves.map(grave =>
            <Text key={grave._id}>{grave.name}</Text>
        )
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResults() }
      </View>
    );
  }
}

</code>```

Body:
I tried to fetch the data from function inside render, when I use alert() it works, but when I try to return real text it not shown any thing

the code I work with:

export default class App extends Component {
    renderResualts(){
        db.find({}, function (err, docs) {
           return docs.map(function(d){
              return(
                <Text>{d.name}</Text>
              )
           })
        })
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResualts() }
      </View>
    );
  }
}

--
UPDATED CODE:

export default class App extends Component {

    constructor(props){
        super(props)
        this.state = {graves:[]}
    }
    componentDidMount(){
        db.find({}, function (err, docs) {
            this.setState({graves:docs})
        })
    }

    renderResults(){
        return this.state.graves.map(grave =>
            <Text>{grave.name}</Text>
        )
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResults() }
      </View>
    );
  }
}

It should be shown these data :

{
    _id: 1,
    name: 'Parturient',
    year: 2017
}, {
    _id: 2,
    name: 'Dapibus',
    year: 2017
}

inside text like so: ParturientDapibus

Body:
By passing the data to State like so:

export default class App extends Component {

    constructor(props){
        super(props)
        this.state = {graves:[]}
    }
    componentDidMount(){
        db.find({}, (err, docs)=> {
            this.setState({graves:docs})
        })
    }

    renderResults(){
        return this.state.graves.map(grave =>
            <Text key={grave._id}>{grave.name}</Text>
        )
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResults() }
      </View>
    );
  }
}


来源: stackexchange

问:
DB backend webapp testing in java [tool needed]
I want to create a test suit for my java web application. Its a JSP applications with JDBC connectivity . My requirements are as follows,

1 - I should be able to test my database logic (Queries etc) through my models.

2 - Its great if i could test my .jsp pages as well (if possible)

After doing some research I found that DBUnit is good for database backend system testing, but unfortunately i couldnt find any good resource as a starter

What are you all think about testing options I have and it would be great if you could post some links to resources/ examples as well

EDIT:

and I have come across with mock objects (like JMock..), wonder I could use it as a replacement for DBUnit ?

thanks in advance

cheers

sameera

答:
For your 1st question have a look at this StackOverFlow thread...

For 2nd, I would go with Chry's suggestion of Cactus or Selenium.

Hope that helps.

ContentLicense: CC BY-SA 3.0


问:
Firebase Realtime Database listener inside a loop is not working properly
I am using Firebase Realtime Database. I have an object which has all the posts created by all our users. This object is huge.

In order to display the posts in a fast way, we have given each user an object with relevant post IDs.

The structure looks like this:

```<code>/allPosts/$postID/
          : { $postID: {id: $postID, details: '', title: '', timestamp: ''} }

/user/$userID/postsRelevantToThisUser/
              : { $postID: {id: $postID} }
</code>```

'postsRelevantToThisUser' only contains the IDs of the posts. I need to iterate over each of these IDs and retrieve the entire post information from /allPosts/

As a result, the client won't have to download the entire allPosts object and the app will be much faster.

To do this, I've written the below code. It is successfully retrieving and rendering only the relevant posts. Whenever a new postID is added or removed from /postsRelevantToThisUser/ in Firebase Realtime Database, React Native correctly re-renders the list.

However, when anything in /allPosts/$postID changes, for exampe: if title parameter changes, it is not reflected in the view.

What's a good way to solve this problem?

```<code>let userPostRef = firebase.database().ref(`/users/${uid}/postsRelevantToThisUser`)

      userPostRef.on('value', (snapshot) => {
        let relPostIds = [];
        let posts = [];

        snapshot.forEach(function(childSnapshot) {
          const {id} = childSnapshot.val();
          relPostIds.push(id);
        })

        relPostIds.map(postId => {
          firebase.database().ref(`allPosts/${postId}`).on('value', (postSnapshot) => {
            let post  = postSnapshot.val()
            posts.push(post);
            this.setState({ postsToRender:posts });
          })

})

</code>```

答:
Since you've spread the data that you need to show the posts to the user over multiple places, you will need to keep listeners attached to multiple places if you want to get realtime updates about that data.

So to listen for title updates, you'll need to keep a listener to each /allPosts/$postID that the user can currently see. While it can be a bit finicky in code to keep track of all those listeners, they are actually quite efficient for Firebase itself, so performance should be fine up to a few dozen listeners at least (and it seems unlikely a user will be actively reading more post titles at once).

Alternatively, you can duplicate the information that you want to show in the list view, under each user's /user/$userID/postsRelevantToThisUser nodes. That way you're duplicating more data, but won't need the additional listeners.

Either approach is fine, but I have a personal preference for the latter, as it keeps the code that reads the data (which is the most critical for scalability) simpler.

ContentLicense: CC BY-SA 4.0

Body:
I am using Firebase Realtime Database. I have an object which has all the posts created by all our users. This object is huge.

In order to display the posts in a fast way, we have given each user an object with relevant post IDs.

The structure looks like this:

/allPosts/$postID/
          : { $postID: {id: $postID, details: '', title: '', timestamp: ''} }

/user/$userID/postsRelevantToThisUser/
              : { $postID: {id: $postID} }

'postsRelevantToThisUser' only contains the IDs of the posts. I need to iterate over each of these IDs and retrieve the entire post information from /allPosts/

As a result, the client won't have to download the entire allPosts object and the app will be much faster.

To do this, I've written the below code. It is successfully retrieving and rendering only the relevant posts. Whenever a new postID is added or removed from /postsRelevantToThisUser/ in Firebase Realtime Database, React Native correctly re-renders the list.

However, when anything in /allPosts/$postID changes, for exampe: if title parameter changes, it is not reflected in the view.

What's a good way to solve this problem?

let userPostRef = firebase.database().ref(`/users/${uid}/postsRelevantToThisUser`)

      userPostRef.on('value', (snapshot) => {
        let relPostIds = [];
        let posts = [];

        snapshot.forEach(function(childSnapshot) {
          const {id} = childSnapshot.val();
          relPostIds.push(id);
        })

        relPostIds.map(postId => {
          firebase.database().ref(`allPosts/${postId}`).on('value', (postSnapshot) => {
            let post  = postSnapshot.val()
            posts.push(post);
            this.setState({ postsToRender:posts });
          })

})


问:
How to make /login route accessible only for anonymous users in Symfony4?
My access_controll looks like:

```<code>- { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY}
- { path: ^/, roles: ROLE_USER}
</code>```

I need to give an access to route /login only to anonymously authenticated users.

答:
Okay, there's a better variant to do this even with redirect. Firstable, you need to edit security.yaml with this:

```<code>access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY}
        - { path: ^/, roles: ROLE_USER}
</code>```

And then just add this to your SecurityController::login() method:

```<code>if ($this->isGranted('ROLE_USER')) {
        return new RedirectResponse(
            $this->generateUrl('index')
        );
    }
</code>```

Body:
My access_controll looks like:

- { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY}
- { path: ^/, roles: ROLE_USER}

I need to give an access to route /login only to anonymously authenticated users.

Body:
Okay, there's a better variant to do this even with redirect. Firstable, you need to edit security.yaml with this:

access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY}
        - { path: ^/, roles: ROLE_USER}

And then just add this to your SecurityController::login() method:

if ($this->isGranted('ROLE_USER')) {
        return new RedirectResponse(
            $this->generateUrl('index')
        );
    }


问:
WooCommerce external product to new tab
I would like to have WooCommerce external/affiliate products open in a new tab. This would go for all aspects of a product: image, title, buy now button and archive pages(product category/tags). All I have been able to find is a way to change the "Buy Now" button but no other solutions to the other areas previously mentioned. Other solutions offer a the external link in all the right places(product image, title, buy now button, archive pages), but it can't open in a new tab.

I've tried a bunch of different codes, as mentioned above, all lead to partial solutions. I believe if these can be combined, it may work. But I haven't been successful.

```<code>add_action( 'template_redirect', 'redirect_external_products' );
function redirect_external_products() {
    global $post;
    if ( is_singular( 'product' ) && ! empty( $post ) && ( $product = wc_get_product( $post ) ) && $product->is_type( 'external' ) ) {
        wp_redirect( $product->get_product_url() );
        exit;
    }
}
</code>```

```<code>function custom_redirect() {
  global $post;
   if( is_single() ){
      $external_link =  get_post_meta( $post->ID, 'external_link', true );
      if($external_link) {
         echo "<script> window.open(".$external_link.", '_blank') </script>";
         exit;
      }
   }
}
</code>```

I would like all affiliate/external links to open in a new tab. This would include: product image, product title, buy now button, archive page listings(product category/tags).

All previous attempts will only open the Buy Now links in a new tab - but the image and title still direct to the single product page. The first code above from does the trick, but won't open in a new tab. My research tells me that when using the template_redirect function, link targeting is not possible.

答:
remove the previous code and let's add this code in the theme's functions.php file.</p>

```<code>add_filter( 'woocommerce_loop_product_link', 'filter_external_product_permalink', 10, 2 );

if ( ! function_exists( 'filter_external_product_permalink' ) ) {
/**
 * Insert the external url for products in the loop.
 */
function filter_external_product_permalink( $the_permalink, $product ){
    global $product;

    if( $product->is_type( 'external' ) ) {
        $external_link =  $product->get_product_url();
        return $external_link;
    }

    return $the_permalink;
}
}

if ( ! function_exists( 'woocommerce_template_loop_product_link_open' ) ) {
/**
 * Insert the opening anchor tag for products in the loop.
 */
function woocommerce_template_loop_product_link_open() {
    global $product;

    $link = apply_filters( 'woocommerce_loop_product_link', get_the_permalink(), $product );

    $link_target = $product->is_type( 'external' ) ? '_blank' : '_self';

    echo '<a target="' . esc_attr( $link_target ).'" href="' . esc_url( $link ) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">';
}
}

add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_external_add_product_link' , 10, 2 );

if ( ! function_exists( 'custom_external_add_product_link' ) ) {

function custom_external_add_product_link( $permalink ) {
    global $product;

    if ( $product->is_type( 'external' ) ) {

        $permalink = sprintf( '<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s" target="_blank">%s</a>',
            esc_url( $product->add_to_cart_url() ),
            esc_attr( isset( $quantity ) ? $quantity : 1 ),
            esc_attr( $product->id ),
            esc_attr( $product->get_sku() ),
            esc_attr( isset( $class ) ? $class : 'button product_type_external add_to_cart_button' ),
            esc_html( $product->add_to_cart_text() )
        );
    }

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

Title: WooCommerce external product to new tab

Body:
I would like to have WooCommerce external/affiliate products open in a new tab. This would go for all aspects of a product: image, title, buy now button and archive pages(product category/tags). All I have been able to find is a way to change the "Buy Now" button but no other solutions to the other areas previously mentioned. Other solutions offer a the external link in all the right places(product image, title, buy now button, archive pages), but it can't open in a new tab.

I've tried a bunch of different codes, as mentioned above, all lead to partial solutions. I believe if these can be combined, it may work. But I haven't been successful.

add_action( 'template_redirect', 'redirect_external_products' );
function redirect_external_products() {
    global $post;
    if ( is_singular( 'product' ) && ! empty( $post ) && ( $product = wc_get_product( $post ) ) && $product->is_type( 'external' ) ) {
        wp_redirect( $product->get_product_url() );
        exit;
    }
}

function custom_redirect() {
  global $post;
   if( is_single() ){
      $external_link =  get_post_meta( $post->ID, 'external_link', true );
      if($external_link) {
         echo "";
         exit;
      }
   }
}

I would like all affiliate/external links to open in a new tab. This would include: product image, product title, buy now button, archive page listings(product category/tags).

All previous attempts will only open the Buy Now links in a new tab - but the image and title still direct to the single product page. The first code above from does the trick, but won't open in a new tab. My research tells me that when using the template_redirect function, link targeting is not possible.

Body:
remove the previous code and let's add this code in the theme's functions.php file.

add_filter( 'woocommerce_loop_product_link', 'filter_external_product_permalink', 10, 2 );

if ( ! function_exists( 'filter_external_product_permalink' ) ) {
/**
 * Insert the external url for products in the loop.
 */
function filter_external_product_permalink( $the_permalink, $product ){
    global $product;

    if( $product->is_type( 'external' ) ) {
        $external_link =  $product->get_product_url();
        return $external_link;
    }

    return $the_permalink;
}
}

if ( ! function_exists( 'woocommerce_template_loop_product_link_open' ) ) {
/**
 * Insert the opening anchor tag for products in the loop.
 */
function woocommerce_template_loop_product_link_open() {
    global $product;

    $link = apply_filters( 'woocommerce_loop_product_link', get_the_permalink(), $product );

    $link_target = $product->is_type( 'external' ) ? '_blank' : '_self';

    echo '<a target="' . esc_attr( $link_target ).'" href="' . esc_url( $link ) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">';
}
}

add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_external_add_product_link' , 10, 2 );

if ( ! function_exists( 'custom_external_add_product_link' ) ) {

function custom_external_add_product_link( $permalink ) {
    global $product;

    if ( $product->is_type( 'external' ) ) {

        $permalink = sprintf( '<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s" target="_blank">%s</a>',
            esc_url( $product->add_to_cart_url() ),
            esc_attr( isset( $quantity ) ? $quantity : 1 ),
            esc_attr( $product->id ),
            esc_attr( $product->get_sku() ),
            esc_attr( isset( $class ) ? $class : 'button product_type_external add_to_cart_button' ),
            esc_html( $product->add_to_cart_text() )
        );
    }

    return $permalink;
}
}


问:
Can I change the SourceFile of a Node using the Typescript Compiler API?
I am currently trying to modify the body of a FunctionDeclaration using Typescript's compiler API. I am creating a few new VariableDeclarations, and the "initializer" field is being set using an expression that is derived from SourceFile A.

I am then attempting to add these new VariableDeclarations to the body of a FunctionDeclaration from SourceFile B, however the right-hand sides of those newly created VariableDeclarations are not printing properly when using SourceFile A as the sourcefile in printer.printFile(...). Semi-colons and operators seem to print, but no identifiers or literals.

The issue seems to be the differing SourceFiles, even though the identifiers used in both SourceFiles are exactly the same.

Is there a way to either set the SourceFile for those newly created VariableDeclarations (or really, for the "initializer" expression which is causing the issue)? If not, is there anything else I can do to be able to take an expression found in one SourceFile and use it in a different one?

答:
You cannot move a node to a different source file since basically nodes are currently implemented as a fragment (span) of the source file text.

What you do is clone it.

The TypeScript Compiler API way is implementing a Transform. Basically it traverse the AST and you identify which nodes to replace, and return a new node instead the original. The transform generates a new sourceFile that you then can print using ts.createPrinter. These are some working examples (click the run button, and the code at the right will be transformed)

simple transformation:
https://typescript-api-playground.glitch.me/#example=Simple%20Transformation

a couple more:
https://typescript-api-playground.glitch.me/#example=Transformation%202

this other uses ts.createMutableClone() so you just clone a node and edit only what you need:
https://typescript-api-playground.glitch.me/#example=Transformation%203

(It's a playground made by me you can edit and run again)

That being said, I recommend you to checkout this library that probably will let you define the expressions and insert them into almost any place:
https://github.com/dsherret/ts-morph

Also, if you are using ts.create* this project could be a great help to automatically transform code in those expressions:
https://ts-creator.js.org/

Good luck


问:
How can I pass a comma separated array to a resource in terraform v0.12.0?
In the following code block I'm trying to pass an array of server names to the attributes_json block:

```<code>resource "aws_instance" "consul-server" {
    ami = var.consul-server
    instance_type = "t2.nano"
    key_name = var.aws_key_name
    iam_instance_profile = "dna_inst_mgmt"
    vpc_security_group_ids = [
        "${aws_security_group.yutani_consul.id}",
        "${aws_security_group.yutani_ssh.id}"
    ]
        subnet_id = "${aws_subnet.public_1_subnet_us_east_1c.id}"
        associate_public_ip_address = true
      tags = {
        Name = "consul-server${count.index}"
    }

    root_block_device {
        volume_size = "30"
        delete_on_termination = "true"
    }

    connection {
        type = "ssh"
        user = "chef"
        private_key = "${file("${var.aws_key_path}")}"
        timeout = "2m"
        agent = false
        host = self.public_ip
    }

   count = var.consul-server_count

   provisioner "chef" {
         attributes_json = <<-EOF
                {
                    "consul": {
                            "servers": ["${split(",",aws_instance.consul-server[count.index].id)}"]
                      }
                }
                EOF
        use_policyfile = true
        policy_name = "consul_server"
        policy_group = "aws_stage_enc"
        node_name       = "consul-server${count.index}"
        server_url      = var.chef_server_url
        recreate_client = true
        skip_install = true
        user_name       = var.chef_username
        user_key        = "${file("${var.chef_user_key}")}"
       version         = "14"
    }
   }
</code>```

Running this gives me an error:

```<code>Error: Cycle: aws_instance.consul-server[1], aws_instance.consul-server[0]
</code>```

(This is after declaring a count of 2 in a variable for var.consul-server_count)

Can anyone tell me what the proper way is to do this?

答:
There are two issues here: (1) How to interpolate a comma-separated list in a JSON string ; and (2) What is causing the cyclic dependency error.

How to interpolate a list to make a valid JSON array

Use jsonencode

The cleanest method is to not use a heredoc at all and just use the jsonencode  function.

You could do this:

locals {
  arr = ["host1", "host2", "host3"]
}

output "test" {
  value = jsonencode(
    {
      "consul" = {
        "servers" = local.arr
      }
    })
}
```

<p>And this yields as output:</p>

<pre class="lang-none prettyprint-override"><code>Outputs:

test = {"consul":{"servers":["host1","host2","host3"]}}
</code>```

Use the join function and a heredoc

The Chef provisioner's docs suggest to use a heredoc for the JSON string, so you can also do this:

locals {
  arr = ["host1", "host2", "host3"]
  sep = "\", \""
}

output "test" {
  value = <<-EOF
    {
      "consul": {
        "servers": ["${join(local.sep, local.arr)}"]
      }
    }
  EOF
}
```

<p>If I apply that:</p>

<pre class="lang-none prettyprint-override"><code>Outputs:

test = {
  "consul": {
    "servers": ["host1", "host2", "host3"]
  }
}
</code>```

Some things to pay attention to here:

You are trying to join your hosts so that they become valid JSON in the context of a JSON array. You need to join them with ",", not just a comma. That's why I've defined a local variable sep = "\", \"".

You seem to be trying to split there when you apparently need join.

Cyclic dependency issue

The cause of the error message:

Error: Cycle: aws_instance.consul-server[1], aws_instance.consul-server[0]
```

<p>Is that you have a cyclic dependency. Consider this simplified example:</p>

<pre class="lang-tf prettyprint-override"><code>resource "aws_instance" "example" {
  count         = 3
  ami           = "ami-08589eca6dcc9b39c"
  instance_type = "t2.micro"
  user_data     = <<-EOF
    hosts="${join(",", aws_instance.example[count.index].id)}"
  EOF
}
</code>```

Or you could use splat notation there too for the same result i.e. aws_instance.example.*.id.

Terraform plan then yields:

▶ terraform012 plan
...
Error: Cycle: aws_instance.example[2], aws_instance.example[1], aws_instance.example[0]
```

<p>So you get a cycle error there because <code>aws_instance.example.*.id</code> depends on the <code>aws_instance.example</code> being created, so the resource depends on itself. In other words, you can't use a resources exported values inside the resource itself.</p>

<h2>What to do</h2>

<p>I don't know much about Consul, but all the same, I'm a bit confused tbh why you want the EC2 instance IDs in the <code>servers</code> field. Wouldn't the Consul config be expecting IP addresses or hostnames there?</p>

<p>In any case, you probably need to calculate the host names yourself outside of this resource, either as a static input parameter or something that you can calculate somehow. And I imagine you'll end up with something like:</p>

<pre class="lang-tf prettyprint-override"><code>variable "host_names" {
  type    = list
  default = ["myhost1"]
}

resource "aws_instance" "consul_server" {
  ...
  provisioner "chef" {
    attributes_json = jsonencode(
      {
        "consul" = {
          "servers" = var.host_names
        }
      })
  }
}
</code>```

Body:
In the following code block I'm trying to pass an array of server names to the attributes_json block:

resource "aws_instance" "consul-server" {
    ami = var.consul-server
    instance_type = "t2.nano"
    key_name = var.aws_key_name
    iam_instance_profile = "dna_inst_mgmt"
    vpc_security_group_ids = [
        "${aws_security_group.yutani_consul.id}",
        "${aws_security_group.yutani_ssh.id}"
    ]
        subnet_id = "${aws_subnet.public_1_subnet_us_east_1c.id}"
        associate_public_ip_address = true
      tags = {
        Name = "consul-server${count.index}"
    }

    root_block_device {
        volume_size = "30"
        delete_on_termination = "true"
    }

    connection {
        type = "ssh"
        user = "chef"
        private_key = "${file("${var.aws_key_path}")}"
        timeout = "2m"
        agent = false
        host = self.public_ip
    }

   count = var.consul-server_count

   provisioner "chef" {
         attributes_json = <<-EOF
                {
                    "consul": {
                            "servers": ["${split(",",aws_instance.consul-server[count.index].id)}"]
                      }
                }
                EOF
        use_policyfile = true
        policy_name = "consul_server"
        policy_group = "aws_stage_enc"
        node_name       = "consul-server${count.index}"
        server_url      = var.chef_server_url
        recreate_client = true
        skip_install = true
        user_name       = var.chef_username
        user_key        = "${file("${var.chef_user_key}")}"
       version         = "14"
    }
   }

Running this gives me an error:

Error: Cycle: aws_instance.consul-server[1], aws_instance.consul-server[0]

(This is after declaring a count of 2 in a variable for var.consul-server_count)

Can anyone tell me what the proper way is to do this?

Body:
There are two issues here: (1) How to interpolate a comma-separated list in a JSON string ; and (2) What is causing the cyclic dependency error.

How to interpolate a list to make a valid JSON array

Use jsonencode

The cleanest method is to not use a heredoc at all and just use the jsonencode  function.

You could do this:

locals {
  arr = ["host1", "host2", "host3"]
}

output "test" {
  value = jsonencode(
    {
      "consul" = {
        "servers" = local.arr
      }
    })
}

And this yields as output:

Outputs:

test = {"consul":{"servers":["host1","host2","host3"]}}

Use the join function and a heredoc

The Chef provisioner's docs suggest to use a heredoc for the JSON string, so you can also do this:

locals {
  arr = ["host1", "host2", "host3"]
  sep = "\", \""
}

output "test" {
  value = <<-EOF
    {
      "consul": {
        "servers": ["${join(local.sep, local.arr)}"]
      }
    }
  EOF
}

If I apply that:

Outputs:

test = {
  "consul": {
    "servers": ["host1", "host2", "host3"]
  }
}

Some things to pay attention to here:

You are trying to join your hosts so that they become valid JSON in the context of a JSON array. You need to join them with ",", not just a comma. That's why I've defined a local variable sep = "\", \"".

You seem to be trying to split there when you apparently need join.

Cyclic dependency issue

The cause of the error message:

Error: Cycle: aws_instance.consul-server[1], aws_instance.consul-server[0]

Is that you have a cyclic dependency. Consider this simplified example:

resource "aws_instance" "example" {
  count         = 3
  ami           = "ami-08589eca6dcc9b39c"
  instance_type = "t2.micro"
  user_data     = <<-EOF
    hosts="${join(",", aws_instance.example[count.index].id)}"
  EOF
}

Or you could use splat notation there too for the same result i.e. aws_instance.example.*.id.

Terraform plan then yields:

▶ terraform012 plan
...
Error: Cycle: aws_instance.example[2], aws_instance.example[1], aws_instance.example[0]

So you get a cycle error there because aws_instance.example.*.id depends on the aws_instance.example being created, so the resource depends on itself. In other words, you can't use a resources exported values inside the resource itself.

What to do

I don't know much about Consul, but all the same, I'm a bit confused tbh why you want the EC2 instance IDs in the servers field. Wouldn't the Consul config be expecting IP addresses or hostnames there?

In any case, you probably need to calculate the host names yourself outside of this resource, either as a static input parameter or something that you can calculate somehow. And I imagine you'll end up with something like:

variable "host_names" {
  type    = list
  default = ["myhost1"]
}

resource "aws_instance" "consul_server" {
  ...
  provisioner "chef" {
    attributes_json = jsonencode(
      {
        "consul" = {
          "servers" = var.host_names
        }
      })
  }
}


问:
Proper way to wait that fragment is visible
I am using fragments for my turn based game, how can i be sure that a fragment is visible and added to context in this kind of async-function before executing any code in that fragment?

```<code>fun respondToRematchInvitation(invitation : Invitation) {
    if (winFragment.isVisible) {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("Accept invitation for rematch?")
        builder.setMessage("Are you sure?")
        builder.setPositiveButton("Yes") { _, _ ->
            turnBasedMultiplayerClient.acceptInvitation(invitation.invitationId)
                .addOnSuccessListener {
                    Log.d(TAG, "Invitation accepted succesfully")
                    isDoingTurn = false
                    gameFragment = GameFragment()
                    supportFragmentManager.beginTransaction().replace(R.id.fragment_container, gameFragment).addToBackStack(null).commit()
                    onInitiateMatch(it) //error happens here
                }.addOnFailureListener {
                    createFailureListener("Accepting invitation failed")
                }
        }

        val dialog : AlertDialog = builder.create()
        dialog.show()
</code>```

Now in onInitiateMatch(it) i have some code that modifies gameFragment, for example possible receiving opponents game data and other initialization. Simply using if (gameFragment.isVisible) or if (gameFragment.isAdded) is not enough because that way onInitiateMatch(it) function might not be executed if that if-statement returns false.

Should I use threads for this?

答: It turned out, that executing supportFragmentManager.executePendingTransactions() solved the problem, I thought first it was not the a solution for the problem.

Body:
I am using fragments for my turn based game, how can i be sure that a fragment is visible and added to context in this kind of async-function before executing any code in that fragment?

fun respondToRematchInvitation(invitation : Invitation) {
    if (winFragment.isVisible) {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("Accept invitation for rematch?")
        builder.setMessage("Are you sure?")
        builder.setPositiveButton("Yes") { _, _ ->
            turnBasedMultiplayerClient.acceptInvitation(invitation.invitationId)
                .addOnSuccessListener {
                    Log.d(TAG, "Invitation accepted succesfully")
                    isDoingTurn = false
                    gameFragment = GameFragment()
                    supportFragmentManager.beginTransaction().replace(R.id.fragment_container, gameFragment).addToBackStack(null).commit()
                    onInitiateMatch(it) //error happens here
                }.addOnFailureListener {
                    createFailureListener("Accepting invitation failed")
                }
        }

        val dialog : AlertDialog = builder.create()
        dialog.show()

Now in onInitiateMatch(it) i have some code that modifies gameFragment, for example possible receiving opponents game data and other initialization. Simply using if (gameFragment.isVisible) or if (gameFragment.isAdded) is not enough because that way onInitiateMatch(it) function might not be executed if that if-statement returns false.

Should I use threads for this?


问:
React search and filter methods issue
I'm working on a component that should be able to:

Search by input - Using the input field a function will be called after the onBlur event got triggered. After the onBlur event the startSearch() method will run.

Filter by a selected genre - From an other component the user can select a genre from a list  with genres. After the onClick event the startFilter() method will run.

GOOD NEWS:
I got the 2 functions above working.

BAD NEWS:
The above 2 functions don't work correct. Please see the code underneath. The 2 calls underneath work, but only if I comment one of the 2 out.  I tried to tweak the startSearch() method in various ways, but I just keep walking to a big fat wall.

```<code>        //////Searching works
        //////this.filter(this.state.searchInput);

         //Filtering works
         this.startFilter(this.state.searchInput);
</code>```

QUESTION
How can I get the filter/search method working?. Unfortunately simply putting them in an if/else is not the solution (see comments in the code).

import { Component } from 'preact';
import listData from '../../assets/data.json';
import { Link } from 'preact-router/match';
import style from './style';

export default class List extends Component {
 state = {
  selectedStreamUrl: "",
  searchInput: "",
  showDeleteButton: false,
  searchByGenre: false,
  list: [],

 }

 startFilter(input, filterByGenre) {
  this.setState({
   searchByGenre: true,
   searchInput: input,
   showDeleteButton: true
  });
  alert("startFilter  ")
  console.log(this.state.searchByGenre)
  /////////---------------------------------
  document.getElementById("searchField").disabled = false;
  document.getElementById('searchField').value = input
  document.getElementById('searchField').focus()
  // document.getElementById('searchField').blur()
  document.getElementById("searchField").disabled = true;

  console.log(input)
  this.filter(input);

 }

 //search
 startSearch(input) {
  alert("startSearch  ")
  console.log(this.state.searchByGenre)

  //komt uit render()
  if (!this.state.searchByGenre) {
   //check for input

   this.setState({
    searchInput: input.target.value,
    showDeleteButton: true,
   })

   //Searching works
   //this.filter(this.state.searchInput);

   //Filtering works
   this.startFilter(this.state.searchInput);

   // DOESNT WORK:
   // if (this.state.searchInput != "") {
   //  this.filter(this.state.searchInput);
   // } else {
   //  this.startFilter(this.state.searchInput);
   // }
  }

 }

 setAllLists(allLists) {
  console.log("setAllLists")
  console.log(this.state.searchByGenre)
  this.setState({ list: allLists })
  //document.body.style.backgroundColor = "red";
 }

 filter(input) {
  let corresondingGenre = [];
  let filteredLists = listData.filter(

   (item1) => {
    var test;
    if (this.state.searchByGenre) {
     alert("--this.state.searchByGenre")
     //filterByGenre
     //& item1.properties.genre == input

     for (var i = 0; i < item1.properties.genre.length; i++) {
      if (item1.properties.genre[i].includes(input)) {
       corresondingGenre.push(item1);
       test = item1.properties.genre[i].indexOf(input) !== -1;

       return test;
      }
      this.setState({ list: corresondingGenre })
     }

    } else {
     //searchByTitle
     alert("--default")
     test = item1.title.indexOf(input.charAt(0).toUpperCase()) !== -1;
    }
    return test;
   })
  console.log("filterdLists:")
  console.log(filteredLists)
  console.log("corresondingGenre:")
  console.log(corresondingGenre)
  //alert(JSON.stringify(filteredLists))
  this.setState({ list: filteredLists })

 }

 removeInput() {
  console.log("removeInput    ")
  console.log(this.state.searchByGenre)
  this.setState({ searchInput: "", showDeleteButton: false, searchByGenre: false })
  document.getElementById("searchField").disabled = false;
  this.filter(this.state.searchInput)
 }

 render() {
  //alle 's komen in deze array, zodat ze gefilterd kunnen worden OBV title.
  if (this.state.list === undefined || this.state.list.length == 0 && this.state.searchInput == "") {
   //init list
   console.log("render ")
   console.log(this.state.searchByGenre)
   this.filter(this.state.searchInput)
  }

  return (

    <input class={style.searchBar} type="text" id="searchField" placeholder={this.state.searchInput} onBlur={this.startSearch.bind(this)} ></input>

    {
     this.state.searchByGenre ?

ja

      :

nee

    }
    {
     this.state.showDeleteButton ?
      <button class={style.deleteButton} onClick={() => this.removeInput()}>Remove</button>
      : null
    }
    {
     this.state.list.map((item, index) => {
      return

{item.title}

     })
    }

  );
 }
}```

答:
can you modify your search func,</p>

```<code>//search
startSearch(input) {
    const { value } = input.target
    const { searchInput } = this.state

    if (!this.state.searchByGenre) {
        this.setState(prevState => ({
            searchInput: prevState.searchInput = value,
            showDeleteButton: prevState.showDeleteButton = true,
  }))

    JSON.stringify(value) !== '' ? this.filter(value) : this.startFilter(searchInput)
    }
}
</code>```

Title: React search and filter methods issue

Body:
I'm working on a component that should be able to:

Search by input - Using the input field a function will be called after the onBlur event got triggered. After the onBlur event the startSearch() method will run.

Filter by a selected genre - From an other component the user can select a genre from a list  with genres. After the onClick event the startFilter() method will run.

GOOD NEWS:
I got the 2 functions above working.

BAD NEWS:
The above 2 functions don't work correct. Please see the code underneath. The 2 calls underneath work, but only if I comment one of the 2 out.  I tried to tweak the startSearch() method in various ways, but I just keep walking to a big fat wall.

        //////Searching works
        //////this.filter(this.state.searchInput);

         //Filtering works
         this.startFilter(this.state.searchInput);

QUESTION
How can I get the filter/search method working?. Unfortunately simply putting them in an if/else is not the solution (see comments in the code).

import { Component } from 'preact';
import listData from '../../assets/data.json';
import { Link } from 'preact-router/match';
import style from './style';

export default class List extends Component {
 state = {
  selectedStreamUrl: "",
  searchInput: "",
  showDeleteButton: false,
  searchByGenre: false,
  list: [],

 }

 startFilter(input, filterByGenre) {
  this.setState({
   searchByGenre: true,
   searchInput: input,
   showDeleteButton: true
  });
  alert("startFilter  ")
  console.log(this.state.searchByGenre)
  /////////---------------------------------
  document.getElementById("searchField").disabled = false;
  document.getElementById('searchField').value = input
  document.getElementById('searchField').focus()
  // document.getElementById('searchField').blur()
  document.getElementById("searchField").disabled = true;

  console.log(input)
  this.filter(input);

 }

 //search
 startSearch(input) {
  alert("startSearch  ")
  console.log(this.state.searchByGenre)

  //komt uit render()
  if (!this.state.searchByGenre) {
   //check for input

   this.setState({
    searchInput: input.target.value,
    showDeleteButton: true,
   })

   //Searching works
   //this.filter(this.state.searchInput);

   //Filtering works
   this.startFilter(this.state.searchInput);

   // DOESNT WORK:
   // if (this.state.searchInput != "") {
   //  this.filter(this.state.searchInput);
   // } else {
   //  this.startFilter(this.state.searchInput);
   // }
  }

 }

 setAllLists(allLists) {
  console.log("setAllLists")
  console.log(this.state.searchByGenre)
  this.setState({ list: allLists })
  //document.body.style.backgroundColor = "red";
 }

 filter(input) {
  let corresondingGenre = [];
  let filteredLists = listData.filter(

   (item1) => {
    var test;
    if (this.state.searchByGenre) {
     alert("--this.state.searchByGenre")
     //filterByGenre
     //& item1.properties.genre == input

     for (var i = 0; i < item1.properties.genre.length; i++) {
      if (item1.properties.genre[i].includes(input)) {
       corresondingGenre.push(item1);
       test = item1.properties.genre[i].indexOf(input) !== -1;

       return test;
      }
      this.setState({ list: corresondingGenre })
     }

    } else {
     //searchByTitle
     alert("--default")
     test = item1.title.indexOf(input.charAt(0).toUpperCase()) !== -1;
    }
    return test;
   })
  console.log("filterdLists:")
  console.log(filteredLists)
  console.log("corresondingGenre:")
  console.log(corresondingGenre)
  //alert(JSON.stringify(filteredLists))
  this.setState({ list: filteredLists })

 }

 removeInput() {
  console.log("removeInput    ")
  console.log(this.state.searchByGenre)
  this.setState({ searchInput: "", showDeleteButton: false, searchByGenre: false })
  document.getElementById("searchField").disabled = false;
  this.filter(this.state.searchInput)
 }

 render() {
  //alle 's komen in deze array, zodat ze gefilterd kunnen worden OBV title.
  if (this.state.list === undefined || this.state.list.length == 0 && this.state.searchInput == "") {
   //init list
   console.log("render ")
   console.log(this.state.searchByGenre)
   this.filter(this.state.searchInput)
  }

  return (

    <input class={style.searchBar} type="text" id="searchField" placeholder={this.state.searchInput} onBlur={this.startSearch.bind(this)} ></input>

    {
     this.state.searchByGenre ?

ja

      :

nee

    }
    {
     this.state.showDeleteButton ?
      <button class={style.deleteButton} onClick={() => this.removeInput()}>Remove</button>
      : null
    }
    {
     this.state.list.map((item, index) => {
      return

{item.title}

     })
    }

  );
 }
}

Body:
can you modify your search func,

//search
startSearch(input) {
    const { value } = input.target
    const { searchInput } = this.state

    if (!this.state.searchByGenre) {
        this.setState(prevState => ({
            searchInput: prevState.searchInput = value,
            showDeleteButton: prevState.showDeleteButton = true,
  }))

    JSON.stringify(value) !== '' ? this.filter(value) : this.startFilter(searchInput)
    }
}


问:
Conditional (Dynamic) Struct Tags
I'm trying to parse some xml documents in Go. I need to define a few structs for this purpose, and my struct tags depend on a certain condition.

Imagine the following code (even though I know it won't work)

```<code>if someCondition {
    type MyType struct {
        // some common fields
        Date    []string `xml:"value"`
    }
} else {
    type MyType struct {
        // some common fields
        Date    []string `xml:"anotherValue"`
    }
}

var t MyType
// do the unmarshalling ...
</code>```

The problem is that these two structs have lots of fields in common. The only difference is in one of the fields and I want to prevent duplication. How can I solve this problem?

答:
The simplest is probably to handle all possible fields and do some post-processing.

For example:

```<code>type MyType struct {
    DateField1    []string `xml:"value"`
    DateField2    []string `xml:"anotherValue"`
}

// After parsing, you have two options:

// Option 1: re-assign one field onto another:
if !someCondition {
    parsed.DateField1 = parsed.DateField2
    parsed.DateField2 = nil
}

// Option 2: use the above as an intermediate struct, the final being:
type MyFinalType struct {
    Date    []string `xml:"value"`
}

if someCondition {
    final.Date = parsed.DateField1
} else {
    final.Date = parsed.DateField2
}
</code>```

Note: if the messages are sufficiently different, you probably want completely different types for parsing. The post-processing can generate the final struct from either.

Title: Conditional (Dynamic) Struct Tags

Body:
I'm trying to parse some xml documents in Go. I need to define a few structs for this purpose, and my struct tags depend on a certain condition.

Imagine the following code (even though I know it won't work)

if someCondition {
    type MyType struct {
        // some common fields
        Date    []string `xml:"value"`
    }
} else {
    type MyType struct {
        // some common fields
        Date    []string `xml:"anotherValue"`
    }
}

var t MyType
// do the unmarshalling ...

The problem is that these two structs have lots of fields in common. The only difference is in one of the fields and I want to prevent duplication. How can I solve this problem?

Body:
The simplest is probably to handle all possible fields and do some post-processing.

For example:

type MyType struct {
    DateField1    []string `xml:"value"`
    DateField2    []string `xml:"anotherValue"`
}

// After parsing, you have two options:

// Option 1: re-assign one field onto another:
if !someCondition {
    parsed.DateField1 = parsed.DateField2
    parsed.DateField2 = nil
}

// Option 2: use the above as an intermediate struct, the final being:
type MyFinalType struct {
    Date    []string `xml:"value"`
}

if someCondition {
    final.Date = parsed.DateField1
} else {
    final.Date = parsed.DateField2
}

Note: if the messages are sufficiently different, you probably want completely different types for parsing. The post-processing can generate the final struct from either.


问:
Install Google Cloud components error from gcloud command
I am trying to install several GCP components from the gcloud command-line tool and always get the same error:

```<code>$ gcloud components list

Your current Cloud SDK version is: 146.0.0
The latest available version is: 146.0.0

┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                  Components                                                 │
├───────────────┬──────────────────────────────────────────────────────┬──────────────────────────┬───────────┤
│     Status    │                         Name                         │            ID            │    Size   │
├───────────────┼──────────────────────────────────────────────────────┼──────────────────────────┼───────────┤
│ Not Installed │ App Engine Go Extensions                             │ app-engine-go            │  47.9 MiB │
│ Not Installed │ Bigtable Command Line Tool                           │ cbt                      │   3.8 MiB │
│ Not Installed │ Cloud Datalab Command Line Tool                      │ datalab                  │   < 1 MiB │
│ Not Installed │ Cloud Datastore Emulator                             │ cloud-datastore-emulator │  15.4 MiB │
│ Not Installed │ Cloud Datastore Emulator (Legacy)                    │ gcd-emulator             │  38.1 MiB │
│ Not Installed │ Cloud Pub/Sub Emulator                               │ pubsub-emulator          │  21.0 MiB │
│ Not Installed │ Google Container Registry's Docker credential helper │ docker-credential-gcr    │   3.3 MiB │
│ Not Installed │ gcloud app Java Extensions                           │ app-engine-java          │ 128.3 MiB │
│ Not Installed │ gcloud app Python Extensions                         │ app-engine-python        │   7.2 MiB │
│ Not Installed │ kubectl                                              │ kubectl                  │  11.5 MiB │
│ Installed     │ BigQuery Command Line Tool                           │ bq                       │   < 1 MiB │
│ Installed     │ Cloud SDK Core Libraries                             │ core                     │   5.7 MiB │
│ Installed     │ Cloud Storage Command Line Tool                      │ gsutil                   │   2.8 MiB │
│ Installed     │ Default set of gcloud commands                       │ gcloud                   │           │
│ Installed     │ gcloud Alpha Commands                                │ alpha                    │   < 1 MiB │
│ Installed     │ gcloud Beta Commands                                 │ beta                     │   < 1 MiB │
└───────────────┴──────────────────────────────────────────────────────┴──────────────────────────┴───────────┘
</code>```

Then attempting to install kubectl

```<code>$ gcloud components install kubectl

You cannot perform this action because this Cloud SDK installation is
managed by an external package manager.  If you would like to get the
latest version, please see our main download page at:
https://cloud.google.com/sdk/
ERROR: (gcloud.components.install) The component manager is disabled for this installation
</code>```

Any idea why is this error raised?

答:
My Problem

I wanted to upgrade the gcloud CLI version on an existing GCE instance (Ubuntu Xenial), and running gcloud components update resulted in this:

```<code># gcloud components update
ERROR: (gcloud.components.update) You cannot perform this action because this Cloud SDK installation is managed by an external package manager.
Please consider using a separate installation of the Cloud SDK created through the default mechanism described at: https://cloud.google.com/sdk/
</code>```

My Solution

What I found is that the SDK executables are installed in /usr/lib/google-cloud-sdk and are included on the PATH via symlinks in /usr/bin:

```<code># ll /usr/bin | grep google-cloud
lrwxrwxrwx  1 root   root          30 Aug 20  2018 bq -> ../lib/google-cloud-sdk/bin/bq*
lrwxrwxrwx  1 root   root          34 Aug 20  2018 gcloud -> ../lib/google-cloud-sdk/bin/gcloud*
lrwxrwxrwx  1 root   root          52 Aug 20  2018 git-credential-gcloud.sh -> ../lib/google-cloud-sdk/bin/git-credential-gcloud.sh*
lrwxrwxrwx  1 root   root          34 Aug 20  2018 gsutil -> ../lib/google-cloud-sdk/bin/gsutil*
</code>```

Therefore, to install the latest version, I followed steps 3 and 4 from https://cloud.google.com/sdk/docs/quickstart-linux:

Download the archive file best suited to your operating system.

```<code># curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-247.0.0-linux-x86_64.tar.gz
</code>```

Extract the archive to any location on your file system; preferably, your Home folder.

```<code># tar zxvf google-cloud-sdk-247.0.0-linux-x86_64.tar.gz google-cloud-sdk
</code>```

and then just replaced the old /usr/lib/google-cloud-sdk directory with the new one:

```<code># mv /usr/lib/google-cloud-sdk /usr/lib/google-cloud-sdk-ORIG
# mv google-cloud-sdk /usr/lib/
</code>```

This allows the symlinks already on the PATH to continue to work, keeps existing auth/config in place, and appears to support upgrades via gcloud components update in the future:

```<code># gcloud components update

All components are up to date.
</code>```

Useful Troubleshooting Commands

It might be helpful to run these before and after you upgrade gcloud.

Where is gcloud on your PATH:

```<code>$ which gcloud
/usr/bin/gcloud
</code>```

What version of gcloud are you using:

```<code>$ gcloud version
Google Cloud SDK 247.0.0
bq 2.0.43
core 2019.05.17
gsutil 4.38
</code>```

What credentials is gcloud using (by default):

```<code>$ gcloud auth list
</code>```

What config is gcloud using (by default):

```<code>$ gcloud config list
</code>```

Body:
I am trying to install several GCP components from the gcloud command-line tool and always get the same error:

$ gcloud components list

Your current Cloud SDK version is: 146.0.0
The latest available version is: 146.0.0

┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                  Components                                                 │
├───────────────┬──────────────────────────────────────────────────────┬──────────────────────────┬───────────┤
│     Status    │                         Name                         │            ID            │    Size   │
├───────────────┼──────────────────────────────────────────────────────┼──────────────────────────┼───────────┤
│ Not Installed │ App Engine Go Extensions                             │ app-engine-go            │  47.9 MiB │
│ Not Installed │ Bigtable Command Line Tool                           │ cbt                      │   3.8 MiB │
│ Not Installed │ Cloud Datalab Command Line Tool                      │ datalab                  │   < 1 MiB │
│ Not Installed │ Cloud Datastore Emulator                             │ cloud-datastore-emulator │  15.4 MiB │
│ Not Installed │ Cloud Datastore Emulator (Legacy)                    │ gcd-emulator             │  38.1 MiB │
│ Not Installed │ Cloud Pub/Sub Emulator                               │ pubsub-emulator          │  21.0 MiB │
│ Not Installed │ Google Container Registry's Docker credential helper │ docker-credential-gcr    │   3.3 MiB │
│ Not Installed │ gcloud app Java Extensions                           │ app-engine-java          │ 128.3 MiB │
│ Not Installed │ gcloud app Python Extensions                         │ app-engine-python        │   7.2 MiB │
│ Not Installed │ kubectl                                              │ kubectl                  │  11.5 MiB │
│ Installed     │ BigQuery Command Line Tool                           │ bq                       │   < 1 MiB │
│ Installed     │ Cloud SDK Core Libraries                             │ core                     │   5.7 MiB │
│ Installed     │ Cloud Storage Command Line Tool                      │ gsutil                   │   2.8 MiB │
│ Installed     │ Default set of gcloud commands                       │ gcloud                   │           │
│ Installed     │ gcloud Alpha Commands                                │ alpha                    │   < 1 MiB │
│ Installed     │ gcloud Beta Commands                                 │ beta                     │   < 1 MiB │
└───────────────┴──────────────────────────────────────────────────────┴──────────────────────────┴───────────┘

Then attempting to install kubectl

$ gcloud components install kubectl

You cannot perform this action because this Cloud SDK installation is
managed by an external package manager.  If you would like to get the
latest version, please see our main download page at:
https://cloud.google.com/sdk/
ERROR: (gcloud.components.install) The component manager is disabled for this installation

Any idea why is this error raised?

Body:
My Problem

I wanted to upgrade the gcloud CLI version on an existing GCE instance (Ubuntu Xenial), and running gcloud components update resulted in this:

# gcloud components update
ERROR: (gcloud.components.update) You cannot perform this action because this Cloud SDK installation is managed by an external package manager.
Please consider using a separate installation of the Cloud SDK created through the default mechanism described at: https://cloud.google.com/sdk/

My Solution

What I found is that the SDK executables are installed in /usr/lib/google-cloud-sdk and are included on the PATH via symlinks in /usr/bin:

# ll /usr/bin | grep google-cloud
lrwxrwxrwx  1 root   root          30 Aug 20  2018 bq -> ../lib/google-cloud-sdk/bin/bq*
lrwxrwxrwx  1 root   root          34 Aug 20  2018 gcloud -> ../lib/google-cloud-sdk/bin/gcloud*
lrwxrwxrwx  1 root   root          52 Aug 20  2018 git-credential-gcloud.sh -> ../lib/google-cloud-sdk/bin/git-credential-gcloud.sh*
lrwxrwxrwx  1 root   root          34 Aug 20  2018 gsutil -> ../lib/google-cloud-sdk/bin/gsutil*

Therefore, to install the latest version, I followed steps 3 and 4 from https://cloud.google.com/sdk/docs/quickstart-linux:

Download the archive file best suited to your operating system.

# curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-247.0.0-linux-x86_64.tar.gz

Extract the archive to any location on your file system; preferably, your Home folder.

# tar zxvf google-cloud-sdk-247.0.0-linux-x86_64.tar.gz google-cloud-sdk

and then just replaced the old /usr/lib/google-cloud-sdk directory with the new one:

# mv /usr/lib/google-cloud-sdk /usr/lib/google-cloud-sdk-ORIG
# mv google-cloud-sdk /usr/lib/

This allows the symlinks already on the PATH to continue to work, keeps existing auth/config in place, and appears to support upgrades via gcloud components update in the future:

# gcloud components update

All components are up to date.

Useful Troubleshooting Commands

It might be helpful to run these before and after you upgrade gcloud.

Where is gcloud on your PATH:

$ which gcloud
/usr/bin/gcloud

What version of gcloud are you using:

$ gcloud version
Google Cloud SDK 247.0.0
bq 2.0.43
core 2019.05.17
gsutil 4.38

What credentials is gcloud using (by default):

$ gcloud auth list

What config is gcloud using (by default):

$ gcloud config list


问:
Getting a JsonDecodeError on Jupyter Notebook
I'm setting up a Jupyter Notebook that apply a Machine learning model from the Ibm watson studio API to some datas that are coming from my Postgresql database.

While reshaping the data to be readable by the API, a JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) appeared and I can't solve it.

This is the full traceback:

```<code>---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-114-9d8e7cf98a41> in <module>()
      1 import json
      2
----> 3 classes = natural_language_classifier.classify_collection('7818d2s519-nlc-1311', reshaped).get_result()
      4
      5 print(json.dumps(classes, indent=2))

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/natural_language_classifier_v1.py in classify_collection(self, classifier_id, collection, **kwargs)
    152         if collection is None:
    153             raise ValueError('collection must be provided')
--> 154         collection = [self._convert_model(x, ClassifyInput) for x in collection]
    155
    156         headers = {}

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/natural_language_classifier_v1.py in <listcomp>(.0)
    152         if collection is None:
    153             raise ValueError('collection must be provided')
--> 154         collection = [self._convert_model(x, ClassifyInput) for x in collection]
    155
    156         headers = {}

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/watson_service.py in _convert_model(val, classname)
    461         if classname is not None and not hasattr(val, "_from_dict"):
    462             if isinstance(val, str):
--> 463                 val = json_import.loads(val)
    464             val = classname._from_dict(dict(val))
    465         if hasattr(val, "_to_dict"):

/opt/conda/envs/DSX-Python35/lib/python3.5/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    317             parse_int is None and parse_float is None and
    318             parse_constant is None and object_pairs_hook is None and not kw):
--> 319         return _default_decoder.decode(s)
    320     if cls is None:
    321         cls = JSONDecoder

/opt/conda/envs/DSX-Python35/lib/python3.5/json/decoder.py in decode(self, s, _w)
    337
    338         """
--> 339         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    340         end = _w(s, end).end()
    341         if end != len(s):

/opt/conda/envs/DSX-Python35/lib/python3.5/json/decoder.py in raw_decode(self, s, idx)
    353         """
    354         try:
--> 355             obj, end = self.scan_once(s, idx)
    356         except StopIteration as err:
    357             raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</code>```

Here's the code in my Notebook:

```<code>from watson_developer_cloud import NaturalLanguageClassifierV1
import pandas as pd
import psycopg2
import json

# connect to the database
conn_string = 'host={} port={}  dbname={}  user={}  password={}'.format('119.203.10.242', 5432, 'mydb', 'locq', 'Mypass***')
conn_cbedce9523454e8e9fd3fb55d4c1a52e = psycopg2.connect(conn_string)

# select the description column
data_df_1 = pd.read_sql('SELECT description from public."search_product"', con=conn_cbedce9523454e8e9fd3fb55d4c1a52e)

# package phrases into format required by Watson
reshaped = json.dumps({'collection': [{'text' : t} for t in data_df_1['description']]})

# connect to the Watson Studio API
natural_language_classifier = NaturalLanguageClassifierV1(
    iam_apikey='F76ugy8hv1s3sr87buhb7564vb7************'
)

# apply the model to the datas
classes = natural_language_classifier.classify_collection('7818d2s519-nlc-1311', reshaped).get_result()

# print the results
print(classes)
</code>```

When I comment the classes line and I just do print(reshaped), this is the response I'm getting which is the correct format for Watson studio:

```<code>{
  "collection": [
    {
      "text": "Lorem ipsum sjvh  hcx bftiyf,  hufcil, igfgvjuoigv gvj ifcil ,ghn fgbcggtc   yfctgg h vgchbvju."
    },
    {
      "text": "Lorem ajjgvc wiufcfboitf iujcvbnb hjnkjc  ivjhn oikgjvn uhnhgv 09iuvhb  oiuvh boiuhb mkjhv mkiuhygv m,khbgv mkjhgv mkjhgv."
    },
    {
      "text": "Lorem aiv ibveikb jvk igvcib ok blnb v  hb b hb bnjb bhb bhn bn vf vbgfc vbgv nbhgv bb nb nbh nj mjhbv mkjhbv nmjhgbv nmkn"
    },
    {
      "text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"
    },
    {
      "text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"
    },
    {
      "text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"
    },
    {
      "text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"
    }
  ]
}
</code>```

Please help.

EDIT

This is what I just did:

```<code>reshape = json.dumps([{'text' : t} for t in data_df_1['description']])

print(reshape)
</code>```

This is the result I'm getting:

```<code>[{"text": "Lorem ipsum sjvh  hcx bftiyf,  hufcil, igfgvjuoigv gvj ifcil ,ghn fgbcggtc   yfctgg h vgchbvju."}, {"text": "Lorem ajjgvc wiufcfboitf iujcvbnb hjnkjc  ivjhn oikgjvn uhnhgv 09iuvhb  oiuvh boiuhb mkjhv mkiuhygv m,khbgv mkjhgv mkjhgv."}, {"text": "Lorem aiv ibveikb jvk igvcib ok blnb v  hb b hb bnjb bhb bhn bn vf vbgfc vbgv nbhgv bb nb nbh nj mjhbv mkjhbv nmjhgbv nmkn"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "lorem sivbnogc hbiuygv bnjiuygv bmkjygv nmjhgv"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "lore  juhgv bnmkiuhygv nmkiuhb mkjiuhb mkjgv mkjhygv nmkjuytfrdc mjhygtfvc mkijuytfc vbnmkjuhygtfv bnmkjuhygtfvc mjhygv mjhgv nmjhuygv bnjhb mnhgv mjhgv njhgv bnjhb njhygvbnjkiuhbhjihbv mjhgbv nmkjhbhnjb njhgv njmkjhbvbh nhgv mbhhnb hjbhu njbhn njb n  jjijh bb jiji bi jiijib bkiijij b hggg."}, {"text": "Lorem uhygfv bniuhgv nmkjuhgv nmkijuhygv mkihv bjijnb bnjib bjinb bnjub vgvg bhgfc nhgytredxc ngtfv mkjuygfcv bnmjuygv mjhgv bnmkjhgv njhgv njgfvc."}]

</code>```

I copied the results and replace the reshape with these datas:

```<code>#reshape = json.dumps([{'text' : t} for t in data_df_1['description']])

reshape = [{"text": "Lorem ipsum sjvh  hcx bftiyf,  hufcil, igfgvjuoigv gvj ifcil ,ghn fgbcggtc   yfctgg h vgchbvju."}, {"text": "Lorem ajjgvc wiufcfboitf iujcvbnb hjnkjc  ivjhn oikgjvn uhnhgv 09iuvhb  oiuvh boiuhb mkjhv mkiuhygv m,khbgv mkjhgv mkjhgv."}, {"text": "Lorem aiv ibveikb jvk igvcib ok blnb v  hb b hb bnjb bhb bhn bn vf vbgfc vbgv nbhgv bb nb nbh nj mjhbv mkjhbv nmjhgbv nmkn"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "lorem sivbnogc hbiuygv bnjiuygv bmkjygv nmjhgv"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "lore  juhgv bnmkiuhygv nmkiuhb mkjiuhb mkjgv mkjhygv nmkjuytfrdc mjhygtfvc mkijuytfc vbnmkjuhygtfv bnmkjuhygtfvc mjhygv mjhgv nmjhuygv bnjhb mnhgv mjhgv njhgv bnjhb njhygvbnjkiuhbhjihbv mjhgbv nmkjhbhnjb njhgv njmkjhbvbh nhgv mbhhnb hjbhu njbhn njb n  jjijh bb jiji bi jiijib bkiijij b hggg."}, {"text": "Lorem uhygfv bniuhgv nmkjuhgv nmkijuhygv mkihv bjijnb bnjib bjinb bnjub vgvg bhgfc nhgytredxc ngtfv mkjuygfcv bnmjuygv mjhgv bnmkjhgv njhgv njgfvc."}]

classes = natural_language_classifier.classify_collection('7818d2s519-nlc-1311', reshape).get_result()

print(classes)
</code>```

And I got a successful response this way.. but that's not very a good way to do it. Any solution?

答:
The problem was that json.dumps() was returning <class 'str'> (json representation) and the input to the classify_collections() required <class 'list'>. Hence we don't use json.dumps() here and simply replace to double quotes(") for the keys and pass <class 'list'> to the function.

```<code>reshape = [{"text" : t} for t in data_df_1["description"]]
</code>```

Body:
I'm setting up a Jupyter Notebook that apply a Machine learning model from the Ibm watson studio API to some datas that are coming from my Postgresql database.

While reshaping the data to be readable by the API, a JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) appeared and I can't solve it.

This is the full traceback:

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-114-9d8e7cf98a41> in <module>()
      1 import json
      2
----> 3 classes = natural_language_classifier.classify_collection('7818d2s519-nlc-1311', reshaped).get_result()
      4
      5 print(json.dumps(classes, indent=2))

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/natural_language_classifier_v1.py in classify_collection(self, classifier_id, collection, **kwargs)
    152         if collection is None:
    153             raise ValueError('collection must be provided')
--> 154         collection = [self._convert_model(x, ClassifyInput) for x in collection]
    155
    156         headers = {}

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/natural_language_classifier_v1.py in <listcomp>(.0)
    152         if collection is None:
    153             raise ValueError('collection must be provided')
--> 154         collection = [self._convert_model(x, ClassifyInput) for x in collection]
    155
    156         headers = {}

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/watson_service.py in _convert_model(val, classname)
    461         if classname is not None and not hasattr(val, "_from_dict"):
    462             if isinstance(val, str):
--> 463                 val = json_import.loads(val)
    464             val = classname._from_dict(dict(val))
    465         if hasattr(val, "_to_dict"):

/opt/conda/envs/DSX-Python35/lib/python3.5/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    317             parse_int is None and parse_float is None and
    318             parse_constant is None and object_pairs_hook is None and not kw):
--> 319         return _default_decoder.decode(s)
    320     if cls is None:
    321         cls = JSONDecoder

/opt/conda/envs/DSX-Python35/lib/python3.5/json/decoder.py in decode(self, s, _w)
    337
    338         """
--> 339         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    340         end = _w(s, end).end()
    341         if end != len(s):

/opt/conda/envs/DSX-Python35/lib/python3.5/json/decoder.py in raw_decode(self, s, idx)
    353         """
    354         try:
--> 355             obj, end = self.scan_once(s, idx)
    356         except StopIteration as err:
    357             raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Here's the code in my Notebook:

from watson_developer_cloud import NaturalLanguageClassifierV1
import pandas as pd
import psycopg2
import json

# connect to the database
conn_string = 'host={} port={}  dbname={}  user={}  password={}'.format('119.203.10.242', 5432, 'mydb', 'locq', 'Mypass***')
conn_cbedce9523454e8e9fd3fb55d4c1a52e = psycopg2.connect(conn_string)

# select the description column
data_df_1 = pd.read_sql('SELECT description from public."search_product"', con=conn_cbedce9523454e8e9fd3fb55d4c1a52e)

# package phrases into format required by Watson
reshaped = json.dumps({'collection': [{'text' : t} for t in data_df_1['description']]})

# connect to the Watson Studio API
natural_language_classifier = NaturalLanguageClassifierV1(
    iam_apikey='F76ugy8hv1s3sr87buhb7564vb7************'
)

# apply the model to the datas
classes = natural_language_classifier.classify_collection('7818d2s519-nlc-1311', reshaped).get_result()

# print the results
print(classes)

When I comment the classes line and I just do print(reshaped), this is the response I'm getting which is the correct format for Watson studio:

{
  "collection": [
    {
      "text": "Lorem ipsum sjvh  hcx bftiyf,  hufcil, igfgvjuoigv gvj ifcil ,ghn fgbcggtc   yfctgg h vgchbvju."
    },
    {
      "text": "Lorem ajjgvc wiufcfboitf iujcvbnb hjnkjc  ivjhn oikgjvn uhnhgv 09iuvhb  oiuvh boiuhb mkjhv mkiuhygv m,khbgv mkjhgv mkjhgv."
    },
    {
      "text": "Lorem aiv ibveikb jvk igvcib ok blnb v  hb b hb bnjb bhb bhn bn vf vbgfc vbgv nbhgv bb nb nbh nj mjhbv mkjhbv nmjhgbv nmkn"
    },
    {
      "text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"
    },
    {
      "text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"
    },
    {
      "text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"
    },
    {
      "text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"
    }
  ]
}

Please help.

EDIT

This is what I just did:

reshape = json.dumps([{'text' : t} for t in data_df_1['description']])

print(reshape)

This is the result I'm getting:

[{"text": "Lorem ipsum sjvh  hcx bftiyf,  hufcil, igfgvjuoigv gvj ifcil ,ghn fgbcggtc   yfctgg h vgchbvju."}, {"text": "Lorem ajjgvc wiufcfboitf iujcvbnb hjnkjc  ivjhn oikgjvn uhnhgv 09iuvhb  oiuvh boiuhb mkjhv mkiuhygv m,khbgv mkjhgv mkjhgv."}, {"text": "Lorem aiv ibveikb jvk igvcib ok blnb v  hb b hb bnjb bhb bhn bn vf vbgfc vbgv nbhgv bb nb nbh nj mjhbv mkjhbv nmjhgbv nmkn"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "lorem sivbnogc hbiuygv bnjiuygv bmkjygv nmjhgv"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "lore  juhgv bnmkiuhygv nmkiuhb mkjiuhb mkjgv mkjhygv nmkjuytfrdc mjhygtfvc mkijuytfc vbnmkjuhygtfv bnmkjuhygtfvc mjhygv mjhgv nmjhuygv bnjhb mnhgv mjhgv njhgv bnjhb njhygvbnjkiuhbhjihbv mjhgbv nmkjhbhnjb njhgv njmkjhbvbh nhgv mbhhnb hjbhu njbhn njb n  jjijh bb jiji bi jiijib bkiijij b hggg."}, {"text": "Lorem uhygfv bniuhgv nmkjuhgv nmkijuhygv mkihv bjijnb bnjib bjinb bnjub vgvg bhgfc nhgytredxc ngtfv mkjuygfcv bnmjuygv mjhgv bnmkjhgv njhgv njgfvc."}]

I copied the results and replace the reshape with these datas:

#reshape = json.dumps([{'text' : t} for t in data_df_1['description']])

reshape = [{"text": "Lorem ipsum sjvh  hcx bftiyf,  hufcil, igfgvjuoigv gvj ifcil ,ghn fgbcggtc   yfctgg h vgchbvju."}, {"text": "Lorem ajjgvc wiufcfboitf iujcvbnb hjnkjc  ivjhn oikgjvn uhnhgv 09iuvhb  oiuvh boiuhb mkjhv mkiuhygv m,khbgv mkjhgv mkjhgv."}, {"text": "Lorem aiv ibveikb jvk igvcib ok blnb v  hb b hb bnjb bhb bhn bn vf vbgfc vbgv nbhgv bb nb nbh nj mjhbv mkjhbv nmjhgbv nmkn"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "lorem sivbnogc hbiuygv bnjiuygv bmkjygv nmjhgv"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "Lorem jsvc smc cbd ciecdbbc d vd bcvdvbj obcvb vcibs j dvx"}, {"text": "lore  juhgv bnmkiuhygv nmkiuhb mkjiuhb mkjgv mkjhygv nmkjuytfrdc mjhygtfvc mkijuytfc vbnmkjuhygtfv bnmkjuhygtfvc mjhygv mjhgv nmjhuygv bnjhb mnhgv mjhgv njhgv bnjhb njhygvbnjkiuhbhjihbv mjhgbv nmkjhbhnjb njhgv njmkjhbvbh nhgv mbhhnb hjbhu njbhn njb n  jjijh bb jiji bi jiijib bkiijij b hggg."}, {"text": "Lorem uhygfv bniuhgv nmkjuhgv nmkijuhygv mkihv bjijnb bnjib bjinb bnjub vgvg bhgfc nhgytredxc ngtfv mkjuygfcv bnmjuygv mjhgv bnmkjhgv njhgv njgfvc."}]

classes = natural_language_classifier.classify_collection('7818d2s519-nlc-1311', reshape).get_result()

print(classes)

And I got a successful response this way.. but that's not very a good way to do it. Any solution?

Body:
The problem was that json.dumps() was returning <class 'str'> (json representation) and the input to the classify_collections() required <class 'list'>. Hence we don't use json.dumps() here and simply replace to double quotes(") for the keys and pass <class 'list'> to the function.

reshape = [{"text" : t} for t in data_df_1["description"]]


问:
Templates and dependency injection
I have a class template ResourceManager and it is intended to be used something like this:

```<code>ResourceManager<Image>* rm =
    ResourceManager<Image>::Instance();

Image* img = rm->acquire("picture.jpg");
rm->release(img);
</code>```

I'd like to use dependency injection (pass the ResourceManager as a parameter to functions that are supposed to use it instead of having it used globally), however given that it's a template I don't know how to do this. Do you have any suggestions?

My game is only at the beginning of the development and I already have four resource types (Image, Font, Animation and Sound) so making a single ResourceManager (i.e. not a template) with an acquire function for each type of resource is not an option.

Edit: Some clarifications.

What I'm looking for is not how to do dependency injection for one type of ResourceManager, but for all of them at once.

My GameState objects need to load resources when they are initialized/opened; they do so through the ResourceManagers. However, GameStates may need to load any number of types of resources: animations, fonts, images, sounds, etc — that's a lot of function parameters for each kind of ResourceManager! What do you suggest I do?

答:
First. Remember when you use templates, you must resolve everything at compile time.

Then ResourceManager in your code seems a singleton. So there's no difference, rougly speaking, with a global variable.

And I think that is useless pass rm as parameters of your functions when you can call the singleton directly.

And this resolves, I hope, your question.

Title: Templates and dependency injection

Body:
I have a class template ResourceManager and it is intended to be used something like this:

ResourceManager<Image>* rm =
    ResourceManager<Image>::Instance();

Image* img = rm->acquire("picture.jpg");
rm->release(img);

I'd like to use dependency injection (pass the ResourceManager as a parameter to functions that are supposed to use it instead of having it used globally), however given that it's a template I don't know how to do this. Do you have any suggestions?

My game is only at the beginning of the development and I already have four resource types (Image, Font, Animation and Sound) so making a single ResourceManager (i.e. not a template) with an acquire function for each type of resource is not an option.

Edit: Some clarifications.

What I'm looking for is not how to do dependency injection for one type of ResourceManager, but for all of them at once.

My GameState objects need to load resources when they are initialized/opened; they do so through the ResourceManagers. However, GameStates may need to load any number of types of resources: animations, fonts, images, sounds, etc — that's a lot of function parameters for each kind of ResourceManager! What do you suggest I do?


问:
How to add a active class that stays activated
Hey there is a relatively strange problem on one part of my website. I included the part that doesn’t work anymore.  Normally the button should stay at the same size and should have a dark blue color if it is clicked. But right now, it just gets a basic html button. That’s strange because a few days ago the code worked perfectly fine and I changed nothing.

var header = document.getElementById("flex-wrapper-zahlung");
var btns = header.getElementsByClassName("accordion-zahlung");
for (var y = 0; y < btns.length; y++) {
  btns[y].addEventListener("click", function() {
    var current = document.getElementsByClassName("activated");
    if (current.length > 0) {
      current[0].className = current[0].className.replace("activated", "");
    }
    this.className += "activated";
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-wrapper-zahlung {
  margin: 0 0 0 0;
  width: 24em;
}

.accordion-zahlung {
  display: flex;
  background-color: #ededed;
  color: black;
  cursor: pointer;
  padding: .75em;
  width: 30em;
  border: none;
  text-align: left;
  outline: none;
  font-size: 1em;
  font-weight: 500;
  transition: 0.4s;
  margin: .5em 0 0 0;
  border-radius: .5em;
}

.activated,
.accordion-zahlung:hover {
  background-color: #092a5e;
  color: white;
}</code>```

  <button class="accordion-zahlung">     Kreditkarte</button>
  <button class="accordion-zahlung">        Lastschrift</button>
  <button class="accordion-zahlung">       PayPal</button>
  <button class="accordion-zahlung">     Rechnung</button>

```

答: You need to add space to the activated class i.e " activated".

Body:
Hey there is a relatively strange problem on one part of my website. I included the part that doesn’t work anymore.  Normally the button should stay at the same size and should have a dark blue color if it is clicked. But right now, it just gets a basic html button. That’s strange because a few days ago the code worked perfectly fine and I changed nothing.

var header = document.getElementById("flex-wrapper-zahlung");
var btns = header.getElementsByClassName("accordion-zahlung");
for (var y = 0; y < btns.length; y++) {
  btns[y].addEventListener("click", function() {
    var current = document.getElementsByClassName("activated");
    if (current.length > 0) {
      current[0].className = current[0].className.replace("activated", "");
    }
    this.className += "activated";
  });
}

.flex-wrapper-zahlung {
  margin: 0 0 0 0;
  width: 24em;
}

.accordion-zahlung {
  display: flex;
  background-color: #ededed;
  color: black;
  cursor: pointer;
  padding: .75em;
  width: 30em;
  border: none;
  text-align: left;
  outline: none;
  font-size: 1em;
  font-weight: 500;
  transition: 0.4s;
  margin: .5em 0 0 0;
  border-radius: .5em;
}

.activated,
.accordion-zahlung:hover {
  background-color: #092a5e;
  color: white;
}

  <button class="accordion-zahlung">     Kreditkarte</button>
  <button class="accordion-zahlung">        Lastschrift</button>
  <button class="accordion-zahlung">       PayPal</button>
  <button class="accordion-zahlung">     Rechnung</button>