问:
Cloned element change events behaviour
I have a the follow problem:

I have a field that listens to changes that happen in a field, but when that object is cloned, them it overrides one field to another, I mean if in one field I choose 3, it displays 3, but if i choose 4 in the cloned field, them it displaya 4 instead of 7, why?
I know I have made a shallowcopy(plainObject) but at the end it should be as easy as:

parseInt($('.selector')[0].value) + parseInt($('.selector')[1].value)
```

<p>Whereever there are more than 1 element.</p>

<p>I have prepared a <strong><em>fiddle</em></strong>: working fiddle</p>

<p>I have never faced to cloned object, I have read that making <code>clone(true,true)</code> will make a deep-cloning with events and a lot of but there was no lucky, any suggest or idea?? </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).on("click", "#btnNewDistribution", function() {
  var distributionContainers = $("#DistributionContainers");
  var lastDistributionContainer = $(distributionContainers).children().last(".DistributionContainer");
  var newDistributionContainer = $(lastDistributionContainer).clone(true);
  $(newDistributionContainer).find(".ChildAgesContainer").empty();
  distributionContainers.append(newDistributionContainer);
});
$('.AmountField').on('change', function() {
  document.getElementById("habitacionesFiltroTop").innerHTML = this.value;
  calculoAmount();
});
calculoAmount = function() {
  for (var i = $('.well').length - 1; i == 0; i--) {
    if ((i - 1) > 0) {
      habitacionesFiltroTop.html(parseInt($('.form-control.AmountField')[i].value) + parseInt($('.form-control.AmountField')[i - 1].value));
    } else {
      habitacionesFiltroTop.html(parseInt($('.form-control.AmountField')[i].value));
    }
  }
}</code>```

<fieldset id="DistributionContainers">
  <legend>Distribuciones</legend>

        Habitaciones

          <select class="formControl AmountField" type="number" min="1" max="5">

            <option value=1>1</option>
            <option value=2>2</option>
            <option value=3>3</option>
            <option value=4>4</option>
          </select>

        Adultos

          <select class="form-control AdultsField" type="number" defaultValue=2 min="1" max="10">

            <option value=1>1</option>
            <option value=2>2</option>
            <option value=3>3</option>
            <option value=4>4</option>
          </select>

        Niños

          <input class="form-control ChildsField" type="number" defaultValue=0 min="0" max="6">

</fieldset>

     Add new Distri

  Habitaciones:
  <output id="habitacionesFiltroTop">
    </output>

```

Thank you very much!!

答:
The issue is because your logic to sum the values of all the .AmoutField elements is flawed. Firstly habitacionesFiltroTop is an Element object, not a jQuery object, so html() won't work. Secondly you can use each() to loop over all .AmountField elements. Try this:

$(document).on("click", "#btnNewDistribution", function() {
  var $distributionContainers = $("#DistributionContainers");
  var $lastDistributionContainer = $distributionContainers.children().last(".DistributionContainer");
  var $newDistributionContainer = $lastDistributionContainer.clone(true);

  $newDistributionContainer.find(".ChildAgesContainer").empty();
  $distributionContainers.append($newDistributionContainer);
});

$('.AmountField').on('change', function() {
  var totalHabitaciones = 0;
  $('.AmountField').each((i, el) => totalHabitaciones += parseInt(el.value, 10) || 0);
  $('#habitacionesFiltroTop').text(totalHabitaciones);
}).trigger('change');```
<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>
<fieldset id="DistributionContainers">
  <legend>Distribuciones</legend>
  <section class="col col-md-3 DistributionContainer">
    <div class="well">
      <div class="form-group">
        <i class="fa fa-trash-o fa"></i>
      </div>
      <div class="form-group">
        <label class="control-label col-md-6">Habitaciones</label>
        <div class="col-md-6">
          <select class="formControl AmountField" type="number" min="1" max="5"><br><br>
            <option value=1>1</option>
            <option value=2>2</option>
            <option value=3>3</option>
            <option value=4>4</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-md-6">Adultos</label>
        <div class="col-md-6">
          <select class="form-control AdultsField" type="number" defaultValue=2 min="1" max="10"><br><br>
            <option value=1>1</option>
            <option value=2>2</option>
            <option value=3>3</option>
            <option value=4>4</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-md-6">Niños</label>
        <div class="col-md-6">
          <input class="form-control ChildsField" type="number" defaultValue=0 min="0" max="6"><br><br>
        </div>
      </div>
      <div class="form-group ChildAgesContainer">
      </div>
    </div>
  </section>
</fieldset>

<section class="col col-md-1">
  <div class="form-group">
    <i class="fa fa-plus"> Add new Distri</i>

  </div>
</section>

<!--TOTAL HABITACIONES-->
<div class="col-lg-1 col-md-1 col-sm-1">
  Habitaciones:
  <output id="habitacionesFiltroTop">
   </output>
</div></code>```

Title: Cloned element change events behaviour

Body:
I have a the follow problem:

I have a field that listens to changes that happen in a field, but when that object is cloned, them it overrides one field to another, I mean if in one field I choose 3, it displays 3, but if i choose 4 in the cloned field, them it displaya 4 instead of 7, why?
I know I have made a shallowcopy(plainObject) but at the end it should be as easy as:

parseInt($('.selector')[0].value) + parseInt($('.selector')[1].value)

Whereever there are more than 1 element.

I have prepared a fiddle: working fiddle

I have never faced to cloned object, I have read that making clone(true,true) will make a deep-cloning with events and a lot of but there was no lucky, any suggest or idea??

$(document).on("click", "#btnNewDistribution", function() {
  var distributionContainers = $("#DistributionContainers");
  var lastDistributionContainer = $(distributionContainers).children().last(".DistributionContainer");
  var newDistributionContainer = $(lastDistributionContainer).clone(true);
  $(newDistributionContainer).find(".ChildAgesContainer").empty();
  distributionContainers.append(newDistributionContainer);
});
$('.AmountField').on('change', function() {
  document.getElementById("habitacionesFiltroTop").innerHTML = this.value;
  calculoAmount();
});
calculoAmount = function() {
  for (var i = $('.well').length - 1; i == 0; i--) {
    if ((i - 1) > 0) {
      habitacionesFiltroTop.html(parseInt($('.form-control.AmountField')[i].value) + parseInt($('.form-control.AmountField')[i - 1].value));
    } else {
      habitacionesFiltroTop.html(parseInt($('.form-control.AmountField')[i].value));
    }
  }
}

<fieldset id="DistributionContainers">
  <legend>Distribuciones</legend>

        Habitaciones

          <select class="formControl AmountField" type="number" min="1" max="5">

            <option value=1>1</option>
            <option value=2>2</option>
            <option value=3>3</option>
            <option value=4>4</option>
          </select>

        Adultos

          <select class="form-control AdultsField" type="number" defaultValue=2 min="1" max="10">

            <option value=1>1</option>
            <option value=2>2</option>
            <option value=3>3</option>
            <option value=4>4</option>
          </select>

        Niños

          <input class="form-control ChildsField" type="number" defaultValue=0 min="0" max="6">

</fieldset>

     Add new Distri

  Habitaciones:
  <output id="habitacionesFiltroTop">
    </output>

Thank you very much!!

Body:
The issue is because your logic to sum the values of all the .AmoutField elements is flawed. Firstly habitacionesFiltroTop is an Element object, not a jQuery object, so html() won't work. Secondly you can use each() to loop over all .AmountField elements. Try this:

$(document).on("click", "#btnNewDistribution", function() {
  var $distributionContainers = $("#DistributionContainers");
  var $lastDistributionContainer = $distributionContainers.children().last(".DistributionContainer");
  var $newDistributionContainer = $lastDistributionContainer.clone(true);

  $newDistributionContainer.find(".ChildAgesContainer").empty();
  $distributionContainers.append($newDistributionContainer);
});

$('.AmountField').on('change', function() {
  var totalHabitaciones = 0;
  $('.AmountField').each((i, el) => totalHabitaciones += parseInt(el.value, 10) || 0);
  $('#habitacionesFiltroTop').text(totalHabitaciones);
}).trigger('change');

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="DistributionContainers">
  <legend>Distribuciones</legend>
  <section class="col col-md-3 DistributionContainer">
    <div class="well">
      <div class="form-group">
        <a class="btn btn-danger pull-right btnDeleteDistribution" href="#" title="Quitar distribucion"><i class="fa fa-trash-o fa"></i></a>
      </div>
      <div class="form-group">
        <label class="control-label col-md-6">Habitaciones</label>
        <div class="col-md-6">
          <select class="formControl AmountField" type="number" min="1" max="5"><br><br>
            <option value=1>1</option>
            <option value=2>2</option>
            <option value=3>3</option>
            <option value=4>4</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-md-6">Adultos</label>
        <div class="col-md-6">
          <select class="form-control AdultsField" type="number" defaultValue=2 min="1" max="10"><br><br>
            <option value=1>1</option>
            <option value=2>2</option>
            <option value=3>3</option>
            <option value=4>4</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-md-6">Niños</label>
        <div class="col-md-6">
          <input class="form-control ChildsField" type="number" defaultValue=0 min="0" max="6"><br><br>
        </div>
      </div>
      <div class="form-group ChildAgesContainer">
      </div>
    </div>
  </section>
</fieldset>

<section class="col col-md-1">
  <div class="form-group">
    <a class="btn btn-primary" id="btnNewDistribution" href="#" title="Añadir distribución"><i class="fa fa-plus"> Add new Distri</i></a>

  </div>
</section>

<!--TOTAL HABITACIONES-->
<div class="col-lg-1 col-md-1 col-sm-1">
  Habitaciones:
  <output id="habitacionesFiltroTop">
   </output>
</div>


来源: stackexchange

问:
How to uniquely create components in vue js?
I am a newbie to Vue js learning through a video tutorial I created a products page here every product will have product details and review forms so, the problem is when submitting review form for prodcut1 the same review is being stored for prodcut 2 and  3 and being displayed in their reviews also
Once see this link https://codepen.io/lakshmi123__/pen/mdJdrYG
js code:

```// This is one vue component named as product
// Every component will have a template,data and methods
var eventBus = new Vue()
//Component1
Vue.component('product', {
  props:{
    premium:{
      type:Boolean,
      required:true
    }
  },
  template:
  `

     <div class = "row"

{{ title }}

In Stock

Out of Stock

User is premium: {{ premium }}

Shipping : {{shipping}}

Shipping cost includes

    {{ sale }}

Details

{{ detail }}

    <button id="click" v-on:click="addToCart"
    :disabled="!InStock"
    :class="{ disabledButton: !InStock }">Add to Cart</button>
    <button id="click" v-on:click="deleteFromCart"
    :disabled="!InStock"
    :class="{ disabledButton: !InStock }">Delete from Cart</button>

    <product-tabs1 :reviews="reviews"></product-tabs1>

     `,
// In this template at the last we are having another component called product-tabs it is actually the another component but
// is nested in the other component called product we will do like this because we want the product-tabs component to be displayed
// in the product component like that we can implement nesting of components

    data(){
        return {
            id:1,
            brand:'Vue Mastery',
            product: 'Socks',
            shipping:'Shipping:0',
            selectedVariant:0,
            Shipping:true,
            details:['80%cotton','20%polester','Gender-neutral'],
            selectedVariant : 0,
            variants:[
            {
                variantId: 2234,
                variantColor: "gray",
                variantImage:"gray.jpeg",
                variantQuantity: 10,
            },
            {
                variantId: 2235,
                variantColor: "blue",
                variantImage:"blue.jpeg",
                variantQuantity: 0
            }
            ],
            reviews:[],

            OnSale:false,
        }
    },
    methods:{
        addToCart(){
            this.$emit('add-to-cart')//this emit is used for letting the parent know that the button was clicked
            // since here the add-to-cart is the name of the event  associated with the add-to-cart button

        },
        updateProduct:function(variantImage){
            this.image=variantImage;
        },
        deleteFromCart:function(){
            this.$emit('delete-from-cart')
        },
        updateProduct(index){
            this.selectedVariant = index
            console.log(index)
        },
        addReview(productReview){
            this.reviews.push(productReview)

        }
    },
    computed:{
        title(){
            return this.brand + ' ' + this.product
        },
        image(){
            return this.variants[this.selectedVariant].variantImage
        },
        InStock(){
            return this.variants[this.selectedVariant].variantQuantity
        },
        sale(){
            if(this.OnSale){
                return this.brand + ' ' +this.product + ' is on sale!'
            }
            return this.brand + ' ' +this.product + ' is not on sale!'
        },
        shipping(){
            if(this.premium){
                return "Free"
            }
            return 2.99
           }
        },
        mounted() {
        eventBus.$on('review-submitted', productReview => {
          this.reviews.push(productReview)
        })
    }
})

