问:
sklearn confusion_matrix: ValueError: not enough values to unpack (expected 4, got 1)
I am getting this error while running the eval report. I trained my model with bert-base-german-cased for my custom dataset.

The code is as follows:

```<code>from sklearn.metrics import confusion_matrix

...
tn, fp, fn, tp = confusion_matrix(labels, preds).ravel()
</code>```

and the error is

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-33-0d7757abd7dd> in <module>
     10         model = model_class.from_pretrained(checkpoint)
     11         model.to(device)
---> 12         result, wrong_preds = evaluate(model, tokenizer, prefix=global_step)
     13         result = dict((k + '_{}'.format(global_step), v) for k, v in result.items())
     14         results.update(result)

<ipython-input-30-c0946f859f89> in evaluate(model, tokenizer, prefix)
     76     elif args['output_mode'] == "regression":
     77         preds = np.squeeze(preds)
---> 78     result, wrong = compute_metrics(EVAL_TASK, preds, out_label_ids)
     79     results.update(result)
     80

<ipython-input-30-c0946f859f89> in compute_metrics(task_name, preds, labels)
     25 def compute_metrics(task_name, preds, labels):
     26     assert len(preds) == len(labels)
---> 27     return get_eval_report(labels, preds)
     28
     29 def evaluate(model, tokenizer, prefix=""):

<ipython-input-30-c0946f859f89> in get_eval_report(labels, preds)
     14 def get_eval_report(labels, preds):
     15     mcc = matthews_corrcoef(labels, preds)
---> 16     tn, fp, fn, tp = confusion_matrix(labels, preds).ravel()
     17     return {
     18         "mcc": mcc,
</code>```

How do I fix this error?

答:
sklearn's confusion matrix returns a 1-element 1D array when all the predictions and ground truth match. For example:

>>> confusion_matrix([1, 1, 1, 1], [1, 1, 1, 1]).ravel()
array([4], dtype=int64)
```
<p>So even though we might have been dealing with binary classification here, i.e., 0 and 1, <code>confusion_matrix</code> naturally has no idea. But there is a way to tell this and it is the <code>labels</code> parameter:</p>
<pre class="lang-py prettyprint-override"><code>>>> confusion_matrix([1, 1, 1, 1], [1, 1, 1, 1], labels=[0, 1]).ravel()
array([0, 0, 0, 4], dtype=int64)
</code>```

Now it is okay: we have 4 TPs and no sample for other 3 fields.

So you should give labels argument with your possible 2 classification values, e.g., [0, 1].

Body:
I am getting this error while running the eval report. I trained my model with bert-base-german-cased for my custom dataset.

The code is as follows:

from sklearn.metrics import confusion_matrix

...
tn, fp, fn, tp = confusion_matrix(labels, preds).ravel()

and the error is

ValueError                                Traceback (most recent call last)
<ipython-input-33-0d7757abd7dd> in <module>
     10         model = model_class.from_pretrained(checkpoint)
     11         model.to(device)
---> 12         result, wrong_preds = evaluate(model, tokenizer, prefix=global_step)
     13         result = dict((k + '_{}'.format(global_step), v) for k, v in result.items())
     14         results.update(result)

<ipython-input-30-c0946f859f89> in evaluate(model, tokenizer, prefix)
     76     elif args['output_mode'] == "regression":
     77         preds = np.squeeze(preds)
---> 78     result, wrong = compute_metrics(EVAL_TASK, preds, out_label_ids)
     79     results.update(result)
     80

<ipython-input-30-c0946f859f89> in compute_metrics(task_name, preds, labels)
     25 def compute_metrics(task_name, preds, labels):
     26     assert len(preds) == len(labels)
---> 27     return get_eval_report(labels, preds)
     28
     29 def evaluate(model, tokenizer, prefix=""):

<ipython-input-30-c0946f859f89> in get_eval_report(labels, preds)
     14 def get_eval_report(labels, preds):
     15     mcc = matthews_corrcoef(labels, preds)
---> 16     tn, fp, fn, tp = confusion_matrix(labels, preds).ravel()
     17     return {
     18         "mcc": mcc,

How do I fix this error?

Body:
sklearn's confusion matrix returns a 1-element 1D array when all the predictions and ground truth match. For example:

>>> confusion_matrix([1, 1, 1, 1], [1, 1, 1, 1]).ravel()
array([4], dtype=int64)

So even though we might have been dealing with binary classification here, i.e., 0 and 1, confusion_matrix naturally has no idea. But there is a way to tell this and it is the labels parameter:

>>> confusion_matrix([1, 1, 1, 1], [1, 1, 1, 1], labels=[0, 1]).ravel()
array([0, 0, 0, 4], dtype=int64)

Now it is okay: we have 4 TPs and no sample for other 3 fields.

So you should give labels argument with your possible 2 classification values, e.g., [0, 1].


来源: stackexchange

问:
How to update dynamically an object in Javascript?
I've got an object and I want to update it with new data. But, if one of the keys has a value of undefined, I want it to have the same value it was priorly defined.

```<code>let obj

obj = {
  name: 'Bill'
  job: 'dev'
  age: 22
}

const newObj = {
  name: 'Sam',
  age: 33
}

Object.keys(obj).forEach(key => {
  obj[key] = newObj[key];
});

</code>```

I want obj to return:

```<code>{
  name: "Sam"
  job:'dev',
  age: 33,

}
</code>```

But it returns:

```<code>{
  age: 33,
  job: undefined,
  name: "Sam"
}
</code>```

Also, it would help to return in the same order as the original.

答:
```<code>let obj

obj = {
  name: 'Bill',
  job: 'dev',
  age: 22
}

const newObj = {
  name: 'Sam',
  age: 33
}

obj= {
  ...obj,
  ...newObj
}
</code>```

Spread will solve your problem. newObject properties will override object properties. (same properties for override)

ContentLicense: CC BY-SA 4.0

Body:
I've got an object and I want to update it with new data. But, if one of the keys has a value of undefined, I want it to have the same value it was priorly defined.

let obj

obj = {
  name: 'Bill'
  job: 'dev'
  age: 22
}

const newObj = {
  name: 'Sam',
  age: 33
}

Object.keys(obj).forEach(key => {
  obj[key] = newObj[key];
});

I want obj to return:

{
  name: "Sam"
  job:'dev',
  age: 33,

}

But it returns:

{
  age: 33,
  job: undefined,
  name: "Sam"
}

Also, it would help to return in the same order as the original.

Body:
let obj

obj = {
  name: 'Bill',
  job: 'dev',
  age: 22
}

const newObj = {
  name: 'Sam',
  age: 33
}

obj= {
  ...obj,
  ...newObj
}

Spread will solve your problem. newObject properties will override object properties. (same properties for override)


问:
Assigning callbacks for a $.post call in jQuery
I have this script that works pretty well, but it keeps triggering the "error" callback, even though there is no error:

```<code>$(".comment-form").submit(function(e) {
    e.preventDefault();

    var $form = $(this),
        text = $form.find('textarea').val();
        url = $form.attr('action');

    $.post(url, { comment: text,
        beforeSend: function() {
            alert("before send");
        },
        error: function() {
            alert("error");
        },
        success: function(data) {
            alert(data);
        }
    });
});
</code>```

Am I using the callbacks incorrectly here? Shouldn't the error callback fire only if there's an ajax error?

My intention is react to the request. If it has an error, I want to do something. If it's successful, I want to do something else, etc...

答:
You're passing the callbacks as part of the data to be posted, so they're getting evaluated as part of the post call.  Try this:

```<code>$.post(url, { comment: text }, function(data) {
        alert(data);
});
</code>```

or

```<code>$.ajax(url, { data: { comment: text },
    type: "POST",
    beforeSend: function() {
        alert("before send");
    },
    error: function() {
        alert("error");
    },
    success: function(data) {
        alert(data);
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this script that works pretty well, but it keeps triggering the "error" callback, even though there is no error:

$(".comment-form").submit(function(e) {
    e.preventDefault();

    var $form = $(this),
        text = $form.find('textarea').val();
        url = $form.attr('action');

    $.post(url, { comment: text,
        beforeSend: function() {
            alert("before send");
        },
        error: function() {
            alert("error");
        },
        success: function(data) {
            alert(data);
        }
    });
});

Am I using the callbacks incorrectly here? Shouldn't the error callback fire only if there's an ajax error?

My intention is react to the request. If it has an error, I want to do something. If it's successful, I want to do something else, etc...

Body:
You're passing the callbacks as part of the data to be posted, so they're getting evaluated as part of the post call.  Try this:

$.post(url, { comment: text }, function(data) {
        alert(data);
});

or

$.ajax(url, { data: { comment: text },
    type: "POST",
    beforeSend: function() {
        alert("before send");
    },
    error: function() {
        alert("error");
    },
    success: function(data) {
        alert(data);
    }
});


问:
Gettign values from jquery ajax sucess using jason
I'm new to jquery and I can;t find an answer to my simple problem on the web.

I have

```<code>     $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "Default.aspx/Getmessage",
                data: "{'uid': '" + "XX" + "' }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: OnFailure
            });
        });
        function OnSuccess(data) {
            $("#lblMessageReceived").html(data.uid + data.text);
        }
        function OnFailure() {
            alert("Error");
        }
</code>```

Server side I have

```<code>Public Class clsResponseData
    Public Property uid As String
    Public Property text As String = "Hello"
End Class

<System.Web.Services.WebMethod()>
Public Shared Function getMessage(uid As String) As String
     Dim rd As New clsResponseData
     rd.uid = uid
     Return JsonConvert.SerializeObject(rd)
End Function
</code>```

When I run the code I get

```<code>    "data" as Object {d: "{"uid":"XX","text":"Hello"}"}
and then
    "data.d" as "{"uid":"XX","text":"Hello"}"
but then
    "data.d.uid" returns undefined
so how do I reference the value of "uid" and "text"? .
</code>```

I have tried this code with the Visuals Studio editor and Chrome browser insepction. What else do I need to add?

答:
In case anyone looks for this, i cound the answer is to add an eval() function</p>

```<code>function OnSuccess(data) {
         eval('var t =' + data.d);
         $("#lblMessageReceived").html(t.uid + t.text);
        }
</code>```

Body:
I'm new to jquery and I can;t find an answer to my simple problem on the web.

I have

     $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "Default.aspx/Getmessage",
                data: "{'uid': '" + "XX" + "' }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: OnFailure
            });
        });
        function OnSuccess(data) {
            $("#lblMessageReceived").html(data.uid + data.text);
        }
        function OnFailure() {
            alert("Error");
        }