Vue.component('product-tabs1', {
    props: {
      reviews: {
        type: Array,
        required: false
      }
    },
    template: `

          {{ tab }}

There are no reviews yet.

{{ review.name }}

Rating:{{ review.rating }}

{{ review.review }}

          <product-review1></product-review1>

    `,
    data() {
      return {
        tabs: ['Reviews', 'Make a Review'],
        selectedTab: 'Reviews'
      }
    }
  })
Vue.component('product-review1',{
    template:

    `
    <form class ="review-form mt-3" @submit.prevent="onSubmit">

      Please correct the following error(s):

{{ error }}

 Please give your review

    Name:

    <input id="name" v-model="name">

    Review:
    <textarea id="review" v-model="review"></textarea>

    Rating:
    <select id="rating" v-model.number="rating">
    <option>5</option>
    <option>4</option>
    <option>3</option>
    <option>2</option>
    <option>1</option>
    </select>

Would you recommend this product?

   Yes
   <input type="radio" value="Yes" v-model="recommend"/>

   No
   <input type="radio" value="No" v-model="recommend"/>

   <input type="submit" value="submit">

   </form>

    `
    ,
    data(){
        return {
            name:null,
            review:null,
            rating:null,
            recommend:null,
            errors:[]
        }
    },
    methods: {
      onSubmit() {
        this.errors = []
        if (this.name && this.review && this.rating && this.recommend) {
          let productReview = {
            name: this.name,
            review: this.review,
            rating: this.rating,
            recommend: this.recommend
          }
          eventBus.$emit('review-submitted', productReview)
          this.name = null
          this.review = null
          this.rating = null
          this.recommend = null
        }
        else {
          if(!this.name) this.errors.push("Name required.")
          if(!this.review) this.errors.push("Review required.")
          if(!this.rating) this.errors.push("Rating required.")
          if(!this.recommend) this.errors.push("Recommend required")
        }
      }
    }
  })

//component2

Vue.component('product2', {
    props:{
        premium:{
            type:Boolean,
            required:true

        }

    },
    template:
    `

     <div class = "row"

{{ title }}

In Stock

Out of Stock

User is premium: true

Shipping cost includes

Shipping is Free

     {{ sale }}

Details

{{ detail }}

     <button id="click" v-on:click="addToCart"
     :disabled="!InStock"
     :class="{ disabledButton: !InStock }">Add to Cart</button>
     <button id="click" v-on:click="deleteFromCart"
     :disabled="!InStock"
     :class="{ disabledButton: !InStock }">Delete from Cart</button>

     <product-tabs2 :reviews="reviews"></product-tabs2>

     `,

    data(){
        return {
            id:1,
            brand:'Jockey',
            product: 'Socks',
            shipping:'Shipping:0',
            selectedVariant:0,
            Shipping:false,
            details:['Nocotton','Purepolyster','Gender-neutral'],
            selectedVariant : 0,
            variants:[
            {
                variantId: 2234,
                variantColor: "pink",
                variantImage:"pink2.jpg",
                variantQuantity: 10,
            },
            {
                variantId: 2235,
                variantColor: "green",
                variantImage:"green.jpeg",
                variantQuantity: 0
            }
            ],
            reviews:[],
            OnSale:false,
        }
    },
    methods:{
        addToCart(){
            this.$emit('add-to-cart')//this emit is used for letting the parent know that the button was clicked
            // since here the add-to-cart is the name of the event  associated with the add-to-cart button

        },
        updateProduct:function(variantImage){
            this.image=variantImage;
        },
        deleteFromCart:function(){
            this.$emit('delete-from-cart')
        },
        updateProduct(index){
            this.selectedVariant = index
            console.log(index)
        },
        addReview(productReview){
            this.reviews.push(productReview)

        }
    },
    computed:{
        title(){
            return this.brand + ' ' + this.product
        },
        image(){
            return this.variants[this.selectedVariant].variantImage
        },
        InStock(){
            return this.variants[this.selectedVariant].variantQuantity
        },
        sale(){
            if(this.OnSale){
                return this.brand + ' ' +this.product + ' is on sale!'
            }
            return this.brand + ' ' +this.product + ' is not on sale!'
        },
        shipping(){
            if(this.premium){
                return "Free"
            }
            return 2.99
        }
    },
    mounted() {
        eventBus.$on('review-submitted', productReview => {
          this.reviews.push(productReview)
        })
    }
})

Vue.component('product3', {
    props:{
        premium:{
            type:Boolean,
            required:true

        }

    },
    template:
    `

     <div class = "row"

{{ title }}

In Stock

Out of Stock

User is premium: {{ premium }}

Shipping : {{shipping}}

Shipping cost includes

     {{ sale }}

Details

{{ detail }}

     <button id="click" v-on:click="addToCart"
     :disabled="!InStock"
     :class="{ disabledButton: !InStock }">Add to Cart</button>
     <button id="click" v-on:click="deleteFromCart"
     :disabled="!InStock"
     :class="{ disabledButton: !InStock }">Delete from Cart</button>

     <product-tabs3 :reviews="reviews"></product-tabs3>

     `,

    data(){
        return {
            id:1,
            brand:'Paragon',
            product: 'Socks',
            shipping:'Shipping:0',
            selectedVariant:0,
            Shipping:true,
            details:['PureCotton','NoPolyster','Gender-neutral'],
            selectedVariant : 0,
            variants:[
            {
                variantId: 2234,
                variantColor: "red",
                variantImage:"red1.jpeg",
                variantQuantity: 10,
            },
            {
                variantId: 2235,
                variantColor: "black",
                variantImage:"black1.jpeg",
                variantQuantity: 0
            }
            ],
            reviews:[],

            OnSale:false,
        }
    },
    methods:{
        addToCart(){
            this.$emit('add-to-cart')//this emit is used for letting the parent know that the button was clicked
            // since here the add-to-cart is the name of the event  associated with the add-to-cart button

        },
        updateProduct:function(variantImage){
            this.image=variantImage;
        },
        deleteFromCart:function(){
            this.$emit('delete-from-cart')
        },
        updateProduct(index){
            this.selectedVariant = index
            console.log(index)
        },
        addReview(productReview){
            this.reviews.push(productReview)

        }
    },
    computed:{
        title(){
            return this.brand + ' ' + this.product
        },
        image(){
            return this.variants[this.selectedVariant].variantImage
        },
        InStock(){
            return this.variants[this.selectedVariant].variantQuantity
        },
        sale(){
            if(this.OnSale){
                return this.brand + ' ' +this.product + ' is on sale!'
            }
            return this.brand + ' ' +this.product + ' is not on sale!'
        },
        shipping(){
            if(this.premium){
                return "Free"
            }
            return 2.99
        }
    },
    mounted() {
        eventBus.$on('review-submitted', productReview => {
          this.reviews.push(productReview)
        })
    }
})

Vue.component('product-review1',{
    template:

    `
    <form class ="review-form mt-3" @submit.prevent="onSubmit">

      Please correct the following error(s):

{{ error }}

 Please give your review

    Name:

    <input id="name" v-model="name">

    Review:
    <textarea id="review" v-model="review"></textarea>

    Rating:
    <select id="rating" v-model.number="rating">
    <option>5</option>
    <option>4</option>
    <option>3</option>
    <option>2</option>
    <option>1</option>
    </select>

Would you recommend this product?

   Yes
   <input type="radio" value="Yes" v-model="recommend"/>

   No
   <input type="radio" value="No" v-model="recommend"/>

   <input type="submit" value="submit">

   </form>

    `
    ,
    data(){
        return {
            name:null,
            review:null,
            rating:null,
            recommend:null,
            errors:[]
        }
    },
    methods: {
      onSubmit() {
        this.errors = []
        if (this.name && this.review && this.rating && this.recommend) {
          let productReview = {
            name: this.name,
            review: this.review,
            rating: this.rating,
            recommend: this.recommend
          }
          eventBus.$emit('review-submitted', productReview)
          this.name = null
          this.review = null
          this.rating = null
          this.recommend = null
        }
        else {
          if(!this.name) this.errors.push("Name required.")
          if(!this.review) this.errors.push("Review required.")
          if(!this.rating) this.errors.push("Rating required.")
          if(!this.recommend) this.errors.push("Recommend required")
        }
      }
    }
  })

//this is for tabs component to get the tabs at the end for reviews in one and make a review in another tab

//this is for tabs component to get the tabs at the end for reviews in one and make a review in another tab
Vue.component('product-tabs2', {
    props: {
      reviews: {
        type: Array,
        required: false
      }
    },
    template: `

          {{ tab }}

There are no reviews yet.

{{ review.name }}

Rating:{{ review.rating }}

{{ review.review }}

          <product-review2></product-review2>

    `,
    data() {
      return {
        tabs: ['Reviews', 'Make a Review'],
        selectedTab: 'Reviews'
      }
    }
  })
Vue.component('product-review2',{
    template:

    `
    <form class ="review-form mt-3" @submit.prevent="onSubmit">

      Please correct the following error(s):

{{ error }}

 Please give your review

    Name:

    <input id="name" v-model="name">

    Review:
    <textarea id="review" v-model="review"></textarea>

    Rating:
    <select id="rating" v-model.number="rating">
    <option>5</option>
    <option>4</option>
    <option>3</option>
    <option>2</option>
    <option>1</option>
    </select>

Would you recommend this product?

   Yes
   <input type="radio" value="Yes" v-model="recommend"/>

   No
   <input type="radio" value="No" v-model="recommend"/>

   <input type="submit" value="submit">

   </form>

    `
    ,
    data(){
        return {
            name:null,
            review:null,
            rating:null,
            recommend:null,
            errors:[]
        }
    },
    methods: {
      onSubmit() {
        this.errors = []
        if (this.name && this.review && this.rating && this.recommend) {
          let productReview = {
            name: this.name,
            review: this.review,
            rating: this.rating,
            recommend: this.recommend
          }
          eventBus.$emit('review-submitted', productReview)
          this.name = null
          this.review = null
          this.rating = null
          this.recommend = null
        }
        else {
          if(!this.name) this.errors.push("Name required.")
          if(!this.review) this.errors.push("Review required.")
          if(!this.rating) this.errors.push("Rating required.")
          if(!this.recommend) this.errors.push("Recommend required")
        }
      }
    }
  })
Vue.component('product-tabs3', {
    props: {
      reviews: {
        type: Array,
        required: false
      }
    },
    template: `

          {{ tab }}

There are no reviews yet.

{{ review.name }}

Rating:{{ review.rating }}

{{ review.review }}

          <product-review2></product-review2>

    `,
    data() {
      return {
        tabs: ['Reviews', 'Make a Review'],
        selectedTab: 'Reviews'
      }
    }
  })
Vue.component('product-review3',{
    template:

    `
    <form class ="review-form mt-3" @submit.prevent="onSubmit">

      Please correct the following error(s):

{{ error }}

 Please give your review

    Name:

    <input id="name" v-model="name">

    Review:
    <textarea id="review" v-model="review"></textarea>

    Rating:
    <select id="rating" v-model.number="rating">
    <option>5</option>
    <option>4</option>
    <option>3</option>
    <option>2</option>
    <option>1</option>
    </select>

Would you recommend this product?

   Yes
   <input type="radio" value="Yes" v-model="recommend"/>

   No
   <input type="radio" value="No" v-model="recommend"/>

   <input type="submit" value="submit">

   </form>

    `
    ,
    data(){
        return {
            name:null,
            review:null,
            rating:null,
            recommend:null,
            errors:[]
        }
    },
    methods: {
      onSubmit() {
        this.errors = []
        if (this.name && this.review && this.rating && this.recommend) {
          let productReview = {
            name: this.name,
            review: this.review,
            rating: this.rating,
            recommend: this.recommend
          }
          eventBus.$emit('review-submitted', productReview)
          this.name = null
          this.review = null
          this.rating = null
          this.recommend = null
        }
        else {
          if(!this.name) this.errors.push("Name required.")
          if(!this.review) this.errors.push("Review required.")
          if(!this.rating) this.errors.push("Rating required.")
          if(!this.recommend) this.errors.push("Recommend required")
        }
      }
    }
  })

var app = new Vue({
    el:'#app',
    data:{
        premium:false,
        cart:[]
    },
    methods:{
        updateCart(id){
            this.cart.push(id)
        },
        degradeCart(id){
            this.cart.pop(id);
        }
    }

})

/*In this vue methods section we are two types of methods one is normal functions and the other is the computed properties
 In the normal functions I took the addToCart and deleteToCart functions for incrementing and decrementing the items from the cart
 In the computed properties
 1.there is title(), image(), InStock() methods title() methods is for printing the product name with
 the brand that means in the title return statement I had returned the brand and product names together.
 2. there is image() method will display image based on selected Variant in default the selected variant is 0 that is gray here and
 if it is 1 then blue color.
 3. there is InStock() method will display the Instock ad outOfStock messages in the front end based on the quantity taken here
 for gray color socks I had took quantity:10 so instock and for blue color I had took quantity:0 so OutofStock will be displayed
 Here we used props A prop is a custom attribute for passing data into our components
 In order to receive props a component should explicitly call the props
 So for example
  Vue.component('product',{
   props:[message],
   template:`
{{message}}
,
   data(){...}
  })
  In the props we have called the message and in the html template we had rendered`

  */
```

答:
You only have one eventBus, but all your components listen for review-submitted on it. So whenever anything emits a review, all the components add it.

Typically you would have just one component here and use it multiple times, passing different products as a prop, rather than duplicating the entire component. That is likely the best way to fix this. (This example seems to come from the VueMastery series, and they walk you though that.)

But you could also fix this by adding a product identifier to the review, and having each listener check whether it applies to them. (Remember that this is a toy project. In any real project, there would be some central store, such as Vuex, that managed all the reviews for all the products.)

ContentLicense: CC BY-SA 4.0

Body:
I am a newbie to Vue js learning through a video tutorial I created a products page here every product will have product details and review forms so, the problem is when submitting review form for prodcut1 the same review is being stored for prodcut 2 and  3 and being displayed in their reviews also
Once see this link https://codepen.io/lakshmi123__/pen/mdJdrYG
js code:

// This is one vue component named as product
// Every component will have a template,data and methods
var eventBus = new Vue()
//Component1
Vue.component('product', {
  props:{
    premium:{
      type:Boolean,
      required:true
    }
  },
  template:
  `

     <div class = "row"

{{ title }}

In Stock

Out of Stock

User is premium: {{ premium }}

Shipping : {{shipping}}

Shipping cost includes

    {{ sale }}

Details

{{ detail }}

    <button id="click" v-on:click="addToCart"
    :disabled="!InStock"
    :class="{ disabledButton: !InStock }">Add to Cart</button>
    <button id="click" v-on:click="deleteFromCart"
    :disabled="!InStock"
    :class="{ disabledButton: !InStock }">Delete from Cart</button>

    <product-tabs1 :reviews="reviews"></product-tabs1>

     `,
// In this template at the last we are having another component called product-tabs it is actually the another component but
// is nested in the other component called product we will do like this because we want the product-tabs component to be displayed
// in the product component like that we can implement nesting of components

    data(){
        return {
            id:1,
            brand:'Vue Mastery',
            product: 'Socks',
            shipping:'Shipping:0',
            selectedVariant:0,
            Shipping:true,
            details:['80%cotton','20%polester','Gender-neutral'],
            selectedVariant : 0,
            variants:[
            {
                variantId: 2234,
                variantColor: "gray",
                variantImage:"gray.jpeg",
                variantQuantity: 10,
            },
            {
                variantId: 2235,
                variantColor: "blue",
                variantImage:"blue.jpeg",
                variantQuantity: 0
            }
            ],
            reviews:[],

            OnSale:false,
        }
    },
    methods:{
        addToCart(){
            this.$emit('add-to-cart')//this emit is used for letting the parent know that the button was clicked
            // since here the add-to-cart is the name of the event  associated with the add-to-cart button

        },
        updateProduct:function(variantImage){
            this.image=variantImage;
        },
        deleteFromCart:function(){
            this.$emit('delete-from-cart')
        },
        updateProduct(index){
            this.selectedVariant = index
            console.log(index)
        },
        addReview(productReview){
            this.reviews.push(productReview)

        }
    },
    computed:{
        title(){
            return this.brand + ' ' + this.product
        },
        image(){
            return this.variants[this.selectedVariant].variantImage
        },
        InStock(){
            return this.variants[this.selectedVariant].variantQuantity
        },
        sale(){
            if(this.OnSale){
                return this.brand + ' ' +this.product + ' is on sale!'
            }
            return this.brand + ' ' +this.product + ' is not on sale!'
        },
        shipping(){
            if(this.premium){
                return "Free"
            }
            return 2.99
           }
        },
        mounted() {
        eventBus.$on('review-submitted', productReview => {
          this.reviews.push(productReview)
        })
    }
})

Vue.component('product-tabs1', {
    props: {
      reviews: {
        type: Array,
        required: false
      }
    },
    template: `

          {{ tab }}

There are no reviews yet.

{{ review.name }}

Rating:{{ review.rating }}

{{ review.review }}

          <product-review1></product-review1>

    `,
    data() {
      return {
        tabs: ['Reviews', 'Make a Review'],
        selectedTab: 'Reviews'
      }
    }
  })
Vue.component('product-review1',{
    template:

    `
    <form class ="review-form mt-3" @submit.prevent="onSubmit">

      Please correct the following error(s):

{{ error }}

 Please give your review

    Name:

    <input id="name" v-model="name">

    Review:
    <textarea id="review" v-model="review"></textarea>

    Rating:
    <select id="rating" v-model.number="rating">
    <option>5</option>
    <option>4</option>
    <option>3</option>
    <option>2</option>
    <option>1</option>
    </select>

Would you recommend this product?

   Yes
   <input type="radio" value="Yes" v-model="recommend"/>

   No
   <input type="radio" value="No" v-model="recommend"/>

   <input type="submit" value="submit">

   </form>

    `
    ,
    data(){
        return {
            name:null,
            review:null,
            rating:null,
            recommend:null,
            errors:[]
        }
    },
    methods: {
      onSubmit() {
        this.errors = []
        if (this.name && this.review && this.rating && this.recommend) {
          let productReview = {
            name: this.name,
            review: this.review,
            rating: this.rating,
            recommend: this.recommend
          }
          eventBus.$emit('review-submitted', productReview)
          this.name = null
          this.review = null
          this.rating = null
          this.recommend = null
        }
        else {
          if(!this.name) this.errors.push("Name required.")
          if(!this.review) this.errors.push("Review required.")
          if(!this.rating) this.errors.push("Rating required.")
          if(!this.recommend) this.errors.push("Recommend required")
        }
      }
    }
  })

//component2

Vue.component('product2', {
    props:{
        premium:{
            type:Boolean,
            required:true

        }

    },
    template:
    `

     <div class = "row"

{{ title }}

In Stock

Out of Stock

User is premium: true

Shipping cost includes

Shipping is Free

     {{ sale }}

Details