Server side I have

Public Class clsResponseData
    Public Property uid As String
    Public Property text As String = "Hello"
End Class

<System.Web.Services.WebMethod()>
Public Shared Function getMessage(uid As String) As String
     Dim rd As New clsResponseData
     rd.uid = uid
     Return JsonConvert.SerializeObject(rd)
End Function

When I run the code I get

    "data" as Object {d: "{"uid":"XX","text":"Hello"}"}
and then
    "data.d" as "{"uid":"XX","text":"Hello"}"
but then
    "data.d.uid" returns undefined
so how do I reference the value of "uid" and "text"? .

I have tried this code with the Visuals Studio editor and Chrome browser insepction. What else do I need to add?

Body:
In case anyone looks for this, i cound the answer is to add an eval() function

function OnSuccess(data) {
         eval('var t =' + data.d);
         $("#lblMessageReceived").html(t.uid + t.text);
        }


问:
Ruby on Rails ActiveStorage image doesn't show up
I am working on an app which works fine before with active storage. But I am not sure what happened but it's no longer working anymore and it's showing a broken image:

Here's what I did in the past on my contact model:

```<code>  has_one_attached :contact_avatar
</code>```

And in my views/index.html.erb:

```<code>  <%= image_tag contact.contact_avatar.attached? ? contact.contact_avatar : "100x100.png", class: "media-object img-thumbnail img-rounded mr-3" %>
</code>```

Any idea what's causing this?

MORE INFO: Whenever I am trying to insert or upload a photo using ActiveStorage I am always having this on my terminal:

```<code>[ActiveJob] [ActiveStorage::AnalyzeJob] [875b372f-3647-4ba0-8beb-3fe38e8885d3]    (9.6ms)  COMMIT
[ActiveJob] [ActiveStorage::AnalyzeJob] [875b372f-3647-4ba0-8beb-3fe38e8885d3]   ↳ /Users/richard/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
[ActiveJob] [ActiveStorage::AnalyzeJob] [875b372f-3647-4ba0-8beb-3fe38e8885d3] Performed ActiveStorage::AnalyzeJob (Job ID: 875b372f-3647-4ba0-8beb-3fe38e8885d3) from Async(default) in 104.68ms
Started GET "/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBHQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--05a842304d7509391444fb7250f49645b77cff00/madman.png" for ::1 at 2020-05-29 13:13:19 +0800
Processing by ErrorsController#page_not_found as PNG
  Parameters: {"path"=>"rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBHQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--05a842304d7509391444fb7250f49645b77cff00/madman"}
  Rendering errors/404.html.erb within layouts/application
  Rendered errors/404.html.erb within layouts/application (0.8ms)
</code>```

Here's the contact controller:

```<code>class ContactsController < ApplicationController
  before_action :set_contact, only: [:show, :edit, :update, :destroy]
  skip_before_action :verify_authenticity_token, only: [:destroy]
  before_action :authenticate_user!

  def index
    @contacts = current_user.contacts.order(created_at: :desc).page(params[:page])
    @contacts = @contacts.where(category_id: params[:category_id]) if params[:category_id].present?
    @contacts = @contacts.search(params[:term]) if params[:term].present?
  end

  def autocomplete
      @contacts = current_user.contacts.order(created_at: :desc).page(params[:page])
      @contacts = @contacts.where(category_id: params[:category_id]) if params[:category_id].present?
      @contacts = @contacts.search(params[:term]) if params[:term].present?
      render json: @contacts.map { |contact| { id: contact.id, value: contact.name }}
  end

  def show
  end

  def new
    @contact = Contact.new
  end

  def edit
    authorize @contact
  end

  def create
    @contact = current_user.contacts.build(contact_params)
    @success = @contact.save ? true : false

    respond_to do |format|
      if @success
        format.html { redirect_to contacts_path, notice: 'Contact was successfully created.' }
        format.js
      else
        format.js
      end
    end
  end

  def update
    @success = @contact.update(contact_params) ? true : false

    respond_to do |format|
      if @success
        format.html { redirect_to contacts_path, notice: 'Contact was successfully updated.' }
        format.js
      else
        format.js
      end
    end
  end

  def destroy
    authorize @contact
    @contact.destroy
    respond_to do |format|
      format.html { redirect_to contacts_url, notice: 'Contact was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_contact
      @contact = Contact.find(params[:id])
    end

    def contact_params
      params.require(:contact).permit(:name, :email, :mobile, :phone, :country, :address, :city, :state, :zip, :note, :category_id, :contact_avatar)
    end

    def has_error?(resource, field)
      resource.errors.messages[field].present?
    end

    def get_error(resource, field)
      msg = resource.errors.messages[field]
      field.to_s.capitalize + " " + msg.join(' and ') + '.'
    end

    helper_method :has_error?
    helper_method :get_error
end
</code>```

Here's the storage.yml file:

```<code>test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

# Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
# amazon:
#   service: S3
#   access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
#   secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
#   region: us-east-1
#   bucket: your_own_bucket

# Remember not to checkin your GCS keyfile to a repository
# google:
#   service: GCS
#   project: your_project
#   credentials: <%= Rails.root.join("path/to/gcs.keyfile") %>
#   bucket: your_own_bucket

# Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key)
# microsoft:
#   service: AzureStorage
#   storage_account_name: your_account_name
#   storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %>
#   container: your_container_name

# mirror:
#   service: Mirror
#   primary: local
#   mirrors: [ amazon, google, microsoft ]
</code>```

答:
Add these gems to the gemfile and run bundle

```<code>#Gemfile
gem 'image_processing'
gem 'mini_magick'
</code>```

You can also need to run
sudo apt install imagemagick in your console afterwards.

Body:
I am working on an app which works fine before with active storage. But I am not sure what happened but it's no longer working anymore and it's showing a broken image:

Here's what I did in the past on my contact model:

  has_one_attached :contact_avatar

And in my views/index.html.erb:

  <%= image_tag contact.contact_avatar.attached? ? contact.contact_avatar : "100x100.png", class: "media-object img-thumbnail img-rounded mr-3" %>

Any idea what's causing this?

MORE INFO: Whenever I am trying to insert or upload a photo using ActiveStorage I am always having this on my terminal:

[ActiveJob] [ActiveStorage::AnalyzeJob] [875b372f-3647-4ba0-8beb-3fe38e8885d3]    (9.6ms)  COMMIT
[ActiveJob] [ActiveStorage::AnalyzeJob] [875b372f-3647-4ba0-8beb-3fe38e8885d3]   ↳ /Users/richard/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
[ActiveJob] [ActiveStorage::AnalyzeJob] [875b372f-3647-4ba0-8beb-3fe38e8885d3] Performed ActiveStorage::AnalyzeJob (Job ID: 875b372f-3647-4ba0-8beb-3fe38e8885d3) from Async(default) in 104.68ms
Started GET "/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBHQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--05a842304d7509391444fb7250f49645b77cff00/madman.png" for ::1 at 2020-05-29 13:13:19 +0800
Processing by ErrorsController#page_not_found as PNG
  Parameters: {"path"=>"rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBHQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--05a842304d7509391444fb7250f49645b77cff00/madman"}
  Rendering errors/404.html.erb within layouts/application
  Rendered errors/404.html.erb within layouts/application (0.8ms)

Here's the contact controller:

class ContactsController < ApplicationController
  before_action :set_contact, only: [:show, :edit, :update, :destroy]
  skip_before_action :verify_authenticity_token, only: [:destroy]
  before_action :authenticate_user!

  def index
    @contacts = current_user.contacts.order(created_at: :desc).page(params[:page])
    @contacts = @contacts.where(category_id: params[:category_id]) if params[:category_id].present?
    @contacts = @contacts.search(params[:term]) if params[:term].present?
  end

  def autocomplete
      @contacts = current_user.contacts.order(created_at: :desc).page(params[:page])
      @contacts = @contacts.where(category_id: params[:category_id]) if params[:category_id].present?
      @contacts = @contacts.search(params[:term]) if params[:term].present?
      render json: @contacts.map { |contact| { id: contact.id, value: contact.name }}
  end

  def show
  end

  def new
    @contact = Contact.new
  end

  def edit
    authorize @contact
  end

  def create
    @contact = current_user.contacts.build(contact_params)
    @success = @contact.save ? true : false

    respond_to do |format|
      if @success
        format.html { redirect_to contacts_path, notice: 'Contact was successfully created.' }
        format.js
      else
        format.js
      end
    end
  end

  def update
    @success = @contact.update(contact_params) ? true : false

    respond_to do |format|
      if @success
        format.html { redirect_to contacts_path, notice: 'Contact was successfully updated.' }
        format.js
      else
        format.js
      end
    end
  end

  def destroy
    authorize @contact
    @contact.destroy
    respond_to do |format|
      format.html { redirect_to contacts_url, notice: 'Contact was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_contact
      @contact = Contact.find(params[:id])
    end

    def contact_params
      params.require(:contact).permit(:name, :email, :mobile, :phone, :country, :address, :city, :state, :zip, :note, :category_id, :contact_avatar)
    end

    def has_error?(resource, field)
      resource.errors.messages[field].present?
    end

    def get_error(resource, field)
      msg = resource.errors.messages[field]
      field.to_s.capitalize + " " + msg.join(' and ') + '.'
    end

    helper_method :has_error?
    helper_method :get_error
end

Here's the storage.yml file:

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

# Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
# amazon:
#   service: S3
#   access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
#   secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
#   region: us-east-1
#   bucket: your_own_bucket

# Remember not to checkin your GCS keyfile to a repository
# google:
#   service: GCS
#   project: your_project
#   credentials: <%= Rails.root.join("path/to/gcs.keyfile") %>
#   bucket: your_own_bucket

# Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key)
# microsoft:
#   service: AzureStorage
#   storage_account_name: your_account_name
#   storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %>
#   container: your_container_name

# mirror:
#   service: Mirror
#   primary: local
#   mirrors: [ amazon, google, microsoft ]

Body:
Add these gems to the gemfile and run bundle

#Gemfile
gem 'image_processing'
gem 'mini_magick'

You can also need to run
sudo apt install imagemagick in your console afterwards.


问:
Call member function of non-active union member
Does calling foo in the following code leads to UB?

using vec = std::array<int, 1>;
struct field0 {
    vec data;
    operator int() {
        return data[0];
    }
};

union a {
    struct {
        vec data;
    } data;
    field0 x;
};

void foo() {
    a bar;
    std::cin >> bar.data.data[0];
    std::cout << bar.x;
}
```

According to standard, x and data have the same address, so it should be safe to cast this to vec*. Also, field0 and vec are layout-compatible, so it should be safe to inspect data via x.data or vice-versa.

However, we not just inspect x.data, we call non-static member function of x outside of it's lifetime (or do we? I can't find a reason why x lifetime should have started), so formally it's UB. Is it correct?

What I am trying to achieve is well-defined version of common approach to name array field like union a { int data[3]; int x, y, z};

UPD:

Sorry, during removing unnecessary details, layout compatibility between array field and "getter" was lost. Restored now.

I will need to use a values to function that takes int*, so going in other direction - declaring fields and overloading operator[] - is not an option.

答:
Your code has undefined behavior.  The initial common sequence rule wont help you here since you are not accessing a common member but instead you are accessing the entire object in order to call the member function1.

What I am trying to achieve is well-defined version of common approach to name array field like union a { int data[3]; int x, y, z};

The way to do this in C++ is to use a struct and operator overloading.  Instead of having an array and trying to map it to individual members, you have individual members and then pretend that your class is an array.  That looks like

```<code>struct vec
{
    int x, y, z;
    int& operator[](size_t index)
    {
        switch(index)
        {
        case 0: return x;
        case 1: return y;
        case 2: return z;
        }
    }
};
</code>```

1: to call a member function is to pass that object to that function as if it was the first parameter of the function.

Body:
Does calling foo in the following code leads to UB?

using vec = std::array<int, 1>;
struct field0 {
    vec data;
    operator int() {
        return data[0];
    }
};

union a {
    struct {
        vec data;
    } data;
    field0 x;
};

void foo() {
    a bar;
    std::cin >> bar.data.data[0];
    std::cout << bar.x;
}

According to standard, x and data have the same address, so it should be safe to cast this to vec*. Also, field0 and vec are layout-compatible, so it should be safe to inspect data via x.data or vice-versa.

However, we not just inspect x.data, we call non-static member function of x outside of it's lifetime (or do we? I can't find a reason why x lifetime should have started), so formally it's UB. Is it correct?

What I am trying to achieve is well-defined version of common approach to name array field like union a { int data[3]; int x, y, z};

UPD:

Sorry, during removing unnecessary details, layout compatibility between array field and "getter" was lost. Restored now.

I will need to use a values to function that takes int*, so going in other direction - declaring fields and overloading operator[] - is not an option.

Body:
Your code has undefined behavior.  The initial common sequence rule wont help you here since you are not accessing a common member but instead you are accessing the entire object in order to call the member function1.

What I am trying to achieve is well-defined version of common approach to name array field like union a { int data[3]; int x, y, z};

The way to do this in C++ is to use a struct and operator overloading.  Instead of having an array and trying to map it to individual members, you have individual members and then pretend that your class is an array.  That looks like

struct vec
{
    int x, y, z;
    int& operator[](size_t index)
    {
        switch(index)
        {
        case 0: return x;
        case 1: return y;
        case 2: return z;
        }
    }
};

1: to call a member function is to pass that object to that function as if it was the first parameter of the function.


问:
Why array_unique does not detect duplicate objects?
I can't seem to figure out what magic is happening behind the PHP scene and why array_unique cannot detect my duplicates.

In my specific situation, I have 2 collections of users, which I am merging into one and then keeping only unique entries. For that I am converting both collections into arrays, array_merge() them and then based on parameter apply array_unique(..., SORT_REGULAR) so that they are compared as objects without any conversions. I realise that comparing objects is a slippery slope, but in this case it's weirder than I though.

After merge but before the uniqueness check I have this state:

As you can see, items 4 and 11 are the same User entity (both non-strict and strict comparison agree on that). Yet after array_unique() they both remain in the list for some reason:

As you can see, items 7-10 were detected and removed, but 11 wasn't.

How is that possible? What am I not seeing here?

Currently running PHP 7.4.5

Code is from project using Symfony 4.4.7 and Doctrine ORM 2.7.2 (although I think this should be irrelevant, if the objects are equal both by == and === comparisons).

Fun fact for bonus points - applying array_unique twice in a row gives actually unique results:

Mind = blown

UPDATE: I have added throw new \RuntimeException() in my User::__toString() method, to be extra sure noone is doing conversion to string.

Please do not suggest converting to string - that is neither a solution to my problem, nor what this question is about.

答:
I know that you said that you don't want converting to string, but i see that you are yet no have way out, so i propose to you use the function serialize to each object in your array, i don't found a method to compare objects that isn't converting in array or string (you cant try convert in binary or hex if you don't unfamiliar with string or array, but i don't know if you can converting to binary or hex without to convert in string).

But, if you use serialize, you can serialize the object in a read data own of php, to you compare with anothers serialized objects, this method (serialize) is safe, because you can do aunserialize, and geting the original object again.

So you can serialize all elements from array and after this, you can use array_unique, like that:

<?php

header("Content-Type: application/json");

class MyClass
{
    public $var1;
    public $var2;
    function __construct($var1, $var2)
    {
        $this->var1 = $var1;
        $this->var2 = $var2;
    }

}

$arr = [
    "a",
    "a",
    [1,2,3],
    "b",
    [1,2,3],
    new MyClass(1,1),
    new MyClass(1,new MyClass(1,1)),
    new MyClass(1,new MyClass(1,1)),
];

$arrSerilized = array_map("serialize", $arr);

var_dump(
    array_map(
        "unserialize",
        array_unique(
            $arrSerilized,
            SORT_STRING
        )
    )
);

/* output:
array(5) {
    [0]=>
    string(1) "a"
    [2]=>
    array(3) {
        [0]=>
        int(1)
        [1]=>
        int(2)
        [2]=>
        int(3)
    }
    [3]=>
    string(1) "b"
    [5]=>
    object(MyClass)#6 (2) {
        ["var1"]=>
        int(1)
        ["var2"]=>
        int(1)
    }
    [6]=>
    object(MyClass)#7 (2) {
        ["var1"]=>
        int(1)
        ["var2"]=>
        object(MyClass)#8 (2) {
            ["var1"]=>
            int(1)
            ["var2"]=>
            int(1)
        }
    }
}
*/
```

Hope this help you man, have a good day!

P.S.: With serialize you can preserve same value in different variable type, like 1 and "1" are serialized in different read data of php

Body:
I know that you said that you don't want converting to string, but i see that you are yet no have way out, so i propose to you use the function serialize to each object in your array, i don't found a method to compare objects that isn't converting in array or string (you cant try convert in binary or hex if you don't unfamiliar with string or array, but i don't know if you can converting to binary or hex without to convert in string).

But, if you use serialize, you can serialize the object in a read data own of php, to you compare with anothers serialized objects, this method (serialize) is safe, because you can do aunserialize, and geting the original object again.

So you can serialize all elements from array and after this, you can use array_unique, like that:

<?php

header("Content-Type: application/json");

class MyClass
{
    public $var1;
    public $var2;
    function __construct($var1, $var2)
    {
        $this->var1 = $var1;
        $this->var2 = $var2;
    }

}

$arr = [
    "a",
    "a",
    [1,2,3],
    "b",
    [1,2,3],
    new MyClass(1,1),
    new MyClass(1,new MyClass(1,1)),
    new MyClass(1,new MyClass(1,1)),
];

$arrSerilized = array_map("serialize", $arr);

var_dump(
    array_map(
        "unserialize",
        array_unique(
            $arrSerilized,
            SORT_STRING
        )
    )
);

/* output:
array(5) {
    [0]=>
    string(1) "a"
    [2]=>
    array(3) {
        [0]=>
        int(1)
        [1]=>
        int(2)
        [2]=>
        int(3)
    }
    [3]=>
    string(1) "b"
    [5]=>
    object(MyClass)#6 (2) {
        ["var1"]=>
        int(1)
        ["var2"]=>
        int(1)
    }
    [6]=>
    object(MyClass)#7 (2) {
        ["var1"]=>
        int(1)
        ["var2"]=>
        object(MyClass)#8 (2) {
            ["var1"]=>
            int(1)
            ["var2"]=>
            int(1)
        }
    }
}
*/

Hope this help you man, have a good day!

P.S.: With serialize you can preserve same value in different variable type, like 1 and "1" are serialized in different read data of php


问:
window.location in a tabbed website
I'm dealing with a website that uses tabs. The outer tab, is facebook.com. The inner tab is a facebook application.

When I run the following function:

```<code> $(document).ready(function() {
    // to show it in an alert window
    alert(window.location);

    // to store it in a variable
    var loc = window.location;
});
</code>```

The returned value is the url of the inner tab, the host. Is there a way to produce the url of the outer tab using a JQuery function?

答:
Maybe you're looking for parent:

```<code>window.parent.location;
</code>```

Title: window.location in a tabbed website

Body:
I'm dealing with a website that uses tabs. The outer tab, is facebook.com. The inner tab is a facebook application.

When I run the following function:

 $(document).ready(function() {
    // to show it in an alert window
    alert(window.location);

    // to store it in a variable
    var loc = window.location;
});

The returned value is the url of the inner tab, the host. Is there a way to produce the url of the outer tab using a JQuery function?

Body:
Maybe you're looking for parent:

window.parent.location;


问:
How can i compare a variable (whose value was taken using combo box) of sqlite3 table to a variable (again taken value using combo box) in pyqt5?
In my PyQt5 GUI, I have created a table using SQLite3. The table has different column, one is 'semester' for which combo box is used to take input. I want to print out information of only those rows which have the same semester value as another user input (taken using a combo box). While taking input i wrote the code as following-

```<code>semester = self.semesterinput.itemText(self.semesterinput.currentIndex()) #used to take input
</code>```

Code portion for the query-

```<code>result = self.c.execute("SELECT row_number() OVER (ORDER BY reg_no) AS serial,reg_no,name,semester FROM socRecord WHERE semester = "+ str(name_of_semester))
</code>```

I am getting 'unrecognized token' error. How can i solve this?

答:
You do not have to concatenate since your code will be susceptible to SQL Injection in addition to generating other problems, instead you must use the placeholders:</p>

```<code>semester = self.semesterinput.currentText()
result = self.c.execute(
    "SELECT row_number() OVER (ORDER BY reg_no) AS serial,reg_no,name,semester FROM socRecord WHERE semester = ? ",
    (semester,),
)
</code>```

Body:
In my PyQt5 GUI, I have created a table using SQLite3. The table has different column, one is 'semester' for which combo box is used to take input. I want to print out information of only those rows which have the same semester value as another user input (taken using a combo box). While taking input i wrote the code as following-

semester = self.semesterinput.itemText(self.semesterinput.currentIndex()) #used to take input

Code portion for the query-

result = self.c.execute("SELECT row_number() OVER (ORDER BY reg_no) AS serial,reg_no,name,semester FROM socRecord WHERE semester = "+ str(name_of_semester))

I am getting 'unrecognized token' error. How can i solve this?

Body:
You do not have to concatenate since your code will be susceptible to SQL Injection in addition to generating other problems, instead you must use the placeholders:

semester = self.semesterinput.currentText()
result = self.c.execute(
    "SELECT row_number() OVER (ORDER BY reg_no) AS serial,reg_no,name,semester FROM socRecord WHERE semester = ? ",
    (semester,),
)


问:
Cannot install package via Miniconda: write permission
I made a silent installation of Miniconda as root and then added write permission to a regular user, that cannot install packages:

If I try - as regular user:

```<code>conda install -y -c bioconda covtobed
</code>```

I get this error:

```<code>EnvironmentNotWritableError: The current user does not have write permissions to the target environment.
  environment location: /virome/tools/Miniconda_Shared
  uid: 1982
  gid: 1982
</code>```

But the following commands work:

```<code>touch /virome/tools/Miniconda_Shared/test.write
touch /virome/tools/Miniconda_Shared/pkgs/test.write
rm /virome/tools/Miniconda_Shared/test.write /virome/tools/Miniconda_Shared/pkgs/test.write
</code>```

What should I check (in terms of permission) to fix this?

答:
Found here: https://docs.anaconda.com/anaconda/install/multi-user/</p>

```<code>sudo chgrp -R $SHAREDGROUP $PATHTOCONDA
sudo chmod 770 -R $PATHTOCONDA
</code>```

Body:
I made a silent installation of Miniconda as root and then added write permission to a regular user, that cannot install packages:

If I try - as regular user:

conda install -y -c bioconda covtobed

I get this error:

EnvironmentNotWritableError: The current user does not have write permissions to the target environment.
  environment location: /virome/tools/Miniconda_Shared
  uid: 1982
  gid: 1982

But the following commands work:

touch /virome/tools/Miniconda_Shared/test.write
touch /virome/tools/Miniconda_Shared/pkgs/test.write
rm /virome/tools/Miniconda_Shared/test.write /virome/tools/Miniconda_Shared/pkgs/test.write

What should I check (in terms of permission) to fix this?

Body:
Found here: https://docs.anaconda.com/anaconda/install/multi-user/

sudo chgrp -R $SHAREDGROUP $PATHTOCONDA
sudo chmod 770 -R $PATHTOCONDA


问:
How can I show specific texts inside a div by the click of a button?
I have a small text translated in 3 languages. I am looking to show the first text in English, and above the text to show two buttons, one that says French and one that says Italian. And I want once you click on French, to display the text in French, and the same with Italian. This means that I will have three separate divs, one for English, one for French and one for Italian. I only want to show one of them on the page, depending on which button I click. How can I do that? Thanks</p>

答:
    document.querySelector(".btn-eng").addEventListener('click', function () {
        document.querySelector(".eng").classList.add("active");
        document.querySelector(".french").classList.remove("active");
        document.querySelector(".italian").classList.remove("active");
    });
    document.querySelector(".btn-french").addEventListener('click', function () {
        document.querySelector(".french").classList.add("active");
        document.querySelector(".eng").classList.remove("active");
        document.querySelector(".italian").classList.remove("active");
    });
    document.querySelector(".btn-italian").addEventListener('click', function () {
        document.querySelector(".italian").classList.add("active");
        document.querySelector(".eng").classList.remove("active");
        document.querySelector(".french").classList.remove("active");
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
    font-size: 1rem;
 }
 .container {
              margin: auto;
              height: 100px;
              width: 250px;
 }
 .flex {
         display: flex;
         justify-content: center;
         align-items: center;
         flex-direction: column;
         height: 100%;
         width: 100%;
 }
 .eng,
 .french,
 .italian {
            display: none;
 }
 .active {
           display: block;
 }</code>```

Hello Developers out there!

Bonjour les développeurs là-bas!

Ciao sviluppatori là fuori!

                <button class="btn-eng">English</button>
                <button class="btn-french">French</button>
                <button class="btn-italian">Italian</button>

```

Body:
    document.querySelector(".btn-eng").addEventListener('click', function () {
        document.querySelector(".eng").classList.add("active");
        document.querySelector(".french").classList.remove("active");
        document.querySelector(".italian").classList.remove("active");
    });
    document.querySelector(".btn-french").addEventListener('click', function () {
        document.querySelector(".french").classList.add("active");
        document.querySelector(".eng").classList.remove("active");
        document.querySelector(".italian").classList.remove("active");
    });
    document.querySelector(".btn-italian").addEventListener('click', function () {
        document.querySelector(".italian").classList.add("active");
        document.querySelector(".eng").classList.remove("active");
        document.querySelector(".french").classList.remove("active");
    });

*{
    font-size: 1rem;
 }
 .container {
              margin: auto;
              height: 100px;
              width: 250px;
 }
 .flex {
         display: flex;
         justify-content: center;
         align-items: center;
         flex-direction: column;
         height: 100%;
         width: 100%;
 }
 .eng,
 .french,
 .italian {
            display: none;
 }
 .active {
           display: block;
 }

<div class="container">
        <div class="flex">
            <div class="section">
                <p class="eng active">Hello Developers out there!</p>
                <p class="french">Bonjour les développeurs là-bas!</p>
                <p class="italian">Ciao sviluppatori là fuori!</p>
            </div>
            <div class="button">
                <button class="btn-eng">English</button>
                <button class="btn-french">French</button>
                <button class="btn-italian">Italian</button>
            </div>
        </div>
</div>


答:
$.post only has one callback function. Try using $ instead as thats a lot more features.

http://api.jquery.com/jQuery.ajax/

Title: Assigning callbacks for a $.post call in jQuery


问:
Text Blink(when printing) in Python 2.7
I'm trying to get a text blink in python . I found this method:

```<code>from termcolor import colored, cprint
cprint('\nJames Everleigh', 'red', attrs=['blink'])
</code>```

but when i compile it i get some sort weird text:

```<code>""[5m[31m
James Everleigh[0m ""
</code>```

What do I need to use to get the desired output?

答:
if you are using windows powershell you need to
pip colorama and import init from colorama and run it like this:

```<code>from colorama import init
from termcolor import colored
init()
print(colored("text","red"))
</code>```

Title: Text Blink(when printing) in Python 2.7

Body:
I'm trying to get a text blink in python . I found this method:

from termcolor import colored, cprint
cprint('\nJames Everleigh', 'red', attrs=['blink'])

but when i compile it i get some sort weird text:

""[5m[31m
James Everleigh[0m ""

What do I need to use to get the desired output?

Body:
if you are using windows powershell you need to
pip colorama and import init from colorama and run it like this:

from colorama import init
from termcolor import colored
init()
print(colored("text","red"))


问:
Is it possible to set a "global" conditional breakpoint that is evaluated anywhere the condition is valid?
I am working with a C++ codebase that does not use exceptions, and the convention is that every function returns false on failure, such that a significant portion of the code looks like this:

```<code>bool compute_something(int& result) {
    bool ok = step1();
    ok = ok && step2();
    ok = ok && step3();
    ...
    ok = ok && stepN(result);
    return ok;
}
</code>```

When debugging an error, I would like to add a breakpoint whenever any variable named "ok" in the program becomes false, in order to find the exact moment the error occured.

I found this question, which is somewhat similar, but does not solve this problem (and it is gdb specific).

Can this be achieved in visual studio? Or any other environment for that matter, the answer might help someone else.

答:
Unfortunately, I am pretty sure you can't. There could be no breakpoints on variables by random names. You can place memory access breakpoint on a specific memory address, or you can use a variable name which is in scope in current sessions (which just puts the breakpoint on the address of said variable).

The reason for this is the fact that memory access breakpoints are done in hardware, and hardware has no notion of any names at all.

Body:
I am working with a C++ codebase that does not use exceptions, and the convention is that every function returns false on failure, such that a significant portion of the code looks like this:

bool compute_something(int& result) {
    bool ok = step1();
    ok = ok && step2();
    ok = ok && step3();
    ...
    ok = ok && stepN(result);
    return ok;
}

When debugging an error, I would like to add a breakpoint whenever any variable named "ok" in the program becomes false, in order to find the exact moment the error occured.

I found this question, which is somewhat similar, but does not solve this problem (and it is gdb specific).

Can this be achieved in visual studio? Or any other environment for that matter, the answer might help someone else.


问:
regex to add a limit of 10 digits with decimal value having no limit
I want to apply a validation where I need a limit of 10 digits on value but the value after decimal has no limit.

Like this
1000000000.2121
The value before decimal should be less than 10 digits.
I am trying this regex
^(10|\d)(\.\d{1,2})?$
 But By this, I only add decimal digits with a limit of two. How can I achieve this?

答:
You are stating two things (and not showing a lot of examples to work with):

"The value before decimal should be less than 10 digits"

"I need a limit of 10 digits on value but the value after decimal has no limit"

Which one is it? I went with the first assumption where there cannot be more than 9 digits but there must be at least one. Also for number validity I thought it would make sense to only start with a single zero or non at all:

```<code>^(?:0|[1-9]\d{0,8})(?:\.\d+)?$
</code>```

See Online Demo

^ - Start string ancor.

(?: - 1st Non-capture group.

0|[1-9]\d{0,8} - a single zero or a single digit between 1-9 followed by zero to 8 more digits to keep under 10 digits total.

) - Closing 1st non-capture group.

(?: - 2nd Non-capture group.

\.\d+ - A literal dot followed by one or more digits.

) - Close 2nd non-capture group.

? - Make 2nd non-capture group optional.

$ - End string ancor.

Note: This can be simplified if you allow numbers to start with a dot.

Body:
You are stating two things (and not showing a lot of examples to work with):

"The value before decimal should be less than 10 digits"

"I need a limit of 10 digits on value but the value after decimal has no limit"

Which one is it? I went with the first assumption where there cannot be more than 9 digits but there must be at least one. Also for number validity I thought it would make sense to only start with a single zero or non at all:

^(?:0|[1-9]\d{0,8})(?:\.\d+)?$

See Online Demo

^ - Start string ancor.

(?: - 1st Non-capture group.

0|[1-9]\d{0,8} - a single zero or a single digit between 1-9 followed by zero to 8 more digits to keep under 10 digits total.

) - Closing 1st non-capture group.

(?: - 2nd Non-capture group.

\.\d+ - A literal dot followed by one or more digits.

) - Close 2nd non-capture group.

? - Make 2nd non-capture group optional.

$ - End string ancor.

Note: This can be simplified if you allow numbers to start with a dot.


问:
touch screen clear status message on any touch
Iam working on a touch screen windows form that has many checkboxes, textboxes, listboxes, date dropdown pickers etc. Depending on user action a status message is displayed at the bottom. For eg., Your profile saved successfully, From and to date cannot be same, Please select a valid ... etc

What is an elegant way to clear the status message on ANY touch.

```<code>if (statusLabel.text != string.empty )
    statusLabel.text = string.empty)
</code>```

Meaning if any checkbox is checked, any text is input in a textbox, any listbox or combo is selected...then I want to clear the status label. This way the last status message does not "stick" to confuse the user. I am poking around to see if I can override some event at the form level in one place that will do this.

thanks

thx Saravanan and Pedery for your suggestions. They do not solve my problem. I just discovered Reactive extensions and posting a related question which may help me. Left mouse button click detect on winform using Reactive extensions IObservable on events

答:
You can put the message in the controls' Tag property and use a single common event to add them all up.

If you wanna be more orderly, you can subclass the checkbox with a custom property the same way.

Body:
Iam working on a touch screen windows form that has many checkboxes, textboxes, listboxes, date dropdown pickers etc. Depending on user action a status message is displayed at the bottom. For eg., Your profile saved successfully, From and to date cannot be same, Please select a valid ... etc

What is an elegant way to clear the status message on ANY touch.

if (statusLabel.text != string.empty )
    statusLabel.text = string.empty)

Meaning if any checkbox is checked, any text is input in a textbox, any listbox or combo is selected...then I want to clear the status label. This way the last status message does not "stick" to confuse the user. I am poking around to see if I can override some event at the form level in one place that will do this.

thanks

thx Saravanan and Pedery for your suggestions. They do not solve my problem. I just discovered Reactive extensions and posting a related question which may help me. Left mouse button click detect on winform using Reactive extensions IObservable on events


问:
How to move the scaled point and keep the shape of the curve?
For a curve, I wanna move the start and end point to new position, and then how to keep the shape of the curve ?

From the points which circulated on the yellow curve, move them to red curve position which circulated on the red curve, how to keep the shape of the curve on the red curve ?

答: When you define spline curve you need to define also tangents angles at endpoints, when you move you points to center, you are chenging the slopes of side lines, so if tangent angles are fixed wrt lines, they will make curve change. If you will see carefully corner angles are same on both images. To keep your curves shape you need to change these angles according side lines slope chenges.</p>


问:
Get headers feign netflix
I'm using netflix feign to communicate microservices.

So my Microservice A has an operation 'OperationA' which is consumed by the Microservice B and it passes one param by header named X-Total to B

```<code> MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
 headers.add("X-Total", page.getTotalSize());
</code>```

My client interface is as next:

```<code>@Headers({
    "Content-Type: " + MediaType.APPLICATION_JSON_UTF8_VALUE
})
@RequestLine("GET Dto/")
List<Dto> search();

static DtoClient connect() {
    return Feign.builder()
        .encoder(new GsonEncoder())
        .decoder(new GsonDecoder())
        .target(ConditionTypeClient.class, Urls.SERVICE_URL.toString());
}
</code>```

Then I've get the list of dto, but I don't know how to get the header X-TOTAL param:

```<code>public List<Dto> search() {
    DtoClient client = DtoClient.connect();
    return client.search();
}
</code>```

How do I get the header params?

答:
I'm getting late to the party, but I know for someone in the future it could help

We can wrap our response into a ResponseEntity<SomePojo>, by doing that we can access as the headers object as the body with type SomePojo.

```<code>...
import org.springframework.http.ResponseEntity;
...

public ResponseEntity<List<Dto>> search() {
    DtoClient client = DtoClient.connect();
    return client.search();
}
</code>```

Title: Get headers feign netflix

Body:
I'm using netflix feign to communicate microservices.

So my Microservice A has an operation 'OperationA' which is consumed by the Microservice B and it passes one param by header named X-Total to B

 MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
 headers.add("X-Total", page.getTotalSize());

My client interface is as next:

@Headers({
    "Content-Type: " + MediaType.APPLICATION_JSON_UTF8_VALUE
})
@RequestLine("GET Dto/")
List<Dto> search();

static DtoClient connect() {
    return Feign.builder()
        .encoder(new GsonEncoder())
        .decoder(new GsonDecoder())
        .target(ConditionTypeClient.class, Urls.SERVICE_URL.toString());
}

Then I've get the list of dto, but I don't know how to get the header X-TOTAL param:

public List<Dto> search() {
    DtoClient client = DtoClient.connect();
    return client.search();
}

How do I get the header params?

Body:
I'm getting late to the party, but I know for someone in the future it could help

We can wrap our response into a ResponseEntity<SomePojo>, by doing that we can access as the headers object as the body with type SomePojo.

...
import org.springframework.http.ResponseEntity;
...

public ResponseEntity<List<Dto>> search() {
    DtoClient client = DtoClient.connect();
    return client.search();
}


问:
How to POST using HTTPclient content type = application/x-www-form-urlencoded
I am currently developing a wp8.1 application C#, i have managed to perform a POST method in json to my api by creating a json object (bm) from textbox.texts.
here is my code below. How do i take the same textbox.text and POST them as a content type = application/x-www-form-urlencoded. whats the code for that?

```<code>Profile bm = new Profile();
bm.first_name = Names.Text;
bm.surname = surname.Text;

string json = JsonConvert.SerializeObject(bm);

MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty
await messageDialog.ShowAsync();

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

byte[] messageBytes = Encoding.UTF8.GetBytes(json);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync("myapiurl", content).Result;
</code>```

答:
The best solution for me is:</p>

```<code>// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");

// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}
</code>```

Body:
I am currently developing a wp8.1 application C#, i have managed to perform a POST method in json to my api by creating a json object (bm) from textbox.texts.
here is my code below. How do i take the same textbox.text and POST them as a content type = application/x-www-form-urlencoded. whats the code for that?

Profile bm = new Profile();
bm.first_name = Names.Text;
bm.surname = surname.Text;

string json = JsonConvert.SerializeObject(bm);

MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty
await messageDialog.ShowAsync();

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

byte[] messageBytes = Encoding.UTF8.GetBytes(json);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync("myapiurl", content).Result;

Body:
The best solution for me is:

// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");

// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}


问:
Destructor called in method that pass value to variable
I am creating pseudo std::vector. I want to be able to declare variable Matrix B and after that assign value to it, passed by another Matrix variable.
Matrix have constructor, that allocate memo

```<code>Vect(int size, char name) : name(name), size(size), store(new int[size]){}
</code>```

and destructor that deletes it on end of var lifecycle

```<code>~Vect(){
  std::cout << "memo located: " << name << std::endl;
  delete[] store;
}
</code>```

Unfortunatelly, the method that used to return value returns it with destructor called

```<code>  Vect operator- (){
    Vect b(size,'C');
    for (int i = 0; i < size; i++){
      b.store[i] = -store[i];
    }
    return b; // <- here it calls destructor!!!
  }
</code>```

I try to do this:

```<code>  Vect m2;
  Vect m1 = Vect(10, 'A');
  m2 = -m1;
</code>```

And I get this error:

```<code>memo located: C
-1, -2, -3, -4, -5, -6, -7, -8, -9, -10,
memo located: A
memo located: C
a.out(46158,0x109e71dc0) malloc: *** error for object 0x7f9162401850: pointer being freed was not allocated
a.out(46158,0x109e71dc0) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6
</code>```

How can I walk around it with functionality saved?
My code:

```<code>#include <iostream>

class Vect {
  int *store;
  int size = 0;
  char name;

  public:
  Vect operator- (){
    Vect b(size,'C');
    for (int i = 0; i < size; i++){
      b.store[i] = -store[i];
    }
    return b;
  }

  int *getPointer(){
    return store;
  }
  int getSize(){
    return size;
  }

  bool set(int i, int v){
    if (i >= size)
      return false;
    store[i] = v;
    return true;
  }

  Vect(){}
  Vect(int size, char name) : name(name), size(size), store(new int[size]){}
  ~Vect(){
    std::cout << "memo located: " << name << std::endl;
    delete[] store;
    }
};

int main(int argc, char **argv){
  Vect m2;
  Vect m1 = Vect(10, 'A');

  int i = 0;
  while(m1.set(i++, i));

  m2 = -m1;
  int size = m2.getSize(), *ptr = m2.getPointer();
  for (int i = 0; i < size; i++){
    std::cout << ptr[i] << ", ";
  }
  std::cout << std::endl;
  return 0;
}
</code>```

答:
I believe you want to implement "copy-and-swap idiom". You need to swap the data from b (temp object) into your object, then the temporary one is safely destroyed.

Demo: https://wandbox.org/permlink/BMccSpz03cpGuG6S

Body:
I am creating pseudo std::vector. I want to be able to declare variable Matrix B and after that assign value to it, passed by another Matrix variable.
Matrix have constructor, that allocate memo

Vect(int size, char name) : name(name), size(size), store(new int[size]){}

and destructor that deletes it on end of var lifecycle

~Vect(){
  std::cout << "memo located: " << name << std::endl;
  delete[] store;
}

Unfortunatelly, the method that used to return value returns it with destructor called

  Vect operator- (){
    Vect b(size,'C');
    for (int i = 0; i < size; i++){
      b.store[i] = -store[i];
    }
    return b; // <- here it calls destructor!!!
  }

I try to do this:

  Vect m2;
  Vect m1 = Vect(10, 'A');
  m2 = -m1;

And I get this error:

memo located: C
-1, -2, -3, -4, -5, -6, -7, -8, -9, -10,
memo located: A
memo located: C
a.out(46158,0x109e71dc0) malloc: *** error for object 0x7f9162401850: pointer being freed was not allocated
a.out(46158,0x109e71dc0) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6

How can I walk around it with functionality saved?
My code:

#include <iostream>

class Vect {
  int *store;
  int size = 0;
  char name;

  public:
  Vect operator- (){
    Vect b(size,'C');
    for (int i = 0; i < size; i++){
      b.store[i] = -store[i];
    }
    return b;
  }

  int *getPointer(){
    return store;
  }
  int getSize(){
    return size;
  }

  bool set(int i, int v){
    if (i >= size)
      return false;
    store[i] = v;
    return true;
  }

  Vect(){}
  Vect(int size, char name) : name(name), size(size), store(new int[size]){}
  ~Vect(){
    std::cout << "memo located: " << name << std::endl;
    delete[] store;
    }
};

int main(int argc, char **argv){
  Vect m2;
  Vect m1 = Vect(10, 'A');

  int i = 0;
  while(m1.set(i++, i));

  m2 = -m1;
  int size = m2.getSize(), *ptr = m2.getPointer();
  for (int i = 0; i < size; i++){
    std::cout << ptr[i] << ", ";
  }
  std::cout << std::endl;
  return 0;
}


问:
array.contains firebase reference object
I don't know why array.conatins() return false when object which I checked is in my array.. This is array of references from firebase.

```<code>    if(props.event){
        const userRef = firebase.firestore().collection('uzytkownik').doc(currentUser);
        console.log(props.event.uczestnicy.includes(userRef))
        console.log("userRef", userRef)
        console.log("uczestnicy[2]", props.event.uczestnicy[2])
    }
</code>```

答: You can't use normal JavaScript equality to compare if two DocumentReference objects are not "equal" to each other.  What you could do instead is use the isEqual() method to compare two references.  (JavaScript arrays don't know to use this method to check for equality.)</p>

Body:
I don't know why array.conatins() return false when object which I checked is in my array.. This is array of references from firebase.

    if(props.event){
        const userRef = firebase.firestore().collection('uzytkownik').doc(currentUser);
        console.log(props.event.uczestnicy.includes(userRef))
        console.log("userRef", userRef)
        console.log("uczestnicy[2]", props.event.uczestnicy[2])
    }


问:
change color when button is pressed and deselect other options
I have 5 options that I wrapped with touchableopacity. I'd like that when one options is clicked that the color turns green. If i click another option then the previous option goes grey and the new option is green. Can someone please help me code this out? I don't want to write a bunch of IF statements. I feel its bad code and there is a faster way of getting to my goal. Don't mind the Alert function there I only had that when i initially setup the touchableopacity. </p>

```<code>const [angryColor, setAngryColor] = useState('grey')
    const [sadColor, setEmojiSad] = useState('grey')
    const [neutral, setNuetral] = useState('grey')
    const [happyColor, setHappyColor] = useState('grey')
    const [laughColor, setLaugh] = useState('grey')

 function toggleAngry(){
     if (angryColor === 'grey'){
         setAngryColor('green')
     } else {
         setAngryColor('grey')
     }
    }

    return(
        <View style={styles.screen}>
            <View style={styles.container}>
                <View style={styles.emojiView}>
                    <TouchableOpacity onPress={() => toggleAngry()}>
                        <FontAwesome5 name="angry" size={40} color={angryColor}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <Entypo name="emoji-sad" size={40} color={sadColor}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <Entypo name="emoji-neutral" size={40} color={neutral} />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <Entypo name="emoji-happy" size={40} color={happyColor}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <FontAwesome5 name="laugh-beam" size={40} color={laughColor} />
                    </TouchableOpacity>
                </View>
</code>```

答:
You can set a single variable and set the colour based on that. There is no need for multiple states. I added a callback function which can be used by the parent component to get this update.</p>

```<code>const EmojiInput = (props) => {
  const [selected, setSelected] = React.useState(0);

  const onItemSelected=emoji=>{
    setSelected(emoji);
    if(props.callback){
      props.callback(emoji);
    }
  };

  return (
    <View style={styles.emojiView}>
      <TouchableOpacity onPress={() => onItemSelected(1)}>
        <FontAwesome5 name="angry" size={40} color={selected==1?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(2)}>
        <Entypo name="emoji-sad" size={40} color={selected==2?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(3)}>
        <Entypo name="emoji-neutral" size={40} color={selected==3?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(4)}>
        <Entypo name="emoji-happy" size={40} color={selected==4?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(5)}>
        <FontAwesome5 name="laugh-beam" size={40} color={selected==5?'red':'grey'} />
      </TouchableOpacity>
    </View>
  );
};
</code>```

Body:
I have 5 options that I wrapped with touchableopacity. I'd like that when one options is clicked that the color turns green. If i click another option then the previous option goes grey and the new option is green. Can someone please help me code this out? I don't want to write a bunch of IF statements. I feel its bad code and there is a faster way of getting to my goal. Don't mind the Alert function there I only had that when i initially setup the touchableopacity.

const [angryColor, setAngryColor] = useState('grey')
    const [sadColor, setEmojiSad] = useState('grey')
    const [neutral, setNuetral] = useState('grey')
    const [happyColor, setHappyColor] = useState('grey')
    const [laughColor, setLaugh] = useState('grey')

 function toggleAngry(){
     if (angryColor === 'grey'){
         setAngryColor('green')
     } else {
         setAngryColor('grey')
     }
    }

    return(
        <View style={styles.screen}>
            <View style={styles.container}>
                <View style={styles.emojiView}>
                    <TouchableOpacity onPress={() => toggleAngry()}>
                        <FontAwesome5 name="angry" size={40} color={angryColor}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <Entypo name="emoji-sad" size={40} color={sadColor}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <Entypo name="emoji-neutral" size={40} color={neutral} />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <Entypo name="emoji-happy" size={40} color={happyColor}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <FontAwesome5 name="laugh-beam" size={40} color={laughColor} />
                    </TouchableOpacity>
                </View>

Body:
You can set a single variable and set the colour based on that. There is no need for multiple states. I added a callback function which can be used by the parent component to get this update.

const EmojiInput = (props) => {
  const [selected, setSelected] = React.useState(0);

  const onItemSelected=emoji=>{
    setSelected(emoji);
    if(props.callback){
      props.callback(emoji);
    }
  };

  return (
    <View style={styles.emojiView}>
      <TouchableOpacity onPress={() => onItemSelected(1)}>
        <FontAwesome5 name="angry" size={40} color={selected==1?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(2)}>
        <Entypo name="emoji-sad" size={40} color={selected==2?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(3)}>
        <Entypo name="emoji-neutral" size={40} color={selected==3?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(4)}>
        <Entypo name="emoji-happy" size={40} color={selected==4?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(5)}>
        <FontAwesome5 name="laugh-beam" size={40} color={selected==5?'red':'grey'} />
      </TouchableOpacity>
    </View>
  );
};


问:
Can't access images in S3 bucket using cognito identity
I'm testing to display images from an s3 bucket using javascript, prior to making this part of an application.

I have an s3 bucket (non-public), named for this post:  IMAGE-BUCKET
Created an identity role : GET-IMAGE.
I have temporarily given full s3 access to GET-IMAGE role.
I have CORS defined for the bucket.
While testing I have disabled the browser cache.

3 issues:

Getting "403 Forbidden" response when images are accessed from the
html/script below.

If I make a particular image public, that image displays -- an issue with large # of images.

If I make the entire bucket public, images do not display

It seems Cognito identiy is not able to access the bucket, or there's an issue in the script below.

Also, setting the bucket public doesn't work either, unless each image is also set public. This bucket will be used privately, so this is only an issue while troubleshooting.

I have attached AmazonS3FullAccess to GET-IMAGE, I  also added the following policy:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AccessS3BucketIMAGEBUCKET",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
</code>```

Using html and script from AWS documentation (modified):

Photo Album Viewer

    <button onclick="viewAlbum('');">View All Images</button>

```
</div>
</div>
</p>

<p>UPDATE:
If I grant public read in S3 Bucket Policy:</p>

```{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::IMAGE-BUCKET/*"
        }
    ]
}
```

<p>It allows to access each image; solving the issue #2 and #3.
But this makes the bucket basically public.</p>

<p>If I change the Bucket policy to limit to the Cognito identity, changing the principal as follows, again I am not able to access images via the html/script, getting 403 errors.</p>

```"Principal": {
    "AWS": "arn:aws:iam::547299998870:role/Cognito_GET-IMAGEIDUnauth_Role"
}
```

<p>UPDATE:
I've been reading online, checking some of the other related posts ...
I've it reduced to the basic components, here's the latest configuration. The configuration should be as simple as, giving access to the GET-IMAGE role based on the documentation:</p>

<p>Under IAM Management Console > Roles > GET-IMAGE role (unauthenticated)
I added an inline policy:</p>

```        {
        "Sid": "VisualEditor2",
        "Effect": "Allow",
        "Action": ["s3:GetObject","s3:ListBucket"],
        "Resource": "arn:aws:s3:::IMAGE-BUCKET/*"
        }
```

I removed the Bucket policy -- this shouldn't be needed, the GET-IMAGE role already has access. Role trust is already included by default.  HTML contains the credential:
IdentityPoolId: 'us-east-1:9bfadd6a-xxxx-41d4-xxxx-79ad7347xxa1

Those are the most basic components, nothing else should be needed. However, it does not work.  I made 1 of the images public and that image is displayed, other images error with 403 Forbidden.

答:
You are not defining the trust policy for your unauthenticated role correctly.

As per this documentation on cognito role trust and permissions, the trust policy for an unauthenticated role can be defined as follows:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "cognito-identity.amazonaws.com:aud": "YOUR_IDENTITY_POOL_ID"
        },
        "ForAnyValue:StringLike": {
          "cognito-identity.amazonaws.com:amr": "unauthenticated"
        }
      }
    }
  ]
}
</code>```

When you use AWS.CognitoIdentityCredentials, under the hood your Cognito Identity Pool will first get a web identity id for your user. As you don't provide a login with an authenticated token from an identity provider such as Cognito User Pools, or Facebook, the id is for an unauthorized web identity.

Cognito will then call the security token service's assumeRoleWithWebIdentity method on your behalf in order to get credentials with the permissions that you defined in the unauthenticated role's access policy that will allow the web identity to access the s3 bucket.

This is why the principal in the trust policy needs to be cognito-identity.amazonaws.com. It is to give cognito identity pools the permission to call the sts:AssumeRoleWithWebIdentity method on behalf of the web identity in order to obtain IAM credentials.

The access policy part of the role, which defines what unauthenticated users can actually do, will continue to be as you originally defined it in your post:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AccessS3BucketIMAGEBUCKET",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:ListBucket"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}
</code>```