{{ detail }}

     <button id="click" v-on:click="addToCart"
     :disabled="!InStock"
     :class="{ disabledButton: !InStock }">Add to Cart</button>
     <button id="click" v-on:click="deleteFromCart"
     :disabled="!InStock"
     :class="{ disabledButton: !InStock }">Delete from Cart</button>

     <product-tabs2 :reviews="reviews"></product-tabs2>

     `,

    data(){
        return {
            id:1,
            brand:'Jockey',
            product: 'Socks',
            shipping:'Shipping:0',
            selectedVariant:0,
            Shipping:false,
            details:['Nocotton','Purepolyster','Gender-neutral'],
            selectedVariant : 0,
            variants:[
            {
                variantId: 2234,
                variantColor: "pink",
                variantImage:"pink2.jpg",
                variantQuantity: 10,
            },
            {
                variantId: 2235,
                variantColor: "green",
                variantImage:"green.jpeg",
                variantQuantity: 0
            }
            ],
            reviews:[],
            OnSale:false,
        }
    },
    methods:{
        addToCart(){
            this.$emit('add-to-cart')//this emit is used for letting the parent know that the button was clicked
            // since here the add-to-cart is the name of the event  associated with the add-to-cart button

        },
        updateProduct:function(variantImage){
            this.image=variantImage;
        },
        deleteFromCart:function(){
            this.$emit('delete-from-cart')
        },
        updateProduct(index){
            this.selectedVariant = index
            console.log(index)
        },
        addReview(productReview){
            this.reviews.push(productReview)

        }
    },
    computed:{
        title(){
            return this.brand + ' ' + this.product
        },
        image(){
            return this.variants[this.selectedVariant].variantImage
        },
        InStock(){
            return this.variants[this.selectedVariant].variantQuantity
        },
        sale(){
            if(this.OnSale){
                return this.brand + ' ' +this.product + ' is on sale!'
            }
            return this.brand + ' ' +this.product + ' is not on sale!'
        },
        shipping(){
            if(this.premium){
                return "Free"
            }
            return 2.99
        }
    },
    mounted() {
        eventBus.$on('review-submitted', productReview => {
          this.reviews.push(productReview)
        })
    }
})

Vue.component('product3', {
    props:{
        premium:{
            type:Boolean,
            required:true

        }

    },
    template:
    `

     <div class = "row"

{{ title }}

In Stock

Out of Stock

User is premium: {{ premium }}

Shipping : {{shipping}}

Shipping cost includes

     {{ sale }}

Details

{{ detail }}

     <button id="click" v-on:click="addToCart"
     :disabled="!InStock"
     :class="{ disabledButton: !InStock }">Add to Cart</button>
     <button id="click" v-on:click="deleteFromCart"
     :disabled="!InStock"
     :class="{ disabledButton: !InStock }">Delete from Cart</button>

     <product-tabs3 :reviews="reviews"></product-tabs3>

     `,

    data(){
        return {
            id:1,
            brand:'Paragon',
            product: 'Socks',
            shipping:'Shipping:0',
            selectedVariant:0,
            Shipping:true,
            details:['PureCotton','NoPolyster','Gender-neutral'],
            selectedVariant : 0,
            variants:[
            {
                variantId: 2234,
                variantColor: "red",
                variantImage:"red1.jpeg",
                variantQuantity: 10,
            },
            {
                variantId: 2235,
                variantColor: "black",
                variantImage:"black1.jpeg",
                variantQuantity: 0
            }
            ],
            reviews:[],

            OnSale:false,
        }
    },
    methods:{
        addToCart(){
            this.$emit('add-to-cart')//this emit is used for letting the parent know that the button was clicked
            // since here the add-to-cart is the name of the event  associated with the add-to-cart button

        },
        updateProduct:function(variantImage){
            this.image=variantImage;
        },
        deleteFromCart:function(){
            this.$emit('delete-from-cart')
        },
        updateProduct(index){
            this.selectedVariant = index
            console.log(index)
        },
        addReview(productReview){
            this.reviews.push(productReview)

        }
    },
    computed:{
        title(){
            return this.brand + ' ' + this.product
        },
        image(){
            return this.variants[this.selectedVariant].variantImage
        },
        InStock(){
            return this.variants[this.selectedVariant].variantQuantity
        },
        sale(){
            if(this.OnSale){
                return this.brand + ' ' +this.product + ' is on sale!'
            }
            return this.brand + ' ' +this.product + ' is not on sale!'
        },
        shipping(){
            if(this.premium){
                return "Free"
            }
            return 2.99
        }
    },
    mounted() {
        eventBus.$on('review-submitted', productReview => {
          this.reviews.push(productReview)
        })
    }
})

Vue.component('product-review1',{
    template:

    `
    <form class ="review-form mt-3" @submit.prevent="onSubmit">

      Please correct the following error(s):

{{ error }}

 Please give your review

    Name:

    <input id="name" v-model="name">

    Review:
    <textarea id="review" v-model="review"></textarea>

    Rating:
    <select id="rating" v-model.number="rating">
    <option>5</option>
    <option>4</option>
    <option>3</option>
    <option>2</option>
    <option>1</option>
    </select>

Would you recommend this product?

   Yes
   <input type="radio" value="Yes" v-model="recommend"/>

   No
   <input type="radio" value="No" v-model="recommend"/>

   <input type="submit" value="submit">

   </form>

    `
    ,
    data(){
        return {
            name:null,
            review:null,
            rating:null,
            recommend:null,
            errors:[]
        }
    },
    methods: {
      onSubmit() {
        this.errors = []
        if (this.name && this.review && this.rating && this.recommend) {
          let productReview = {
            name: this.name,
            review: this.review,
            rating: this.rating,
            recommend: this.recommend
          }
          eventBus.$emit('review-submitted', productReview)
          this.name = null
          this.review = null
          this.rating = null
          this.recommend = null
        }
        else {
          if(!this.name) this.errors.push("Name required.")
          if(!this.review) this.errors.push("Review required.")
          if(!this.rating) this.errors.push("Rating required.")
          if(!this.recommend) this.errors.push("Recommend required")
        }
      }
    }
  })

//this is for tabs component to get the tabs at the end for reviews in one and make a review in another tab

//this is for tabs component to get the tabs at the end for reviews in one and make a review in another tab
Vue.component('product-tabs2', {
    props: {
      reviews: {
        type: Array,
        required: false
      }
    },
    template: `

          {{ tab }}

There are no reviews yet.

{{ review.name }}

Rating:{{ review.rating }}

{{ review.review }}

          <product-review2></product-review2>

    `,
    data() {
      return {
        tabs: ['Reviews', 'Make a Review'],
        selectedTab: 'Reviews'
      }
    }
  })
Vue.component('product-review2',{
    template:

    `
    <form class ="review-form mt-3" @submit.prevent="onSubmit">

      Please correct the following error(s):

{{ error }}

 Please give your review

    Name:

    <input id="name" v-model="name">

    Review:
    <textarea id="review" v-model="review"></textarea>

    Rating:
    <select id="rating" v-model.number="rating">
    <option>5</option>
    <option>4</option>
    <option>3</option>
    <option>2</option>
    <option>1</option>
    </select>

Would you recommend this product?

   Yes
   <input type="radio" value="Yes" v-model="recommend"/>

   No
   <input type="radio" value="No" v-model="recommend"/>

   <input type="submit" value="submit">

   </form>

    `
    ,
    data(){
        return {
            name:null,
            review:null,
            rating:null,
            recommend:null,
            errors:[]
        }
    },
    methods: {
      onSubmit() {
        this.errors = []
        if (this.name && this.review && this.rating && this.recommend) {
          let productReview = {
            name: this.name,
            review: this.review,
            rating: this.rating,
            recommend: this.recommend
          }
          eventBus.$emit('review-submitted', productReview)
          this.name = null
          this.review = null
          this.rating = null
          this.recommend = null
        }
        else {
          if(!this.name) this.errors.push("Name required.")
          if(!this.review) this.errors.push("Review required.")
          if(!this.rating) this.errors.push("Rating required.")
          if(!this.recommend) this.errors.push("Recommend required")
        }
      }
    }
  })
Vue.component('product-tabs3', {
    props: {
      reviews: {
        type: Array,
        required: false
      }
    },
    template: `

          {{ tab }}

There are no reviews yet.

{{ review.name }}

Rating:{{ review.rating }}

{{ review.review }}

          <product-review2></product-review2>

    `,
    data() {
      return {
        tabs: ['Reviews', 'Make a Review'],
        selectedTab: 'Reviews'
      }
    }
  })
Vue.component('product-review3',{
    template:

    `
    <form class ="review-form mt-3" @submit.prevent="onSubmit">

      Please correct the following error(s):

{{ error }}

 Please give your review

    Name:

    <input id="name" v-model="name">

    Review:
    <textarea id="review" v-model="review"></textarea>

    Rating:
    <select id="rating" v-model.number="rating">
    <option>5</option>
    <option>4</option>
    <option>3</option>
    <option>2</option>
    <option>1</option>
    </select>

Would you recommend this product?

   Yes
   <input type="radio" value="Yes" v-model="recommend"/>

   No
   <input type="radio" value="No" v-model="recommend"/>

   <input type="submit" value="submit">

   </form>

    `
    ,
    data(){
        return {
            name:null,
            review:null,
            rating:null,
            recommend:null,
            errors:[]
        }
    },
    methods: {
      onSubmit() {
        this.errors = []
        if (this.name && this.review && this.rating && this.recommend) {
          let productReview = {
            name: this.name,
            review: this.review,
            rating: this.rating,
            recommend: this.recommend
          }
          eventBus.$emit('review-submitted', productReview)
          this.name = null
          this.review = null
          this.rating = null
          this.recommend = null
        }
        else {
          if(!this.name) this.errors.push("Name required.")
          if(!this.review) this.errors.push("Review required.")
          if(!this.rating) this.errors.push("Rating required.")
          if(!this.recommend) this.errors.push("Recommend required")
        }
      }
    }
  })

var app = new Vue({
    el:'#app',
    data:{
        premium:false,
        cart:[]
    },
    methods:{
        updateCart(id){
            this.cart.push(id)
        },
        degradeCart(id){
            this.cart.pop(id);
        }
    }

})

/*In this vue methods section we are two types of methods one is normal functions and the other is the computed properties
 In the normal functions I took the addToCart and deleteToCart functions for incrementing and decrementing the items from the cart
 In the computed properties
 1.there is title(), image(), InStock() methods title() methods is for printing the product name with
 the brand that means in the title return statement I had returned the brand and product names together.
 2. there is image() method will display image based on selected Variant in default the selected variant is 0 that is gray here and
 if it is 1 then blue color.
 3. there is InStock() method will display the Instock ad outOfStock messages in the front end based on the quantity taken here
 for gray color socks I had took quantity:10 so instock and for blue color I had took quantity:0 so OutofStock will be displayed
 Here we used props A prop is a custom attribute for passing data into our components
 In order to receive props a component should explicitly call the props
 So for example
  Vue.component('product',{
   props:[message],
   template:`
{{message}}
,
   data(){...}
  })
  In the props we have called the message and in the html template we had rendered`

  */


问:
How to detect and use the row number of a table in postgreSQL, using Python?
I'm trying to find a way to use the row number of a table in postgreSQL, using Python.
So in a for loop, when the table row number is 22, do something.

Let me show you an easy example:

```<code>conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)
cur = conn.cursor()

cur.execute("SELECT a, b FROM table")
rows = cur.fetchall()

for data in rows:
    if data.row_number == 22:`    #if the table row number is 22...
        do something
</code>```

obviously the expression "data.row_number" does not exist and produces an error...

Somebody could help me?

Thanks

答: You can try ROW_NUMBER() method from documentation</p>

Body:
I'm trying to find a way to use the row number of a table in postgreSQL, using Python.
So in a for loop, when the table row number is 22, do something.

Let me show you an easy example:

conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)
cur = conn.cursor()

cur.execute("SELECT a, b FROM table")
rows = cur.fetchall()

for data in rows:
    if data.row_number == 22:`    #if the table row number is 22...
        do something

obviously the expression "data.row_number" does not exist and produces an error...

Somebody could help me?

Thanks


问:
R - return multiple objects to a different (parent) environment
I am writing a function where I will return several object.
The usual way is to store them as a list and return the list.
However, that means I will have to unlist the list to access those objects.

Is there a way to instead store them in a different environment outside the function itself?

I am thinking I will use this function directly inside my code or inside other function.
The idea would be to push those object to the direct parent environment, so a function if I execute this function inside another function, or the global environment if I executed the function inline in my code.

Best,

Edit:
Hi, I added a dummy list. It is actually data that I am using. The first element contains the dataset after modification by a function and a vector containing names of column that were added, that I use further in my code.
Why I asked the question in the first place is that I want to extract the dataset and vector, and that they replace the original dataset or vector if they already exist, or create them if they don't.

I will most likely call this inside a function that will use them further. I would normally do this with a loop but I'd rather a function to do this that I can call anytime.

How would you do this?
I tried with unlist but never achieved what I am after.

```<code>list(dummy2 = structure(list(interaction = c("Rutilus rutilus<-Hydrachnidia",
"Rutilus rutilus<-Hydrachnidia", "Rutilus rutilus<-Hydrachnidia",
"Rutilus rutilus<-Hydrachnidia", "Rutilus rutilus<-Hydrachnidia",
"Rutilus rutilus<-Hydrachnidia"), PREDATOR = c("Rutilus rutilus",
"Rutilus rutilus", "Rutilus rutilus", "Rutilus rutilus", "Rutilus rutilus",
"Rutilus rutilus"), PREY = c("Hydrachnidia", "Hydrachnidia",
"Hydrachnidia", "Hydrachnidia", "Hydrachnidia", "Hydrachnidia"
), interaction_type = c("eats", "eats", "preysOn", "preysOn",
"preysOn", "eats"), source = c("Globi", "Globi", "Globi", "Globi",
"Globi", "Globi"), pred_prey_lifestage = c("NA<-NA", "larvae<-larvae",
"larvae<-larvae", "larvae<-NA", "NA<-NA", "NA<-NA"), interaction_lifestage = c("NA<-NA",
"larvae<-larvae", "larvae<-larvae", "larvae<-NA", "NA<-NA", "NA<-NA"
), pred_lifestage = c(NA, "larvae", "larvae", "larvae", NA, NA
), prey_lifestage = c(NA, "larvae", "larvae", NA, NA, NA), lat = c(NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_
), lon = c(NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_), ref = c("Rowan Dunn, D. (1954). The Feeding Habits of some of the Fishes and some Members of the Bottom Fauna of Llyn Tegid (Bala Lake), Merionethshire. Journal of Animal Ecology, 23(2), 224�233.",
"Northcott, D. S., The role of aquatic macrophytes in the availabillty of food for young fish, 1981, PhD thesis, City of London Polytechnic, UK",
"Northcott, D. S., The role of aquatic macrophytes in the availabillty of food for young fish, 1981, PhD thesis, City of London Polytechnic, UK",
"Northcott, D. S., The role of aquatic macrophytes in the availabillty of food for young fish, 1981, PhD thesis, City of London Polytechnic, UK",
"Northcott, D. S., The role of aquatic macrophytes in the availabillty of food for young fish, 1981, PhD thesis, City of London Polytechnic, UK",
"Northcott, D. S., The role of aquatic macrophytes in the availabillty of food for young fish, 1981, PhD thesis, City of London Polytechnic, UK"
), data_provider = c("Gray C, Ma A, Perkins D, Hudson L, Figueroa D, Woodward G (2015). Database of trophic interactions. Zenodo. https://doi.org/10.5281/zenodo.13751. Accessed at <https://github.com/globalbioticinteractions/gray2015/archive/95bfd96cc46e5d58482fd2bdad0677eeb74ba0f4.zip> on 16 Feb 2020.",
"Gray C, Ma A, Perkins D, Hudson L, Figueroa D, Woodward G (2015). Database of trophic interactions. Zenodo. https://doi.org/10.5281/zenodo.13751. Accessed at <https://github.com/globalbioticinteractions/gray2015/archive/95bfd96cc46e5d58482fd2bdad0677eeb74ba0f4.zip> on 16 Feb 2020.",
"Gray C, Ma A, Perkins D, Hudson L, Figueroa D, Woodward G (2015). Database of trophic interactions. Zenodo. https://doi.org/10.5281/zenodo.13751. Accessed at <https://github.com/globalbioticinteractions/gray2015/archive/95bfd96cc46e5d58482fd2bdad0677eeb74ba0f4.zip> on 16 Feb 2020.",
"Gray C, Ma A, Perkins D, Hudson L, Figueroa D, Woodward G (2015). Database of trophic interactions. Zenodo. https://doi.org/10.5281/zenodo.13751. Accessed at <https://github.com/globalbioticinteractions/gray2015/archive/95bfd96cc46e5d58482fd2bdad0677eeb74ba0f4.zip> on 16 Feb 2020.",
"Gray, C., Ma, A., Perkins, D., Hudson, L., Figueroa, D., & Woodward, G. (2015). Database of trophic interactions [Data set]. Zenodo. http://doi.org/10.5281/zenodo.13751. Accessed at <https://zenodo.org/record/13751/files/trophic.links.2014-11-10.csv> on 16 Feb 2020.",
"Gray, C., Ma, A., Perkins, D., Hudson, L., Figueroa, D., & Woodward, G. (2015). Database of trophic interactions [Data set]. Zenodo. http://doi.org/10.5281/zenodo.13751. Accessed at <https://zenodo.org/record/13751/files/trophic.links.2014-11-10.csv> on 16 Feb 2020."
)), row.names = c(351L, 361L, 362L, 366L, 376L, 377L), class = "data.frame"),
    dummy2.addi = c("interaction", "interaction_lifestage"))
</code>```

答:
Yes, there is a possibility to do that:

```<code>assign(x, value, pos = -1, envir = as.environment(pos),
       inherits = FALSE, immediate = TRUE)
</code>```

Another possibility is

```<code>foo <- function(){
    someVariableInParentEnvironment <<- 5
}
</code>```

assign() has the possibility to write to any environment you want.

However

You should really think before you do that. I would recommend not doing this unless in small functions in small scripts that only you use. The problem is that you lose sight of where which variable exists.

Body:
I am writing a function where I will return several object.
The usual way is to store them as a list and return the list.
However, that means I will have to unlist the list to access those objects.

Is there a way to instead store them in a different environment outside the function itself?

I am thinking I will use this function directly inside my code or inside other function.
The idea would be to push those object to the direct parent environment, so a function if I execute this function inside another function, or the global environment if I executed the function inline in my code.

Best,

Edit:
Hi, I added a dummy list. It is actually data that I am using. The first element contains the dataset after modification by a function and a vector containing names of column that were added, that I use further in my code.
Why I asked the question in the first place is that I want to extract the dataset and vector, and that they replace the original dataset or vector if they already exist, or create them if they don't.

I will most likely call this inside a function that will use them further. I would normally do this with a loop but I'd rather a function to do this that I can call anytime.

How would you do this?
I tried with unlist but never achieved what I am after.

list(dummy2 = structure(list(interaction = c("Rutilus rutilus<-Hydrachnidia",
"Rutilus rutilus<-Hydrachnidia", "Rutilus rutilus<-Hydrachnidia",
"Rutilus rutilus<-Hydrachnidia", "Rutilus rutilus<-Hydrachnidia",
"Rutilus rutilus<-Hydrachnidia"), PREDATOR = c("Rutilus rutilus",
"Rutilus rutilus", "Rutilus rutilus", "Rutilus rutilus", "Rutilus rutilus",
"Rutilus rutilus"), PREY = c("Hydrachnidia", "Hydrachnidia",
"Hydrachnidia", "Hydrachnidia", "Hydrachnidia", "Hydrachnidia"
), interaction_type = c("eats", "eats", "preysOn", "preysOn",
"preysOn", "eats"), source = c("Globi", "Globi", "Globi", "Globi",
"Globi", "Globi"), pred_prey_lifestage = c("NA<-NA", "larvae<-larvae",
"larvae<-larvae", "larvae<-NA", "NA<-NA", "NA<-NA"), interaction_lifestage = c("NA<-NA",
"larvae<-larvae", "larvae<-larvae", "larvae<-NA", "NA<-NA", "NA<-NA"
), pred_lifestage = c(NA, "larvae", "larvae", "larvae", NA, NA
), prey_lifestage = c(NA, "larvae", "larvae", NA, NA, NA), lat = c(NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_
), lon = c(NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_), ref = c("Rowan Dunn, D. (1954). The Feeding Habits of some of the Fishes and some Members of the Bottom Fauna of Llyn Tegid (Bala Lake), Merionethshire. Journal of Animal Ecology, 23(2), 224�233.",
"Northcott, D. S., The role of aquatic macrophytes in the availabillty of food for young fish, 1981, PhD thesis, City of London Polytechnic, UK",
"Northcott, D. S., The role of aquatic macrophytes in the availabillty of food for young fish, 1981, PhD thesis, City of London Polytechnic, UK",
"Northcott, D. S., The role of aquatic macrophytes in the availabillty of food for young fish, 1981, PhD thesis, City of London Polytechnic, UK",
"Northcott, D. S., The role of aquatic macrophytes in the availabillty of food for young fish, 1981, PhD thesis, City of London Polytechnic, UK",
"Northcott, D. S., The role of aquatic macrophytes in the availabillty of food for young fish, 1981, PhD thesis, City of London Polytechnic, UK"
), data_provider = c("Gray C, Ma A, Perkins D, Hudson L, Figueroa D, Woodward G (2015). Database of trophic interactions. Zenodo. https://doi.org/10.5281/zenodo.13751. Accessed at <https://github.com/globalbioticinteractions/gray2015/archive/95bfd96cc46e5d58482fd2bdad0677eeb74ba0f4.zip> on 16 Feb 2020.",
"Gray C, Ma A, Perkins D, Hudson L, Figueroa D, Woodward G (2015). Database of trophic interactions. Zenodo. https://doi.org/10.5281/zenodo.13751. Accessed at <https://github.com/globalbioticinteractions/gray2015/archive/95bfd96cc46e5d58482fd2bdad0677eeb74ba0f4.zip> on 16 Feb 2020.",
"Gray C, Ma A, Perkins D, Hudson L, Figueroa D, Woodward G (2015). Database of trophic interactions. Zenodo. https://doi.org/10.5281/zenodo.13751. Accessed at <https://github.com/globalbioticinteractions/gray2015/archive/95bfd96cc46e5d58482fd2bdad0677eeb74ba0f4.zip> on 16 Feb 2020.",
"Gray C, Ma A, Perkins D, Hudson L, Figueroa D, Woodward G (2015). Database of trophic interactions. Zenodo. https://doi.org/10.5281/zenodo.13751. Accessed at <https://github.com/globalbioticinteractions/gray2015/archive/95bfd96cc46e5d58482fd2bdad0677eeb74ba0f4.zip> on 16 Feb 2020.",
"Gray, C., Ma, A., Perkins, D., Hudson, L., Figueroa, D., & Woodward, G. (2015). Database of trophic interactions [Data set]. Zenodo. http://doi.org/10.5281/zenodo.13751. Accessed at <https://zenodo.org/record/13751/files/trophic.links.2014-11-10.csv> on 16 Feb 2020.",
"Gray, C., Ma, A., Perkins, D., Hudson, L., Figueroa, D., & Woodward, G. (2015). Database of trophic interactions [Data set]. Zenodo. http://doi.org/10.5281/zenodo.13751. Accessed at <https://zenodo.org/record/13751/files/trophic.links.2014-11-10.csv> on 16 Feb 2020."
)), row.names = c(351L, 361L, 362L, 366L, 376L, 377L), class = "data.frame"),
    dummy2.addi = c("interaction", "interaction_lifestage"))

Body:
Yes, there is a possibility to do that:

assign(x, value, pos = -1, envir = as.environment(pos),
       inherits = FALSE, immediate = TRUE)

Another possibility is

foo <- function(){
    someVariableInParentEnvironment <<- 5
}

assign() has the possibility to write to any environment you want.

However

You should really think before you do that. I would recommend not doing this unless in small functions in small scripts that only you use. The problem is that you lose sight of where which variable exists.


问:
What the different with this.text = 'a' vs this.setState({text:a'})
I've known  the component will re-render when the state change. but in this code:

```<code> <ColorPicker
     onColorSelected={color => this.color = color}
     style={{ width: width / 2, height: 200 }}
 />
     <View style={{ width: width / 2, height: 200, justifyContent: 'center' }}>
          <AnimatedText style={{ fontSize: 25, fontWeight: "bold", color:  this.color }}> asdasdasdasdasd</AnimatedText>
     </View>