Update

I notice that the last inline policy you have posted for your unauthenticated role won't work for s3.listObjects(). It will return a 403 because it needs a slightly different resource statement to indicate the bucket itself, rather than the buckets content.

You can update your policy as follows:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject"
      ],
      "Resource": [
        "arn:aws:s3:::IMAGE-BUCKET/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::IMAGE-BUCKET"
      ]
    }
  ]
}
</code>```

Body:
I'm testing to display images from an s3 bucket using javascript, prior to making this part of an application.

I have an s3 bucket (non-public), named for this post:  IMAGE-BUCKET
Created an identity role : GET-IMAGE.
I have temporarily given full s3 access to GET-IMAGE role.
I have CORS defined for the bucket.
While testing I have disabled the browser cache.

3 issues:

Getting "403 Forbidden" response when images are accessed from the
html/script below.

If I make a particular image public, that image displays -- an issue with large # of images.

If I make the entire bucket public, images do not display

It seems Cognito identiy is not able to access the bucket, or there's an issue in the script below.

Also, setting the bucket public doesn't work either, unless each image is also set public. This bucket will be used privately, so this is only an issue while troubleshooting.

I have attached AmazonS3FullAccess to GET-IMAGE, I  also added the following policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AccessS3BucketIMAGEBUCKET",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

Using html and script from AWS documentation (modified):

Photo Album Viewer

    <button onclick="viewAlbum('');">View All Images</button>

UPDATE:
If I grant public read in S3 Bucket Policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::IMAGE-BUCKET/*"
        }
    ]
}

It allows to access each image; solving the issue #2 and #3.
But this makes the bucket basically public.

If I change the Bucket policy to limit to the Cognito identity, changing the principal as follows, again I am not able to access images via the html/script, getting 403 errors.

"Principal": {
    "AWS": "arn:aws:iam::547299998870:role/Cognito_GET-IMAGEIDUnauth_Role"
}

UPDATE:
I've been reading online, checking some of the other related posts ...
I've it reduced to the basic components, here's the latest configuration. The configuration should be as simple as, giving access to the GET-IMAGE role based on the documentation:

Under IAM Management Console > Roles > GET-IMAGE role (unauthenticated)
I added an inline policy:

        {
        "Sid": "VisualEditor2",
        "Effect": "Allow",
        "Action": ["s3:GetObject","s3:ListBucket"],
        "Resource": "arn:aws:s3:::IMAGE-BUCKET/*"
        }

I removed the Bucket policy -- this shouldn't be needed, the GET-IMAGE role already has access. Role trust is already included by default.  HTML contains the credential:
IdentityPoolId: 'us-east-1:9bfadd6a-xxxx-41d4-xxxx-79ad7347xxa1

Those are the most basic components, nothing else should be needed. However, it does not work.  I made 1 of the images public and that image is displayed, other images error with 403 Forbidden.

Body:
You are not defining the trust policy for your unauthenticated role correctly.

As per this documentation on cognito role trust and permissions, the trust policy for an unauthenticated role can be defined as follows:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "cognito-identity.amazonaws.com:aud": "YOUR_IDENTITY_POOL_ID"
        },
        "ForAnyValue:StringLike": {
          "cognito-identity.amazonaws.com:amr": "unauthenticated"
        }
      }
    }
  ]
}

When you use AWS.CognitoIdentityCredentials, under the hood your Cognito Identity Pool will first get a web identity id for your user. As you don't provide a login with an authenticated token from an identity provider such as Cognito User Pools, or Facebook, the id is for an unauthorized web identity.

Cognito will then call the security token service's assumeRoleWithWebIdentity method on your behalf in order to get credentials with the permissions that you defined in the unauthenticated role's access policy that will allow the web identity to access the s3 bucket.

This is why the principal in the trust policy needs to be cognito-identity.amazonaws.com. It is to give cognito identity pools the permission to call the sts:AssumeRoleWithWebIdentity method on behalf of the web identity in order to obtain IAM credentials.

The access policy part of the role, which defines what unauthenticated users can actually do, will continue to be as you originally defined it in your post:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AccessS3BucketIMAGEBUCKET",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:ListBucket"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}

Update

I notice that the last inline policy you have posted for your unauthenticated role won't work for s3.listObjects(). It will return a 403 because it needs a slightly different resource statement to indicate the bucket itself, rather than the buckets content.

You can update your policy as follows:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject"
      ],
      "Resource": [
        "arn:aws:s3:::IMAGE-BUCKET/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::IMAGE-BUCKET"
      ]
    }
  ]
}


问:
Share Image Via URL
I am creating Images app from my WordPress website with json and i am using swift, i want to share image on Social Networks from my app , currently i tried this code it works but only with image name i want to share image from image url, is that possible ?

this is my code

```<code> let myWebsite = NSURL(string: "nice")

           let img: UIImage = UIImage(named:"splash")!

           guard let url = myWebsite else {
               print("nothing found")
               return
           }

           let shareItems:Array = [img,url]
           let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
        activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToVimeo]
        self!.present(activityViewController, animated: true, completion: nil)