</code>```

the no state change but the color of text still change. So what the mean of setState? and the way im doing, is it make better perfomance?

答:
this.setState({text:a'}) will invoke render method , this.text = 'a' will not.

react suggest using state props to update ui.

this.text = 'a' will work just after assignment but this.setState({text:a'}) will work in batch

Body:
I've known  the component will re-render when the state change. but in this code:

 <ColorPicker
     onColorSelected={color => this.color = color}
     style={{ width: width / 2, height: 200 }}
 />
     <View style={{ width: width / 2, height: 200, justifyContent: 'center' }}>
          <AnimatedText style={{ fontSize: 25, fontWeight: "bold", color:  this.color }}> asdasdasdasdasd</AnimatedText>
     </View>

the no state change but the color of text still change. So what the mean of setState? and the way im doing, is it make better perfomance?


问:
Load dynamic library and use functions inside the library
In C#, I am using an external dll, using loadLibrary, like this:

```<code>public class Utilities
    [DllImport("kernel32", CharSet= CharSet.Auto, SetLastError=true)]
    private static extern IntPtr LoadLibrary(string librayName);
    [DllImport("kernel32", CharSet= CharSet.Auto, SetLastError=true)]
    private static extern IntPtr GetProcAddress(intPtr hwnd, string procedureName);

    public static LoadAssembliesAndMethods() {
        string mainPath = AppDomain.CurrentDomain.BaseDirectory;
        string path = Path.Combine(mainPath, "MyAssembly.dll");

        IntPtr ptr = LoadLibrary(path);

        // What to do next in order to get all the list of functions/methods/class in the library and use them?

    }
</code>```

The dll has no signature of Assembly (it's a 3rd party), so I cannot do

```<code>Assebly.LoadFile(path);
</code>```

I need to get all of the functions/methods/class of the dll, and use some of them, using C#.

How can I do that.

答:
If you want to list all methods inside a unmanaged dll this link help you:

C# get the list of unmanaged C dll exports

Update:

```<code>IntPtr funcaddr = GetProcAddress(Handle,functionName);
YourFunctionDelegate function =
Marshal.GetDelegateForFunctionPointer(funcaddr,typeof(YourFunctionDelegate ))
as YourFunctionDelegate ;
function.Invoke(pass here your parameters);
</code>```

you need to create delegates at coding or using DynamicModules for creating delegates at runtime

Body:
In C#, I am using an external dll, using loadLibrary, like this:

public class Utilities
    [DllImport("kernel32", CharSet= CharSet.Auto, SetLastError=true)]
    private static extern IntPtr LoadLibrary(string librayName);
    [DllImport("kernel32", CharSet= CharSet.Auto, SetLastError=true)]
    private static extern IntPtr GetProcAddress(intPtr hwnd, string procedureName);

    public static LoadAssembliesAndMethods() {
        string mainPath = AppDomain.CurrentDomain.BaseDirectory;
        string path = Path.Combine(mainPath, "MyAssembly.dll");

        IntPtr ptr = LoadLibrary(path);

        // What to do next in order to get all the list of functions/methods/class in the library and use them?

    }

The dll has no signature of Assembly (it's a 3rd party), so I cannot do

Assebly.LoadFile(path);

I need to get all of the functions/methods/class of the dll, and use some of them, using C#.

How can I do that.

Body:
If you want to list all methods inside a unmanaged dll this link help you:

C# get the list of unmanaged C dll exports

Update:

IntPtr funcaddr = GetProcAddress(Handle,functionName);
YourFunctionDelegate function =
Marshal.GetDelegateForFunctionPointer(funcaddr,typeof(YourFunctionDelegate ))
as YourFunctionDelegate ;
function.Invoke(pass here your parameters);

you need to create delegates at coding or using DynamicModules for creating delegates at runtime


问:
org.jasypt.exceptions.EncryptionOperationNotPossibleException
I am using Jasypt-1.9.0 with Spring 3.1 and Hibernate 4.0.1. I have a requirement in my application to connect to database whose password(root) is stored  in the encrypted form in the property file within the application.

I looked online and found the way with following links:

http://www.jasypt.org/spring31.html

http://www.jasypt.org/hibernate.html

http://www.jasypt.org/encrypting-configuration.html

I have done the following steps and configuration for my requirement:

Added jasypt-1.9.0 and jasypt-hibernate4-1.9.0 in build path.

Added following in my dispatcher-servlet file:

```<code>< bean id="propertyConfigurer"
   class="org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer">

  < constructor-arg ref="configurationEncryptor" />
  < property name="locations">
    < list>
      < value>classpath:database.properties< /value>
    < /list>
  < /property>
< /bean>

< bean id="configurationEncryptor"
    class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
  < property name="config" ref="environmentVariablesConfiguration" />
< /bean>

< bean id="environmentVariablesConfiguration"
    class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig">
  < property name="algorithm" value="PBEWithMD5AndDES" />
  < property name="passwordEnvName" value="APP_ENCRYPTION_PASSWORD" />
</bean>
</code>```

Using CLI tool of Jasypt 1.9.0, I have generated the password
below(attached snapshot of CLI)

 - Added a new Environment  Varibale as APP_ENCRYPTION_PASSWORD with value as root

Added the encrypted password in database.properties file

```<code>db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/db1
db.username=root
db.password=ENC(bmfeQmgP/hJrh+mj6NANKA==)
</code>```

Now, if I run my application, the following exception appears:

```<code>org.jasypt.exceptions.EncryptionOperationNotPossibleException
    at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.decrypt(StandardPBEByteEncryptor.java:981)
    at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.decrypt(StandardPBEStringEncryptor.java:725)
    at org.jasypt.properties.PropertyValueEncryptionUtils.decrypt(PropertyValueEncryptionUtils.java:72)
</code>```

答:
I had a similar issue, but I realize when using the CLI tool and trying to decrypt the password you don't have to include the algorithm property and the password property needs to match the one used in the CLI Tool.

In their http://www.jasypt.org/encrypting-configuration.html

their example looks like this, but this doesn't work.

encryptor.setPassword("jasypt"); // could be got from web, env variable...
encryptor.setAlgorithm("PBEWithHMACSHA512AndAES_256");
encryptor.setIvGenerator(new RandomIvGenerator());

Solution:

encryptor.setPassword("MYPAS_WORD"); // Like in the CLI Tool
encryptor.setAlgorithm("PBEWithHMACSHA512AndAES_256"); //Remove this
encryptor.setIvGenerator(new RandomIvGenerator()); //Remove this as well

It'll work fine.

In your case you can remove the algorithm property and passwordEvnName needs to match the one used in CLI Tool.

Body:
I am using Jasypt-1.9.0 with Spring 3.1 and Hibernate 4.0.1. I have a requirement in my application to connect to database whose password(root) is stored  in the encrypted form in the property file within the application.

I looked online and found the way with following links:

http://www.jasypt.org/spring31.html

http://www.jasypt.org/hibernate.html

http://www.jasypt.org/encrypting-configuration.html

I have done the following steps and configuration for my requirement:

Added jasypt-1.9.0 and jasypt-hibernate4-1.9.0 in build path.

Added following in my dispatcher-servlet file:

< bean id="propertyConfigurer"
   class="org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer">

  < constructor-arg ref="configurationEncryptor" />
  < property name="locations">
    < list>
      < value>classpath:database.properties< /value>
    < /list>
  < /property>
< /bean>

< bean id="configurationEncryptor"
    class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
  < property name="config" ref="environmentVariablesConfiguration" />
< /bean>

< bean id="environmentVariablesConfiguration"
    class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig">
  < property name="algorithm" value="PBEWithMD5AndDES" />
  < property name="passwordEnvName" value="APP_ENCRYPTION_PASSWORD" />
</bean>

Using CLI tool of Jasypt 1.9.0, I have generated the password
below(attached snapshot of CLI)

 - Added a new Environment  Varibale as APP_ENCRYPTION_PASSWORD with value as root

Added the encrypted password in database.properties file

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/db1
db.username=root
db.password=ENC(bmfeQmgP/hJrh+mj6NANKA==)

Now, if I run my application, the following exception appears:

org.jasypt.exceptions.EncryptionOperationNotPossibleException
    at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.decrypt(StandardPBEByteEncryptor.java:981)
    at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.decrypt(StandardPBEStringEncryptor.java:725)
    at org.jasypt.properties.PropertyValueEncryptionUtils.decrypt(PropertyValueEncryptionUtils.java:72)


问:
Gmail centers email signature when it shouldn't
I have made an email signature for a client which works perfectly on everything except Gmail. When I try to use the signature in Gmail it somehow centers it. This is only on the browser version. When I view the signature in the mail app on the iPhone it looks good. When I send the signature to Gmail from, for example, Outlook it looks good too. A screenshot of the problem: click .

I have no idea why this happens so I hope someone here has the answer for me. My code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3-column layout</title>

</head>

<style type="text/css">
/* Client-specific Styles */

#outlook a {
padding: 0;
} /* Force Outlook to provide a "view in browser" menu link. */
body {
width: 100% !important;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
margin: 0;
padding: 0;
}
/* Prevent Webkit and Windows Mobile platforms from changing default font sizes, while not breaking desktop design. */
.ExternalClass {
width: 100%;
} /* Force Hotmail to display emails at full width */
   .ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font,              .ExternalClass td, .ExternalClass div {
    line-height: 100%;
    } /* Force Hotmail to display normal line spacing.  More on that:     http://www.emailonacid.com/forum/viewthread/43/ */
#backgroundTable {
margin: 0;
padding: 0;
width: 100% !important;
line-height: 100% !important;
}
img {
outline: none;
text-decoration: none;
border: none;
-ms-interpolation-mode: bicubic;
}
a img {
border: none;
}
.image_fix {
display: block;
}
p {
margin: 0px 0px !important;
}
table td {
border-collapse: collapse;
}
table {
border-collapse: collapse;
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
}

/*##############################################*/
/*IPHONE STYLES*/
/*##############################################*/
@media only screen and (max-width: 480px) {
table {
position: relative;
}

table[class="fluid-table"], td[class="fluid-cell"]{
width: 100% !important;
padding: 0 20px 0 20px!important;

}

}
</style>

<body style="padding:0; margin:0">
<!--
/*##############################################*/

3 column

/*##############################################*/
-->

<table align="left" border="0" cellpadding="0" cellspacing="0" class="fluid-table">
<tbody>

  <tr>
    <td  align="left" style="display:block; border:none; outline:none; text-decoration:none; color:#000; font-size:14px; text-align:left; font-family: Open Sans, Arial, Verdana, sans-serif;" border="0">
            <span style="text-align: left; color: #9C1C27;font-size: 14px; font-weight: bold">Voornaam en Achternaam</span><br>
            <span style="text-align: left; margin-top: 0px; margin-bottom: 0px; color: #B5987F; font-weight: normal; font-style:italic; font-size: 12px;">Functie titel</span><br>
    </td>
  </tr>

<tr>
    <td valign="top" style="padding-left: 0px; padding-top: 7px; padding-bottom: 10px; padding-right: 0px; width:100%; height:100%;">
        <a href="http://www.deleeuwhides.com/"><img src="http://www.deleeuwhides.com/img/logo.png" nosend="1" border="0" style="width:179px; height:111px;"  alt="De Leeuw Hides logo" title="De Leeuw Hides logo"></a>
    </td>
    </tr>
   </tbody>
 </table>

<div class="block">
  <table cellpadding="0" cellspacing="0" border="0" width="100%" align="left">
<tr>
  <td><table cellpadding="0" cellspacing="0" border="0" width="600" align="left" class="fluid-table">
      <tr>

        <!-- Start of first column -->

        <td><table width="175" align="left" border="0" cellpadding="0" cellspacing="0" class="fluid-table">
            <tbody>

              <tr>
                <td width="175" align="left" style=" border:none; text-decoration:none; color:#B5987F; font-size:14px; text-align:left; font-family: Open Sans, Arial, Verdana, sans-serif;" border="0">
                    <strong style="color:#9C1C27;">Location Nijmegen</strong><br>
                    Lindenhoutseweg 69<br>
                    6545 AH Nijmegen <br>
                    The Netherlands
                </td>
              </tr>

            </tbody>
          </table>

          <!-- End of first column -->

          <!--[if mso]></td><td valign="top"><![endif]-->

          <!-- Start of second column -->

          <table width="175" align="left" border="0" cellpadding="0" cellspacing="0" class="fluid-table">
            <tbody>

              <tr>
                <td width="175" align="left" style="border:none; text-decoration:none; color:#B5987F; font-size:14px; text-align:left; font-family: Open Sans, Arial, Verdana, sans-serif;" border="0">
                    <strong style="color:#9C1C27;">Location Winterswijk</strong><br>
                    Industrieweg 2a<br>
                    7102 DZ Winterswijk<br>
                    The Netherlands
                </td>
              </tr>
            </tbody>
          </table>

          <!-- End of second column -->

          <!--[if mso]></td><td valign="top"><![endif]-->

          <!-- Start of third column -->

          <table width="175" align="left" border="0" cellpadding="0" cellspacing="0" class="fluid-table">
            <tbody>
              <tr>
                 <td width="175" align="left" style="border:none; text-decoration:none; color:#B5987F; font-size:14px; text-align:left; font-family: Open Sans, Arial, Verdana, sans-serif;" border="0">
                        <a href="tel:0031-024-3775233" style="color:#B5987F;"><font>T:</font> 0031-024-3775233</a> <br>
                        F: 0031-024-3779316 <br>
                        <a style="text-decoration:none; color:#9C1C27;" href="mailto:sales@deleeuwhides.nl">sales@deleeuwhides.nl</a><br>
                        <a style="text-decoration:none; color:#9C1C27;" href="http://www.deleeuwhides.com">www.deleeuwhides.com</a>
                    </td>
              </tr>
            </tbody>
          </table>

          <!-- End of third column --></td>
      </tr>
    </table>

    <table cellpadding="0" cellspacing="0" border="0" width="100%" align="left" style="margin-top:5px; margin-bottom:3px;" class="fluid-table">
       <tr>
            <td style="padding: 0 0 2px 0; height:1px; width:100%; background-color:#B5987F;">
            </td>
        </tr>
    </table>

        <table cellpadding="0" cellspacing="0" border="0" width="100%" align="left" class="fluid-table">
                <tr>
                    <td valign="top"bgcolor="#9C1C27" style="height:30px; width:100%; background-color:#9C1C27;"><img style="display:block; margin:auto; padding:8px 0 0 0;" src="http://www.deleeuwhides.com/img/slogan-footer.png" alt="slogan">
                    </td>
               </tr>
        </table>

   </td>
 </tr>
</table>

</div>
</body>
</html>
</code>```

Thanks in advance!

答: I had the same issue and solved it by applying <strong>"margin:0 !important"</strong> to the signature main container. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have made an email signature for a client which works perfectly on everything except Gmail. When I try to use the signature in Gmail it somehow centers it. This is only on the browser version. When I view the signature in the mail app on the iPhone it looks good. When I send the signature to Gmail from, for example, Outlook it looks good too. A screenshot of the problem: click .

I have no idea why this happens so I hope someone here has the answer for me. My code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3-column layout</title>

            Voornaam en Achternaam

            Functie titel

                    Location Nijmegen

                    Lindenhoutseweg 69

                    6545 AH Nijmegen

                    The Netherlands

                    Location Winterswijk

                    Industrieweg 2a

                    7102 DZ Winterswijk

                    The Netherlands

                        T: 0031-024-3775233

                        F: 0031-024-3779316

                        sales@deleeuwhides.nl

                        www.deleeuwhides.com

Thanks in advance!

Body: I had the same issue and solved it by applying "margin:0 !important" to the signature main container.


问:
How to remove Kotlin Support from Flutter App?
Created a new Flutter project with Kotlin support on Android Studio and it is giving the following error on running the app:-

What went wrong: Execution failed for task ':app:compileDebugKotlin'.

Now I just want to remove the Kotlin support from my project, please suggest the steps?

答:
According to your question, there might be many reasons behind...

Check out this Stack Overflow Solution if this can work.

Apart from this, To remove Kotlin support you can check your Gradle for some lines below..

```<code>buildscript {
    ext.kotlin_version = '1.2.71'
    ...

    dependencies {
        ...
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
</code>```

```<code>...
apply plugin: 'kotlin-android'
...
android{
    ...
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
    ...
}
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    ...
}
</code>```

Delete all of these above to remove kotlin support in your project.

Body:
According to your question, there might be many reasons behind...

Check out this Stack Overflow Solution if this can work.

Apart from this, To remove Kotlin support you can check your Gradle for some lines below..