</code>```

答:
If you need to download an image and then share you should do that separately, there is no single method that does that for you. Here is how:

func shareImageFromUrl(_ string: String) {

    guard let myUrl = URL(string: string) else {
        print("Invalid url!")
        return
    }

    URLSession.shared.dataTask(with: myUrl) { (data, _, _) in
        guard let data = data,
            let image = UIImage(data: data) else
        { return }

        let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
        activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToVimeo]
        DispatchQueue.main.async {
            self.present(activityViewController, animated: true, completion: nil)
        }
    }.resume()
}
```

Title: Share Image Via URL

Body:
I am creating Images app from my WordPress website with json and i am using swift, i want to share image on Social Networks from my app , currently i tried this code it works but only with image name i want to share image from image url, is that possible ?

this is my code

 let myWebsite = NSURL(string: "nice")

           let img: UIImage = UIImage(named:"splash")!

           guard let url = myWebsite else {
               print("nothing found")
               return
           }

           let shareItems:Array = [img,url]
           let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
        activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToVimeo]
        self!.present(activityViewController, animated: true, completion: nil)


问:
Group row id for all unique rows in SQL Server
I would like to generate group row id for each unique rows. Any hint or suggestion would be helpful. I am using SQL Server 2017.

答:
You can use the windowed function ROW_NUMBER() as shown below:

```<code>Select col1
, col2
, ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col1, col2) [Group ID]
from <YourTableName>
</code>```

Db<>Fiddle Demo

Body:
You can use the windowed function ROW_NUMBER() as shown below:

Select col1
, col2
, ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col1, col2) [Group ID]
from <YourTableName>

Db<>Fiddle Demo


问:
Promise.resolve() inside click handler
I'm trying to make some decorators for some event handlers: a few simple functions that take a handler A as parameter and return a function B that do some stuff and then call A(...arguments).

There is a decorator in particular that I would like to build, it should fire the handler passed as parameter, after all the other handlers. But I noticed that the handling of clicks is different if the event is triggered programmatically rather then manually.

This is particularly evident in case of  bla tag, with an async handler on the click event, that waits for the next thread to finish its execution (ie at some point has await Promise.resolve()).

for example given this code

click

```

during the 10 second timeout I can click anytime I want on the link: the page is not reloaded because the e.preventDefault() statement will prevent the link to be loaded even if there is an await Promise.resolve().

But when setTimeout fires its click function (programmatically), the page starts to reload itself as soon as the program awaits for the await Promise.resolve(). The function continues its execution after the awaiting (you can see the 'done' string printed on the console if you have the persistent log active), but the page is reloaded anyway.

I wonder why this behaviour is different.

This is also noticeable on input type submit.

EDIT

With the debugger I noticed that the script follows a different path when the click is triggered manually instead of via js: when triggered manually, the handler doesn't await for the Promise to be resolved, so the second handler is triggered after the first (as if the Promise.resolve() where ignored). When triggered via js, the handler awaits for the promise, so the second handler added is triggered before the first.

答: The difference is that in the setTimeout case you you are calling preventDefault() in an async callback that has an await-ed Promise in it. When you await the Promise, the event completes and thereafter it is no longer possible to intercept it with preventDefault().

Title: Promise.resolve() inside click handler

Body:
I'm trying to make some decorators for some event handlers: a few simple functions that take a handler A as parameter and return a function B that do some stuff and then call A(...arguments).

There is a decorator in particular that I would like to build, it should fire the handler passed as parameter, after all the other handlers. But I noticed that the handling of clicks is different if the event is triggered programmatically rather then manually.

This is particularly evident in case of  bla tag, with an async handler on the click event, that waits for the next thread to finish its execution (ie at some point has await Promise.resolve()).

for example given this code

click

during the 10 second timeout I can click anytime I want on the link: the page is not reloaded because the e.preventDefault() statement will prevent the link to be loaded even if there is an await Promise.resolve().

But when setTimeout fires its click function (programmatically), the page starts to reload itself as soon as the program awaits for the await Promise.resolve(). The function continues its execution after the awaiting (you can see the 'done' string printed on the console if you have the persistent log active), but the page is reloaded anyway.

I wonder why this behaviour is different.

This is also noticeable on input type submit.

EDIT

With the debugger I noticed that the script follows a different path when the click is triggered manually instead of via js: when triggered manually, the handler doesn't await for the Promise to be resolved, so the second handler is triggered after the first (as if the Promise.resolve() where ignored). When triggered via js, the handler awaits for the promise, so the second handler added is triggered before the first.


问:
Grakn data validation and updating schema
So I'm using Grakn and wanted to know how Grakn handles existing schema updates.

If I have this schema:

```<code>person sub entity, has name;
</code>```

and I want to extend it with:

```<code>person sub entity, has name, has age;
</code>```

How is this done in Grakn if there's already data present? Do I need to be careful to migrate my data when I extend my schema?

答:
Extending a schema (ie - define new functionality) is always allowed, as long as the new schema components all satisfy the standard schema validation.

Using undefine, is more tricky, for instance, because you cannot undefine schema types that still have instances in the data. Attempting to do so will throw an exception.

There's a third class of operations where using define can mutate a schema, such as modifying a key to be a has or a has to be a key. However, many of these operations are tricky and will throw exceptions if not very careful.

Body:
So I'm using Grakn and wanted to know how Grakn handles existing schema updates.

If I have this schema:

person sub entity, has name;

and I want to extend it with:

person sub entity, has name, has age;

How is this done in Grakn if there's already data present? Do I need to be careful to migrate my data when I extend my schema?


问:
Is there a shortcut for switching between panels in eclipse?
Eclipse has an MDI structure (Multi Document Interface), so the search panel, the package explorer and the code editor can all be open in one window, but I haven't found a keyboard shortcut for switching between these panels. For example, after I search the code-base, I would love to have a quick shortcut for going back to the code editor.</p>

答:
Not an universal shortcut for going to any panel, but:

Ctrl+Shift+E

allows you to go back to any Editor (although it's still a little heavyweight for quick editor navigation).


问:
How to display different column data as tool tip in ag grid pivot mode?
```<code>var ColDef = [{
    headerName: "colA",
    field: 'colA',
    rowGroup: true
  },
  {
    headerName: "colB",
    field: 'colB',
    pivot: true,
    enablePivot: true
  },
  {
    headerName: "colC",
    field: 'colC',
    rowGroup: true
  },
  {
    field: 'colD',
    aggFunc: 'first',
    valueFormatter: currencyFormatter,
    tooltip: function(params) {
      return (params.valueFormatted);
    },
  },
  {
    field: 'comment'
  },
  {
    field: 'colF'
  }
];
function currencyFormatter(params) {
  return params.value;
}
</code>```

<p>above code is from different question. it works but i want to use different 'comment' field as tool tip to current 'colD' . also this is a group and pivot agGrid,if it is normal grid this is not a problem. I would appreciate any ideas for group and pivot agGrid? </p>

答:
just use tooltipValueGetter

```<code>{
   field: 'message',
   headerName: 'Message',
   headerTooltip: 'Message',
   width: 110,
   filter: 'agSetColumnFilter',
   tooltipValueGetter: (params) =>  `${params.value} some text`
}
</code>```

or just use the same method for tooltipValueGetter

UPDATE:

Okay, I understood

but it also easy

Ag-grid has property tooltipField - where you can choose any field from grid

For example here - in the column of 'sport' I am showing tooltip of the previous column

Example: https://plnkr.co/edit/zNbMPT5HOB9yqI08

OR

You can easily manipulate with data for each field by tooltipValueGetter
with next construction:

```<code>tooltipValueGetter: function(params) {
  return `Country: ${params.data.country}, Athlete: ${params.data.athlete}, Sport: ${params.data.sport}`;
},
</code>```

Example: https://plnkr.co/edit/zNbMPT5HOB9yqI08

Result:

UPDATE 2

Hey Man! I do not understand was is wrong

I just used  your code snippet and my solution

And it works as you want

Example: https://plnkr.co/edit/zNbMPT5HOB9yqI08

UPDATE 3

A little bit of manipulation and I can get the data

```<code>{ field: 'gold', aggFunc: 'sum',
    tooltipValueGetter: function(params) {
    var model = params.api.getDisplayedRowAtIndex(params.rowIndex);
    return model.allLeafChildren[0].data.silver;
  },
},
</code>```

The Last:
https://plnkr.co/edit/9qtYjkngKJg6Ihwb?preview

Body:
var ColDef = [{
    headerName: "colA",
    field: 'colA',
    rowGroup: true
  },
  {
    headerName: "colB",
    field: 'colB',
    pivot: true,
    enablePivot: true
  },
  {
    headerName: "colC",
    field: 'colC',
    rowGroup: true
  },
  {
    field: 'colD',
    aggFunc: 'first',
    valueFormatter: currencyFormatter,
    tooltip: function(params) {
      return (params.valueFormatted);
    },
  },
  {
    field: 'comment'
  },
  {
    field: 'colF'
  }
];
function currencyFormatter(params) {
  return params.value;
}

above code is from different question. it works but i want to use different 'comment' field as tool tip to current 'colD' . also this is a group and pivot agGrid,if it is normal grid this is not a problem. I would appreciate any ideas for group and pivot agGrid?

Body:
just use tooltipValueGetter

{
   field: 'message',
   headerName: 'Message',
   headerTooltip: 'Message',
   width: 110,
   filter: 'agSetColumnFilter',
   tooltipValueGetter: (params) =>  `${params.value} some text`
}

or just use the same method for tooltipValueGetter

UPDATE:

Okay, I understood

but it also easy

Ag-grid has property tooltipField - where you can choose any field from grid

For example here - in the column of 'sport' I am showing tooltip of the previous column

Example: https://plnkr.co/edit/zNbMPT5HOB9yqI08

OR

You can easily manipulate with data for each field by tooltipValueGetter
with next construction:

tooltipValueGetter: function(params) {
  return `Country: ${params.data.country}, Athlete: ${params.data.athlete}, Sport: ${params.data.sport}`;
},

Example: https://plnkr.co/edit/zNbMPT5HOB9yqI08

Result:

UPDATE 2

Hey Man! I do not understand was is wrong

I just used  your code snippet and my solution

And it works as you want

Example: https://plnkr.co/edit/zNbMPT5HOB9yqI08

UPDATE 3

A little bit of manipulation and I can get the data

{ field: 'gold', aggFunc: 'sum',
    tooltipValueGetter: function(params) {
    var model = params.api.getDisplayedRowAtIndex(params.rowIndex);
    return model.allLeafChildren[0].data.silver;
  },
},

The Last:
https://plnkr.co/edit/9qtYjkngKJg6Ihwb?preview