buildscript {
    ext.kotlin_version = '1.2.71'
    ...

    dependencies {
        ...
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

...
apply plugin: 'kotlin-android'
...
android{
    ...
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
    ...
}
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    ...
}

Delete all of these above to remove kotlin support in your project.


问:
Media Queries: How to target all landscape devices below 1024 using css media query
How to target all landscape devices below 1024 using css media query this should work only for mobile devices not desktop browsers</p>

答:
```<code>@media only screen
  and (max-device-width: 1024px)
  and (orientation: landscape)
  and (-webkit-min-device-pixel-ratio: 2) {

    //your styles

}
</code>```


问:
Git discard all changes
Hi folks I am new developer trying to learn.

I use git desktop where you right click on a file and select discard changes, if you don't want to add that file into commit. It revert it back to its original state.

Now I am working in terminal how can I do that in terminal?

By mistake I added some changes into a file and I don't want to keep those changes. Please help.

Please, I am not an advanced user therefore kindly keep it as simple as possible. I have not made any commit on that machine yet.

I am only interested in I googled it but could not find a simple layman'ish answer.

答:
You can do this in several ways

You can checkout original file

```<code>git checkout file_path
</code>```

Stash changes and continue work

```<code>git stash file_path
</code>```

Revert head to the previous commit

```<code>git reset --hard HEAD~1
</code>```

Checkout to a specific commit

```<code>git reset --hard commit_sha
</code>```

Title: Git discard all changes

Body:
You can do this in several ways

You can checkout original file

git checkout file_path

Stash changes and continue work

git stash file_path

Revert head to the previous commit

git reset --hard HEAD~1

Checkout to a specific commit

git reset --hard commit_sha


问:
How convert a very large JSON response of a web service into CSV using Python?
I call a web service that returns a very large JSON response. I want to parse it and convert it into a CSV format using Python. I have written a code to load json and convert it to CSV. However, for a large response it raises MemoryError. How can I load and convert response data using streaming?

Here is my code

```<code>import json
from pandas import json_normalize
re = requests.get(url)
data = json.loads(re.text)
df = json_normalize(data)
df.to_csv(fileName, index=False, encoding='utf-8')
</code>```

Here is a sample of my JSON response:

```<code>[{"F1":"V1_1","F2":false,,"F3":120,"F4":"URL1","F5":{"F5_1":4,"F5_2":"A"}},
{"F1":"V2_1","F2":true,,"F3":450,"F4":"URL2","F5":{"F5_1":13,"F5_2":"B"}},
{"F1":"V3_1","F2":false,,"F3":312,"F4":"URL3","F5":{"F5_1":6,"F5_2":"C"}},
...
]
</code>```

The MemoryError occurs in the json.loads() function. I also test following python code:

```<code>import pandas as pd
response = requests.get(url)
data = response.json()
df = pd.json_normalize(data)
df.to_csv("filename.csv", index=False, encoding="utf-8")
</code>```

But still there is a MemmoryError on response.json() function.
Is there any idea how I can load and parse and convert such a big JSON response to a CSV file?

答:
There is no well-known or "the best" way to handle very large JSON files.

However requests library provide a way to stream results line by line and with modifications of lines it might be possible to achieve your task.

The algorithm is simple:

Iterate over these lines parsing every single line as JSON as in streaming results example in requests library

replace "special" markers in the data stream so JSON parser could parse each record without problems. Markers: delete openning [, replace separator },\n{ by }\n{, delete closing ]. For your example you'll need to replace double coma ,, with single one , as well

At the end you should receive code resembling the following:

import requests

import json, pandas as pd

url = '...'
filename = '...'

def decode_record(r):
    pl: str = r.decode('utf-8')
    pl = pl.replace('[{', '{').replace('}},', '}}').replace(',,', ',').replace('}}]', '}}')
    # The rest of cleanup goes here
    return json.loads(pl)

def run():
    r = requests.get(url, stream=True)
    res = []
    for line in r.iter_lines():

        # filter out keep-alive new lines
        if line:
            jso = decode_record(line)
            # You might also want to stream lines directly to CSV file here,
            # just not to allocate the DataFrame
            res.append(jso)
    df = pd.DataFrame(res)
    # Parsingof F5 field may be better performed with Pandas functions
    # because it's still a complex object
    print(df.info())
    df.to_csv(filename, index=False, encoding='utf-8')

```

<p>The variation without a dataframe:</p>

<pre class="lang-py prettyprint-override"><code>import requests
import json

url = '...'
filename = '...'

def decode_record(r):
    pl: str = r.decode('utf-8')
    pl = pl.replace('[{', '{').replace('}},', '}}').replace(',,', ',').replace('}}]', '}}')
    # The rest of cleanup goes here
    return json.loads(pl)

def encode_csv_record(jso):
    res = []
    for k,v in jso.items():
        res.append(str(v))
    return ','.join(res)

def run():
    r = requests.get(url, stream=True)
    res = []
    with open(filename, 'w') as csvout:
        for line in r.iter_lines():
            # filter out keep-alive new lines
            if line:
                jso = decode_record(line)
                csv_line = encode_csv_record(jso)
                csvout.writelines(csv_line)
</code>```

Of cause this answer has some leaks but it should present the idea.

Body:
I call a web service that returns a very large JSON response. I want to parse it and convert it into a CSV format using Python. I have written a code to load json and convert it to CSV. However, for a large response it raises MemoryError. How can I load and convert response data using streaming?

Here is my code

import json
from pandas import json_normalize
re = requests.get(url)
data = json.loads(re.text)
df = json_normalize(data)
df.to_csv(fileName, index=False, encoding='utf-8')

Here is a sample of my JSON response:

[{"F1":"V1_1","F2":false,,"F3":120,"F4":"URL1","F5":{"F5_1":4,"F5_2":"A"}},
{"F1":"V2_1","F2":true,,"F3":450,"F4":"URL2","F5":{"F5_1":13,"F5_2":"B"}},
{"F1":"V3_1","F2":false,,"F3":312,"F4":"URL3","F5":{"F5_1":6,"F5_2":"C"}},
...
]

The MemoryError occurs in the json.loads() function. I also test following python code:

import pandas as pd
response = requests.get(url)
data = response.json()
df = pd.json_normalize(data)
df.to_csv("filename.csv", index=False, encoding="utf-8")

But still there is a MemmoryError on response.json() function.
Is there any idea how I can load and parse and convert such a big JSON response to a CSV file?

Body:
There is no well-known or "the best" way to handle very large JSON files.

However requests library provide a way to stream results line by line and with modifications of lines it might be possible to achieve your task.

The algorithm is simple:

Iterate over these lines parsing every single line as JSON as in streaming results example in requests library

replace "special" markers in the data stream so JSON parser could parse each record without problems. Markers: delete openning [, replace separator },\n{ by }\n{, delete closing ]. For your example you'll need to replace double coma ,, with single one , as well

At the end you should receive code resembling the following:

import requests

import json, pandas as pd

url = '...'
filename = '...'

def decode_record(r):
    pl: str = r.decode('utf-8')
    pl = pl.replace('[{', '{').replace('}},', '}}').replace(',,', ',').replace('}}]', '}}')
    # The rest of cleanup goes here
    return json.loads(pl)

def run():
    r = requests.get(url, stream=True)
    res = []
    for line in r.iter_lines():

        # filter out keep-alive new lines
        if line:
            jso = decode_record(line)
            # You might also want to stream lines directly to CSV file here,
            # just not to allocate the DataFrame
            res.append(jso)
    df = pd.DataFrame(res)
    # Parsingof F5 field may be better performed with Pandas functions
    # because it's still a complex object
    print(df.info())
    df.to_csv(filename, index=False, encoding='utf-8')

The variation without a dataframe:

import requests
import json

url = '...'
filename = '...'

def decode_record(r):
    pl: str = r.decode('utf-8')
    pl = pl.replace('[{', '{').replace('}},', '}}').replace(',,', ',').replace('}}]', '}}')
    # The rest of cleanup goes here
    return json.loads(pl)

def encode_csv_record(jso):
    res = []
    for k,v in jso.items():
        res.append(str(v))
    return ','.join(res)

def run():
    r = requests.get(url, stream=True)
    res = []
    with open(filename, 'w') as csvout:
        for line in r.iter_lines():
            # filter out keep-alive new lines
            if line:
                jso = decode_record(line)
                csv_line = encode_csv_record(jso)
                csvout.writelines(csv_line)

Of cause this answer has some leaks but it should present the idea.


问:
SQL Server CREATE tables with types
I need to create a table that has a choice of 2 types. The main table is product with:

ProductCode

ProductName

ProductPrice

ProductStockLevel

ProductType

It then splits into 2 choices, food and non-food. Under food, it will have expiry date and under non-food, it will ask for classifications such as bedding, clothes, cosmetics etc. It will then have the offer id, offer period and offer price as the last 3 columns for both.

Example:

What is the query needed to create the 2 types or how do I go about doing something like this?

答:
Solution 1 :  Using CHECK constraint

Your query should be like below :

```<code>CREATE TABLE Product (ProductCode int, ProductName varchar(255),
                      ProductPrice float,ProductStockLevel int,
                      ProductType varchar(255) NOT NULL CHECK (ProductType IN('Food', 'Non-Food')))
</code>```

And keep the two columns Class and ExprDate.

If the Type is Food set Class to Undefined.

If the Type is Non-Food set ExprDate to 9999-12-31.

Solution 2 : Implementing Table Inheritance in SQL Server

Start by creating a Base Table - Deriving Sub-Tables from the Base Table
 :

```<code>create table Product(ProductCode int primary key, ProductName varchar,ProductPrice float,ProductStockLevel int )

create table FoodProduct(ProductCode int primary key references Product(ProductCode ), ExprDate date)
create table NonFoodProduct(ProductCode int primary key references Product(ProductCode ), [Calss] varchar(255))
</code>```

Title: SQL Server CREATE tables with types

Body:
Solution 1 :  Using CHECK constraint

Your query should be like below :

CREATE TABLE Product (ProductCode int, ProductName varchar(255),
                      ProductPrice float,ProductStockLevel int,
                      ProductType varchar(255) NOT NULL CHECK (ProductType IN('Food', 'Non-Food')))

And keep the two columns Class and ExprDate.

If the Type is Food set Class to Undefined.

If the Type is Non-Food set ExprDate to 9999-12-31.

Solution 2 : Implementing Table Inheritance in SQL Server

Start by creating a Base Table - Deriving Sub-Tables from the Base Table
 :

create table Product(ProductCode int primary key, ProductName varchar,ProductPrice float,ProductStockLevel int )

create table FoodProduct(ProductCode int primary key references Product(ProductCode ), ExprDate date)
create table NonFoodProduct(ProductCode int primary key references Product(ProductCode ), [Calss] varchar(255))


问:
Python how to insert extracted title from name field and add it to its specific column and index?
I am trying to extract the title from name field in a dataframe and append into new column using python:

```<code>import pandas as pd
df = pd.DataFrame(columns = ['id', 'name'])
df = df.append({'id': 123, 'name': 'Mr. Rooney'}, ignore_index=True)
df = df.append({'id': 124, 'name': 'Miss. Aniston'}, ignore_index=True)
df = df.append({'id': 125, 'name': 'Sir. Alex'}, ignore_index=True)
</code>```

And then I have the following list containing title names:

```<code>titles = ['Miss.', 'Mr.', 'Master', 'Sir.', 'Mrs.']
</code>```

I've added a new column to the data frame:

```<code>df['Title']=''
</code>```

Now I will iterate all the rows and write the existing title of each name at its corresponding row:

```<code>for idx, row in (df.iterrows()):
  for t in titles:
    if(t in row['name']):
      df['Title']=t
</code>```

Apparently I am not been able to iterate over each index. I am new to python for data science.

How to extract the title for each row and add to its corespondent index?

答:
One line solution for your problem is as below.

```<code>df['title'] = df['name'].apply(lambda x : x.split('.')[0].strip())
</code>```

You can avoid a loop in pandas by using apply().
It executes faster than a loop.

Body:
I am trying to extract the title from name field in a dataframe and append into new column using python:

import pandas as pd
df = pd.DataFrame(columns = ['id', 'name'])
df = df.append({'id': 123, 'name': 'Mr. Rooney'}, ignore_index=True)
df = df.append({'id': 124, 'name': 'Miss. Aniston'}, ignore_index=True)
df = df.append({'id': 125, 'name': 'Sir. Alex'}, ignore_index=True)

And then I have the following list containing title names:

titles = ['Miss.', 'Mr.', 'Master', 'Sir.', 'Mrs.']

I've added a new column to the data frame:

df['Title']=''

Now I will iterate all the rows and write the existing title of each name at its corresponding row:

for idx, row in (df.iterrows()):
  for t in titles:
    if(t in row['name']):
      df['Title']=t

Apparently I am not been able to iterate over each index. I am new to python for data science.

How to extract the title for each row and add to its corespondent index?

Body:
One line solution for your problem is as below.

df['title'] = df['name'].apply(lambda x : x.split('.')[0].strip())

You can avoid a loop in pandas by using apply().
It executes faster than a loop.