问:
how to access database model fields of parent model linked as e.g. Class->School->User?
I am fairly new to programming languages, django and database models. So my question is simple I have 3 models in models.py as

```<code>class UserProfileInfo(models.Model):
# create relationship with built-in user in admin
user = models.OneToOneField(User)
portfolio_site = models.URLField(blank=True)

class School(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=256)
principal = models.CharField(max_length=256)
location = models.CharField(max_length=256)

class Classroom(models.Model):
school = models.ForeignKey(School, on_delete=models.CASCADE)
class_name = models.CharField(max_length=256)
desc = models.CharField(max_length=256)
</code>```

And I want to access 'id' from User model. I have tried using

def ClassroomView(request):

```<code>classroom_list = Classroom.objects\
                    .filter(school__id=request.session.get('user_id','0'))\
                    .filter(user__id=1).values()
class_dict = {'class_records': classroom_list}
return render(request, 'basic_app/classroom_list.html', context=class_dict)
</code>```

And it gives the following error:

```<code>FieldError at /basic_app/class/
Cannot resolve keyword 'user' into field. Choices are: class_name, desc, id, school, school_id
</code>```

Is there any way that i can access the fields of User model from Classroom model since it is linked by foreign key as Classroom->School->User
Please tell me if I am doing something wrong here any insights and solutions are appreciated!!

答:
Just to recap:

User - UserProfileInfo = 1:1

School - User = 1:N

Classroom - School = 1:N

In other words each user has 1 and only one UserProfile.  Each school has 1 user attached and that user can be attached to multiple schools (not sure if this is desired, but that depends on the use case).  Each school can have multiple classrooms.

Your goal is to return the list of schools attached to the user. I would do this by:

```<code>classroom_list = Classroom.objects.filter(school__user=User.objects.get(pk=0))
</code>```

or if in a view with request:

```<code>classroom_list = Classroom.objects.filter(school__user=request.user)
</code>```

Body:
I am fairly new to programming languages, django and database models. So my question is simple I have 3 models in models.py as

class UserProfileInfo(models.Model):
# create relationship with built-in user in admin
user = models.OneToOneField(User)
portfolio_site = models.URLField(blank=True)

class School(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=256)
principal = models.CharField(max_length=256)
location = models.CharField(max_length=256)

class Classroom(models.Model):
school = models.ForeignKey(School, on_delete=models.CASCADE)
class_name = models.CharField(max_length=256)
desc = models.CharField(max_length=256)

And I want to access 'id' from User model. I have tried using

def ClassroomView(request):

classroom_list = Classroom.objects\
                    .filter(school__id=request.session.get('user_id','0'))\
                    .filter(user__id=1).values()
class_dict = {'class_records': classroom_list}
return render(request, 'basic_app/classroom_list.html', context=class_dict)

And it gives the following error:

FieldError at /basic_app/class/
Cannot resolve keyword 'user' into field. Choices are: class_name, desc, id, school, school_id

Is there any way that i can access the fields of User model from Classroom model since it is linked by foreign key as Classroom->School->User
Please tell me if I am doing something wrong here any insights and solutions are appreciated!!

Body:
Just to recap:

User - UserProfileInfo = 1:1

School - User = 1:N

Classroom - School = 1:N

In other words each user has 1 and only one UserProfile.  Each school has 1 user attached and that user can be attached to multiple schools (not sure if this is desired, but that depends on the use case).  Each school can have multiple classrooms.

Your goal is to return the list of schools attached to the user. I would do this by:

classroom_list = Classroom.objects.filter(school__user=User.objects.get(pk=0))

or if in a view with request:

classroom_list = Classroom.objects.filter(school__user=request.user)


来源: stackexchange

问:
Mapping data with ajax returns zero
I've been working with ajax to get input values from a form when it's submitted, but when I look into the console it comes back as 0. I'm not too familiar with ajax overall, so I'm not sure if I'm not using this correctly or if I have an error somewhere else.

Here's what I have:

JS:

```<code>jQuery(this).find(".form-item").on("submit", function(e) {
    var $this = jQuery(this);
    if (this.checkValidity()) {
      e.preventDefault();
      $.ajax({
        url: Config.ajaxurl,
        type: 'POST',
        dataType: 'json',
        accepts: 'application/json',
        context: this,
        data: {
          action: 'process_form',
          form_info: {
            "input_18_16": $(this).parents('.form-item').find('#input_18_16').val() || '',
            "input_18_17": $(this).parents('.form-item').find('#input_18_17').val() || '',
            "input_18_3": $(this).parents('.form-item').find('#input_18_3').val() || '',
            "input_18_2": $(this).parents('.form-item').find('#input_18_2').val() || ''
          },
        },
        success: function(data, status, xhr) {
          console.log('Response:\n', data)
          console.log('successful trigger');
          console.log($(this).find('#input_18_16').val());
        },
        error: function(xhr, code, error) {
          console.log(error)
        }
      })
    }
  });
</code>```

The crazy thing is that I can get the data correctly from this:
console.log($(this).find('#input_18_16').val());
In the console. Which but for some reason the console.log('Response:\n', data) comes back as Response:0 so I'm not sure why it's successful but not able to return anything?

答:
In the success function you should use $this instead of $(this). That's why you set it in the first place, isn't it?

You can also use it in the data: option, since it's more efficient to reuse the variable instead of calling jQuery() repeatedly.

ContentLicense: CC BY-SA 3.0

Title: Mapping data with ajax returns zero

Body:
I've been working with ajax to get input values from a form when it's submitted, but when I look into the console it comes back as 0. I'm not too familiar with ajax overall, so I'm not sure if I'm not using this correctly or if I have an error somewhere else.

Here's what I have:

JS:

jQuery(this).find(".form-item").on("submit", function(e) {
    var $this = jQuery(this);
    if (this.checkValidity()) {
      e.preventDefault();
      $.ajax({
        url: Config.ajaxurl,
        type: 'POST',
        dataType: 'json',
        accepts: 'application/json',
        context: this,
        data: {
          action: 'process_form',
          form_info: {
            "input_18_16": $(this).parents('.form-item').find('#input_18_16').val() || '',
            "input_18_17": $(this).parents('.form-item').find('#input_18_17').val() || '',
            "input_18_3": $(this).parents('.form-item').find('#input_18_3').val() || '',
            "input_18_2": $(this).parents('.form-item').find('#input_18_2').val() || ''
          },
        },
        success: function(data, status, xhr) {
          console.log('Response:\n', data)
          console.log('successful trigger');
          console.log($(this).find('#input_18_16').val());
        },
        error: function(xhr, code, error) {
          console.log(error)
        }
      })
    }
  });

The crazy thing is that I can get the data correctly from this:
console.log($(this).find('#input_18_16').val());
In the console. Which but for some reason the console.log('Response:\n', data) comes back as Response:0 so I'm not sure why it's successful but not able to return anything?


问:
Vue method not firing
I am working on a project that uses Vue2 (2.5.3) along with Vue Tables 2. All I am trying to do is add an anchor around each row, as the  linked example shows, and invoke the edit() function. However, it doesn't seem to fire at all and I am not getting any errors. Any idea why this is?

.vue file

```<code>  <template>
    <div class="col-md-8 col-md-offset-2">
        <div id="people">
            <v-client-table :data="tableData" :columns="columns">
                <template slot="edit" slot-scope="props">
                    <div>
                        <a class="fa fa-edit" :href="edit(props.row.id)"></a>
                    </div>
                </template>
            </v-client-table>
        </div>
    </div>
</template>

<script>
    import {ServerTable, ClientTable, Event} from 'vue-tables-2';
    import Vue from 'vue';
    import axios from 'axios';

    Vue.use(ClientTable, {
        perPage: 3
    }, false);

    export default {
        methods: {
          edit: function(id){
              console.log("OK", id);
          }
        },
        data() {
            return {
                columns: ['id','name','age'],
                tableData: [
                    {id:1, name:"John",age:"20"},
                    {id:2, name:"Jane",age:"24"},
                    {id:3, name:"Susan",age:"16"},
                    {id:4, name:"Chris",age:"55"},
                    {id:5, name:"Dan",age:"40"}
                ]
            };
        }
    }
</script>

<style lang="scss">
.VuePagination__count {
    display:none;
}
</style>
</code>```

答:
The first problem I see is that there is no way that I can tell from the documentation to wrap an entire row the way you are proposing with a link. There are several pre-defined slots you can customize, and you can also use a slot for each column you pass into the columns property.

Templates allow you to wrap your cells with vue-compiled HTML. It can
  be used in any of the following ways:

Note that says cells. So you can provide a template for each individual cell by specifying the name of the column as the slot.

In your example, there is no edit column, so nothing is actually rendered.

You could add an edit column to columns:

```<code>columns: ['edit', 'id','name','age'],
</code>```

And then your template would work; it would add the font awesome icon to a column in the table.

Here is an example.

Title: Vue method not firing

Body:
I am working on a project that uses Vue2 (2.5.3) along with Vue Tables 2. All I am trying to do is add an anchor around each row, as the  linked example shows, and invoke the edit() function. However, it doesn't seem to fire at all and I am not getting any errors. Any idea why this is?

.vue file

  <template>

            <v-client-table :data="tableData" :columns="columns">
                <template slot="edit" slot-scope="props">

                </template>
            </v-client-table>

</template>

Body:
The first problem I see is that there is no way that I can tell from the documentation to wrap an entire row the way you are proposing with a link. There are several pre-defined slots you can customize, and you can also use a slot for each column you pass into the columns property.

Templates allow you to wrap your cells with vue-compiled HTML. It can
  be used in any of the following ways:

Note that says cells. So you can provide a template for each individual cell by specifying the name of the column as the slot.

In your example, there is no edit column, so nothing is actually rendered.

You could add an edit column to columns:

columns: ['edit', 'id','name','age'],

And then your template would work; it would add the font awesome icon to a column in the table.

Here is an example.


问:
which is better "for(int i = 0; i != 5; ++i)" or "for(int i = 0; i <= 5; i++)"?
which is better for(int i = 0; i != 5; ++i) or for(int i = 0; i <= 5; i++)?

Please explain the rationale, if possible.

I read somewhere that != operator is better than comparison operators. also pre-increment operator is better than post-increment operator, since it doesn't require any temporary variable to store the intermediate value.

Is there any better form of for loop than these two?

p.s: I use the former one as suggested by one of the sources, which i don't remember now.

答:
There are at least two differences:

the first one will iterate 5 times (from 0 to 4), while the second one will iterate 6 times (from 0 to 5).

This is a logic difference, and it depends on what you need to do.

If what you meant for the second example was i<=4 (versus i!=5) you shouldn't bother: any compiler will always be able to optimize such a trivial expression even with optimizations turned off.

the second difference is the use of operator ++: in a case you use the prefix version, while in the other the postfix version.

This doesn't make difference for native types, but could do some difference with user defined types (ie classes, structs, enums, ...), since the user could overload the operator, and the postfix one (var ++) could be a little slower sometimes.

ContentLicense: CC BY-SA 2.5


问:
parseInt() string hash returns integer
I have a hash as an ID that I accidentally used parseInt() on.

I am wondering why it returns an actual integer (7) instead of NaN

const hash = "7bb94588-4f62-4c41-a782-e5164844cc0d";
console.log(hash);
console.log(typeof hash);
console.log(parseInt(hash))```

Not really a question in need of help... but I would like to have a better understanding of how JS works.

答:
parseInt starts looking at characters from the beginning of the string and when it encounters non-numeric character, cuts away the rest of the string from this position.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Title: parseInt() string hash returns integer

Body:
I have a hash as an ID that I accidentally used parseInt() on.

I am wondering why it returns an actual integer (7) instead of NaN

const hash = "7bb94588-4f62-4c41-a782-e5164844cc0d";
console.log(hash);
console.log(typeof hash);
console.log(parseInt(hash))

Not really a question in need of help... but I would like to have a better understanding of how JS works.


问:
How do I add multiple inputs from a prompt in an array together?
I was instructed to create a program that takes 10 numbers from a user. Then it should display it and find its difference from the average (from the 10 numbers inputted.) I've messed around with the code for a while but I'm not sure what I'm doing wrong. When I open in browser, the calculations aren't correct. </p>

```<code>var number = new Array(10);
for(var i=0; i<10; i++) {
var number = prompt("PLEASE ENTER A NUMBER");
total =  parseInt(number);
average = total/10;
document.write("The difference from the average for the number, " + number +
"is equal to " + (number - average) +  "<br>");
}
</code>```

答:
It's because your every input starts calculating the average even before you get the other numbers. You would want to wait for all the input and then do the computation.

And for total you have to add numbers. Probably all you need is to get your math right.

var number = new Array(10);
var total = 0;
for(var i=0; i<10; i++) {
   number[i] = parseInt(prompt("PLEASE ENTER A NUMBER\n"));
   total +=  parseInt(number[i]);
}
var average = total / number.length
for(var i=0; i<10; i++) {
    alert("The difference from the average for the number, " + number[i] +
"is equal to " + (number[i] - average));
}```

Body:
I was instructed to create a program that takes 10 numbers from a user. Then it should display it and find its difference from the average (from the 10 numbers inputted.) I've messed around with the code for a while but I'm not sure what I'm doing wrong. When I open in browser, the calculations aren't correct.

var number = new Array(10);
for(var i=0; i<10; i++) {
var number = prompt("PLEASE ENTER A NUMBER");
total =  parseInt(number);
average = total/10;
document.write("The difference from the average for the number, " + number +
"is equal to " + (number - average) +  "
");
}


问:
android, go back to the saved data after selection in the listview
In android studio, I have an activity called ADD that let the user enter his name and birthday. when the user click on ok button the data will be saved to SQLDatabase, and then the data will be displayed in another activity in a listview. what i want is: when the user is in listview activity and click on any item of this listview , i want to take him back to the ADD activity with the saved data not with the default data.<br>
anyone here have a solution please? </p>

答:
Try to use startActivityForResult
and onActivityResult
Example By Two Classes A&B

Start Activity B from A

```<code>Intent i = new Intent(this, B.class);
startActivityForResult(i, 1);
</code>```

In Activity B when you want to get back with data

```<code>Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
</code>```

if You want to return without data

```<code>Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
</code>```

In Activity A :

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}
</code>```

Body:
In android studio, I have an activity called ADD that let the user enter his name and birthday. when the user click on ok button the data will be saved to SQLDatabase, and then the data will be displayed in another activity in a listview. what i want is: when the user is in listview activity and click on any item of this listview , i want to take him back to the ADD activity with the saved data not with the default data.

anyone here have a solution please?

Body:
Try to use startActivityForResult
and onActivityResult
Example By Two Classes A&B

Start Activity B from A

Intent i = new Intent(this, B.class);
startActivityForResult(i, 1);

In Activity B when you want to get back with data

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

if You want to return without data

Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();

In Activity A :

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}


问:
Get html body of a httppost
How do I read out html tags from a httppost. the issue is that I have to read out the __viewstate key of aspx request and than send them back in a form with user, password. The get method is blocked by the server. Any ideas?

答:
Once you have executed your HttpPost you can save the "response" inside a HttpResponse object.

You can then obtain the HTML from there. Here you can see an example in Java.

```<code> HttpClient client = HttpClientBuilder.create().build();

 HttpPost postMethod = new HttpPost("http://any.url.com");

 try{
     HttpResponse response = client.execute(postMethod);
     String yourHTML = EntityUtils.toString(response.getEntity());
 }catch(Exception e){
     e.printStackTrace();
 }
</code>```

I hope it helps you.

Title: Get html body of a httppost

Body:
Once you have executed your HttpPost you can save the "response" inside a HttpResponse object.

You can then obtain the HTML from there. Here you can see an example in Java.

 HttpClient client = HttpClientBuilder.create().build();

 HttpPost postMethod = new HttpPost("http://any.url.com");

 try{
     HttpResponse response = client.execute(postMethod);
     String yourHTML = EntityUtils.toString(response.getEntity());
 }catch(Exception e){
     e.printStackTrace();
 }

I hope it helps you.


答:
hello to my dear friend , first of i have a question do you code for console or web ?

if you doing for console you must write like this :

```<code>var number = new Array(10);
var total = 0;
for(var i=0; i<10; i++) {
var number = console.log("PLEASE ENTER A NUMBER\n");
total = total + parseInt(readline());
}
average = total/10;
console.log("The difference from the average for the number, " + number +
"is equal to " + (number - average));
</code>```

and for your way you can simply just change your code to :

```<code>var number = new Array(10);
var total = 0 ;
    for(var i=0; i<5; i++) {
    var number = prompt("PLEASE ENTER A NUMBER");
    total = total + parseInt(number);
    }
    average = total/5;
    document.write("The difference from the average for the number, " + number +
    "is equal to " + (number - average) +  "<br>");
</code>```

var number = new Array(10);
var total = 0 ;
    for(var i=0; i<5; i++) {
    var number = prompt("PLEASE ENTER A NUMBER");
    total = total + parseInt(number);
    }
    average = total/5;
    document.write("The difference from the average for the number, " + number +
    "is equal to " + (number - average) +  "
");```

Title: How do I add multiple inputs from a prompt in an array together?

Body:
hello to my dear friend , first of i have a question do you code for console or web ?

if you doing for console you must write like this :

var number = new Array(10);
var total = 0;
for(var i=0; i<10; i++) {
var number = console.log("PLEASE ENTER A NUMBER\n");
total = total + parseInt(readline());
}
average = total/10;
console.log("The difference from the average for the number, " + number +
"is equal to " + (number - average));

and for your way you can simply just change your code to :

var number = new Array(10);
var total = 0 ;
    for(var i=0; i<5; i++) {
    var number = prompt("PLEASE ENTER A NUMBER");
    total = total + parseInt(number);
    }
    average = total/5;
    document.write("The difference from the average for the number, " + number +
    "is equal to " + (number - average) +  "<br>");

var number = new Array(10);
var total = 0 ;
    for(var i=0; i<5; i++) {
    var number = prompt("PLEASE ENTER A NUMBER");
    total = total + parseInt(number);
    }
    average = total/5;
    document.write("The difference from the average for the number, " + number +
    "is equal to " + (number - average) +  "<br>");


问:
How to check if a data item is empty in Blueprism
I want to check if a data item is empty or not. I am storing some values from clipboard into a data item and want to check if data item is empty or contains some text.</p>

答: For example, in a decision stage, you do [Item]<>"". the <> is the symbol that means not equal to in blueprism "language", so basically here you are comparing the item to an empty string.</p>


问:
How to create users to access mapR cluster and be recognized by MCS?
How do you create users that can be 'seen' by the mapr control system (MCS) web ui?

Currently have a mapr installation running on 6 CentOS 7 nodes and have one of the nodes (say node02) acting as an edge node for users to log into (using gnome desktop environment and xrdp). When using system-config-users on node02, can create users and groups, but when trying to assign properties to these these users/groups in the MCS (eg. setting permissions or assigning volumes) the MCS gives error that 'this user or group does not exist'.

May be misinterpreting the info, but this post from the mapr community forms as well as the official documentation seems to imply that users on any of the nodes used in the mapr cluster should be able to be configured in the MCS:

'MapR uses each node's native operating system configuration to authenticate users and groups for access to the cluster'.

However, as stated in the previous paragraph, this does not seem to be the case.

New to using mapr and any explaination of what is happening and how to correct it would be appreciated.

答:
It seems that users and groups for the cluster must have the same name, UID, and GID on every node in the cluster. You can't put them on just one. Would need to use a command like:

```<code>clush -a 'groupadd -g 677 mygroup'
clush -a useradd -g 677 -u 6771 myuser_0001
clush -a ‘echo "myuser0001:mypassword123" | chpasswd'
mkdir $MAPR_HOME/directory/user/myuser0001
chown myuser0001 $MAPR_HOME/user/myuser0001
</code>```

Corroborating information can be found in the docs:

Any user of the cluster must be established with the same Linux UID and GID on every node in the cluster.

Body:
It seems that users and groups for the cluster must have the same name, UID, and GID on every node in the cluster. You can't put them on just one. Would need to use a command like:

clush -a 'groupadd -g 677 mygroup'
clush -a useradd -g 677 -u 6771 myuser_0001
clush -a ‘echo "myuser0001:mypassword123" | chpasswd'
mkdir $MAPR_HOME/directory/user/myuser0001
chown myuser0001 $MAPR_HOME/user/myuser0001

Corroborating information can be found in the docs:

Any user of the cluster must be established with the same Linux UID and GID on every node in the cluster.


问:
Is setting the Authorization header in HttpClient safe?
I'm working in a MVC5 ASP.NET project, and learned that to send authenticated requests to a WEB API from the controller I could do the following to add a token to the header(using an example code):

```<code>public static class APICaller
{
    // Use a single instance for HttpClient to reduce overhead
    private static readonly HttpClient client = new HttpClient();

    //Set the Authorization Header
    public static string SetHeader( string token )
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        return("Success");
    }
}
</code>```

Is setting the header this way on the HttpClient thread-safe? Will other users have a way to access this same token, given that there is only one instance of this HttpClient?

EDIT:

I'd like to ask one more question to get a better understanding of how it works. Would I need to add the header each time I'm making a request with the same HttpClient object?

答:
With the approach you have, once you've set the default request header on your static instance, it will remain set without you having to keep setting it. This means that if you have multiple requests coming into your server, you could end up in a situation where the header is set for one user and then changed by another request before that first request makes it out the door.

One option to avoid this would be to use SendAsync when using user-specific authorisation headers. This allows you to tie the header to a specific message, rather than setting it as a default for the HttpClient itself.

The code is a bit more verbose, but would look something like this:

```<code>using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://path/to/wherever"))
{
    httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "TheToken");

    using (var httpResponseMessage = httpClient.SendAsync(httpRequestMessage))
    {
        // ...
    }
}
</code>```

As you can see, the header is set specially on each request and therefore the issue of mixing up the headers goes away. The obvious downside is that this syntax is more verbose.

Body:
I'm working in a MVC5 ASP.NET project, and learned that to send authenticated requests to a WEB API from the controller I could do the following to add a token to the header(using an example code):

public static class APICaller
{
    // Use a single instance for HttpClient to reduce overhead
    private static readonly HttpClient client = new HttpClient();

    //Set the Authorization Header
    public static string SetHeader( string token )
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        return("Success");
    }
}

Is setting the header this way on the HttpClient thread-safe? Will other users have a way to access this same token, given that there is only one instance of this HttpClient?

EDIT:

I'd like to ask one more question to get a better understanding of how it works. Would I need to add the header each time I'm making a request with the same HttpClient object?

Body:
With the approach you have, once you've set the default request header on your static instance, it will remain set without you having to keep setting it. This means that if you have multiple requests coming into your server, you could end up in a situation where the header is set for one user and then changed by another request before that first request makes it out the door.

One option to avoid this would be to use SendAsync when using user-specific authorisation headers. This allows you to tie the header to a specific message, rather than setting it as a default for the HttpClient itself.

The code is a bit more verbose, but would look something like this:

using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://path/to/wherever"))
{
    httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "TheToken");

    using (var httpResponseMessage = httpClient.SendAsync(httpRequestMessage))
    {
        // ...
    }
}

As you can see, the header is set specially on each request and therefore the issue of mixing up the headers goes away. The obvious downside is that this syntax is more verbose.


答: the data in 'console.log('Response:\n', data)' is actually being returned from the success function after ajax returns successful. Is is not the same as the data you are posting to  Config.ajaxurl.</p>

Title: Mapping data with ajax returns zero


问:
SVG clip path hole / inner cut
```<code><clipPath id="clip1">
    <rect x="10" y="222" height="30" width="50" rx="5"  />
</clipPath>

<image .... clip-path="url(#clip1)"  />
</code>```

It cuts the outer space of the image. But I want to cut a hole into the image. How can I achieve it?

答:
For your purposes, you can use a mask

<svg width="200" height="200" viewBox="0 0 200 200">
<defs>
   <mask id="hole">
    <rect width="100%" height="100%" fill="white"/>
   <rect x="50" y="50" height="50" width="100" rx="5"  fill="black" />
   </mask>
  </defs>
    <image x="0" y="0" width="200" height="200"
 xlink:href="http://placeimg.com/200/200/any"
 mask="url(#hole)" >
  </image>
    </svg>```

Title: SVG clip path hole / inner cut

Body:
<clipPath id="clip1">
    <rect x="10" y="222" height="30" width="50" rx="5"  />
</clipPath>

<image .... clip-path="url(#clip1)"  />

It cuts the outer space of the image. But I want to cut a hole into the image. How can I achieve it?


问:
core-image-minimal has bluetooth
I am trying to build core-image-minimal receipe for iMx7 (Yocto project), the image gets successfully built but it has bluetooth, caam and lot of other stuff. How can I remove these from including in the minimal-image?

core-image-minimal should only have things required for just booting nothing else, somehow other packages are getting added. I didnt add anything in my local.config file.

MACHINE = "imx7dsabresd"

答: You do not mention which machine you are building for, but I suspect it has bluetooth enabled in the MACHINE_FEATURES. I also didn't look at the bb file for core-image-minimal closely, so could be something else.</p>

Title: core-image-minimal has bluetooth


问:
Transact SQL UPDATE based on a declared variable
I have two tables called ALUMNO and ALUMNO_GENERAL.

I would like to create a stored procedure which automatically chooses which table will update by looking at the variable @campo declared as a parameter to the stored procedure.

When I execute the procedure below, it says 1 row affected, but does not update the value of the table.

```<code>exec updateAl 'CALLE','0015','ROJO'
</code>```

Stored procedure:

```<code>create procedure updateAl

    @campo varchar(30), @matr varchar(10), @newVal varchar(15)
    as begin

    if @campo  IN ('AP_PATERNO' , 'AP_MATERNO', 'NOMBRE', 'GRUPO', 'TURNO' , 'SEMESTRE' , 'STATUS' , 'NUMEMPLEADO')

    begin
        select @campo
        declare @sql varchar (1000)

        select @sql= 'update alumno set '+ @campo+'='+@newVal +' where MATRICULA='+@matr
        exec(@sql)
    end
    else
         update ALUMNO_GENERAL set @campo =@newVal where MATRICULA=@matr
end
</code>```

答:
Your dynamic sql is not correct, try this:</p>

```<code>select @sql= 'update alumno set '+ @campo+'='''+@newVal +''' where MATRICULA='''+@matr + '''
exec(@sql)
end
</code>```

Body:
I have two tables called ALUMNO and ALUMNO_GENERAL.

I would like to create a stored procedure which automatically chooses which table will update by looking at the variable @campo declared as a parameter to the stored procedure.

When I execute the procedure below, it says 1 row affected, but does not update the value of the table.

exec updateAl 'CALLE','0015','ROJO'

Stored procedure:

create procedure updateAl

    @campo varchar(30), @matr varchar(10), @newVal varchar(15)
    as begin

    if @campo  IN ('AP_PATERNO' , 'AP_MATERNO', 'NOMBRE', 'GRUPO', 'TURNO' , 'SEMESTRE' , 'STATUS' , 'NUMEMPLEADO')

    begin
        select @campo
        declare @sql varchar (1000)

        select @sql= 'update alumno set '+ @campo+'='+@newVal +' where MATRICULA='+@matr
        exec(@sql)
    end
    else
         update ALUMNO_GENERAL set @campo =@newVal where MATRICULA=@matr
end

Body:
Your dynamic sql is not correct, try this:

select @sql= 'update alumno set '+ @campo+'='''+@newVal +''' where MATRICULA='''+@matr + '''
exec(@sql)
end


问:
Plot a Linear Regression in ggplot2
I have this dataframe:

```<code>> head(data)
    sx   yd  sl
1   male 35  36350
2   male 22  35350
3   male 23  28200
4 female 27  26775
5   male 30  33696
6   male 21  28516
</code>```

Where "sx" is sex, "yd" is years since acquired degree and "sl" is salary. Using ggplot or plot, I can plot the scatter easily.

```<code>palette(c("pink", "blue"))
plot(data$yr, data$sl, col = factor(data$sx), xlab = "Years Since Earned Highest Degree", ylab = "Salary (dollars)", main = "Salary Increases with Experience", pch = 19)
legend("topleft", legend = unique(data$sx), col = c("blue", "pink"), pch=19)

library(ggplot2)
ggplot(data, aes(x=yd,y=sl)) +
    geom_point(shape=21, aes(col=sx, bg=sx)) +
    xlab("Years Since Earned Highest Degree") +
    ylab("Salary (dollars)") +
    ggtitle("Salary Increases with Experience") +
    scale_color_discrete(guide=FALSE) +
    labs(fill="sex")
</code>```

However, I have also made a linear model based on the data:

```<code>mod<-lm(sl~sx*poly(yd,2),data)
</code>```

And I am unable to figure out how to plot the data to the graphs. Specifically, I want two lines corresponding to male and female data superimposed on the scatterplot AND to be color-coded. I would assume that R has some way to do this so that I don't have to actually write out the model. Either base plot or ggplot answers are good. Thanks.

Edit:

Running this the above ggplot with geom_smooth(aes(col=sx), se = FALSE, method = "lm", formula = sl ~ sx * poly(yd, 2)):

```<code>ggplot(data, aes(x=yd,y=sl)) + geom_point(shape=21, aes(col=sx, bg=sx)) + geom_smooth(aes(col=sx), se = FALSE, method = "lm", formula = sl ~ sx * poly(yd, 2)) + xlab("Years Since Earned Highest Degree") + ylab("Salary (dollars)") + ggtitle("Salary Increases with Experience") + scale_color_discrete(guide=FALSE)+ labs(fill="sex")
</code>```

Returns this error:

```<code>Error in model.frame.default(formula = formula, data = data, weights = weight,  :
  variable lengths differ (found for '(weights)')
Error in if (nrow(layer_data) == 0) return() : argument is of length zero
</code>```

答:
```<code>data = data.frame(sx = c("male", "male", "male", "female", "male", "male"),
              yr = c(35, 22, 23, 27, 30, 21),
              sl = c(36350, 35350, 28200, 26775, 33696, 28516))
ggplot(data, aes(x=yr,y=sl)) +
  geom_point(shape=21, aes(col=sx, bg=sx)) +
  geom_smooth(aes(color = sx), se = FALSE, method = "lm", formula = y ~ poly(x, 2)) +
  xlab("Years Since Earned Highest Degree") +
  ylab("Salary (dollars)") +
  ggtitle("Salary Increases with Experience") +
  scale_color_discrete(guide=FALSE)+ labs(fill="sex")
</code>```

Is this what you want? You should get individual fits if you have more data for female. Right now sum(data$sx == 'female') is 1. There's no way to have a polynomial fit to that.

For example, try:

```<code>data = data.frame(sx = c("male", "male", "male", "female", "male", "male", "female", "female", "female"),
                  yr = c(35, 22, 23, 27, 30, 21, 25, 18, 29),
                  sl = c(36350, 35350, 28200, 26775, 33696, 28516, 27402, 31492, 23195))
</code>```

This should work.

OwnerDisplayName: Jeff

Title: Plot a Linear Regression in ggplot2

Body:
I have this dataframe:

> head(data)
    sx   yd  sl
1   male 35  36350
2   male 22  35350
3   male 23  28200
4 female 27  26775
5   male 30  33696
6   male 21  28516

Where "sx" is sex, "yd" is years since acquired degree and "sl" is salary. Using ggplot or plot, I can plot the scatter easily.

palette(c("pink", "blue"))
plot(data$yr, data$sl, col = factor(data$sx), xlab = "Years Since Earned Highest Degree", ylab = "Salary (dollars)", main = "Salary Increases with Experience", pch = 19)
legend("topleft", legend = unique(data$sx), col = c("blue", "pink"), pch=19)

library(ggplot2)
ggplot(data, aes(x=yd,y=sl)) +
    geom_point(shape=21, aes(col=sx, bg=sx)) +
    xlab("Years Since Earned Highest Degree") +
    ylab("Salary (dollars)") +
    ggtitle("Salary Increases with Experience") +
    scale_color_discrete(guide=FALSE) +
    labs(fill="sex")

However, I have also made a linear model based on the data:

mod<-lm(sl~sx*poly(yd,2),data)

And I am unable to figure out how to plot the data to the graphs. Specifically, I want two lines corresponding to male and female data superimposed on the scatterplot AND to be color-coded. I would assume that R has some way to do this so that I don't have to actually write out the model. Either base plot or ggplot answers are good. Thanks.

Edit:

Running this the above ggplot with geom_smooth(aes(col=sx), se = FALSE, method = "lm", formula = sl ~ sx * poly(yd, 2)):

ggplot(data, aes(x=yd,y=sl)) + geom_point(shape=21, aes(col=sx, bg=sx)) + geom_smooth(aes(col=sx), se = FALSE, method = "lm", formula = sl ~ sx * poly(yd, 2)) + xlab("Years Since Earned Highest Degree") + ylab("Salary (dollars)") + ggtitle("Salary Increases with Experience") + scale_color_discrete(guide=FALSE)+ labs(fill="sex")

Returns this error:

Error in model.frame.default(formula = formula, data = data, weights = weight,  :
  variable lengths differ (found for '(weights)')
Error in if (nrow(layer_data) == 0) return() : argument is of length zero

Body:
data = data.frame(sx = c("male", "male", "male", "female", "male", "male"),
              yr = c(35, 22, 23, 27, 30, 21),
              sl = c(36350, 35350, 28200, 26775, 33696, 28516))
ggplot(data, aes(x=yr,y=sl)) +
  geom_point(shape=21, aes(col=sx, bg=sx)) +
  geom_smooth(aes(color = sx), se = FALSE, method = "lm", formula = y ~ poly(x, 2)) +
  xlab("Years Since Earned Highest Degree") +
  ylab("Salary (dollars)") +
  ggtitle("Salary Increases with Experience") +
  scale_color_discrete(guide=FALSE)+ labs(fill="sex")

Is this what you want? You should get individual fits if you have more data for female. Right now sum(data$sx == 'female') is 1. There's no way to have a polynomial fit to that.

For example, try:

data = data.frame(sx = c("male", "male", "male", "female", "male", "male", "female", "female", "female"),
                  yr = c(35, 22, 23, 27, 30, 21, 25, 18, 29),
                  sl = c(36350, 35350, 28200, 26775, 33696, 28516, 27402, 31492, 23195))

This should work.


问:
Macro increment
I have table lookup values as below

```<code>sno date
1   200101
2   200102
3   200103
4   200104
</code>```

I wrote below macro

```<code>%let date=200102
 proc sql;
 select sno into :no from lookup where date=&date.;
 quit;
</code>```

I need a help on how to convert the entire table lookup into macro increment by creating first s.no and date as two macro variable then increment. So that i don’t need to update dates in my table lookup every time. So if i look up for date 201304 i need to get its corresponding s.no

答:
If you want to simply translate one (unique) value into another. You can use (in)formats. They can do much more than just changing how data are read/displayed. They are easy to use, fast (in-memory) and don't depend on the table once created. Change the library to a permanent one if work (=> temporary library) doesn't suit your needs.</p>

```<code>options fmtsearch=(formats,work);

data fmt(keep = fmtname type start end label hlo default);
length fmtname $10 type $1 start end $6 label 8 hlo $1 default 8;
fmtname = 'date_to_no';
type = 'I';
label=0;
do y = 2001 to 2099;
    do m = 1 to 12;
        start = put(y,4.) || put(m,z2.);
        end = start;
        label + 1;
        default=50; /*default length of the string compared when informat is used. Should be higher than both start and end*/
        output;
    end;
end;
/*if you want to assign a value (=label) to inputs not found. In this case it's -2*/
hlo="O";
start = "";
end = start;
label= -2;
output;
run;

proc format library=work cntlin=fmt;
run;

data test;
no = input('200101',date_to_no.); output;
no = input('201710',date_to_no.); output;
no = input('201713',date_to_no.); output;
run;
</code>```

Title: Macro increment

Body:
I have table lookup values as below

sno date
1   200101
2   200102
3   200103
4   200104

I wrote below macro

%let date=200102
 proc sql;
 select sno into :no from lookup where date=&date.;
 quit;

I need a help on how to convert the entire table lookup into macro increment by creating first s.no and date as two macro variable then increment. So that i don’t need to update dates in my table lookup every time. So if i look up for date 201304 i need to get its corresponding s.no

Body:
If you want to simply translate one (unique) value into another. You can use (in)formats. They can do much more than just changing how data are read/displayed. They are easy to use, fast (in-memory) and don't depend on the table once created. Change the library to a permanent one if work (=> temporary library) doesn't suit your needs.

options fmtsearch=(formats,work);

data fmt(keep = fmtname type start end label hlo default);
length fmtname $10 type $1 start end $6 label 8 hlo $1 default 8;
fmtname = 'date_to_no';
type = 'I';
label=0;
do y = 2001 to 2099;
    do m = 1 to 12;
        start = put(y,4.) || put(m,z2.);
        end = start;
        label + 1;
        default=50; /*default length of the string compared when informat is used. Should be higher than both start and end*/
        output;
    end;
end;
/*if you want to assign a value (=label) to inputs not found. In this case it's -2*/
hlo="O";
start = "";
end = start;
label= -2;
output;
run;

proc format library=work cntlin=fmt;
run;

data test;
no = input('200101',date_to_no.); output;
no = input('201710',date_to_no.); output;
no = input('201713',date_to_no.); output;
run;


问:
Angular POST with XML
I am using angular (not AngularJS). I have web service(SOAP) which is expecting XML data.

I tried to search but i couldn't find complete example of POST request with XML.

I need a sample in angular 2+ that explain data format, content-type, handle response...

Any help would be greatly appreciated.

答:
```<code>@Component({
  /* templateUrl, stylesUrls, selector, providers, etc. go here */
})
export class FooComponent {
  someXml;
  constructor(private _http:Http) {}
  // Maybe postStuff() is called on a button click or something.
  postStuff() {
    this._http.post("http://example.com/api", { responseType:'text' })
      .subscribe(
        res => this.someXml = res
      );
  }
}
</code>```

Now, how you parse the XML and what you do with it is chapter 2 of the story, but we'd need some real examples to answer that.

Title: Angular POST with XML

Body:
@Component({
  /* templateUrl, stylesUrls, selector, providers, etc. go here */
})
export class FooComponent {
  someXml;
  constructor(private _http:Http) {}
  // Maybe postStuff() is called on a button click or something.
  postStuff() {
    this._http.post("http://example.com/api", { responseType:'text' })
      .subscribe(
        res => this.someXml = res
      );
  }
}

Now, how you parse the XML and what you do with it is chapter 2 of the story, but we'd need some real examples to answer that.


问:
Is there a performance difference in using a GROUP BY with MAX() as the aggregate vs ROW_NUMBER over partition by?
Is there a performance difference between the following 2 queries, and if so, then which one is better?:

```<code>    select
    q.id,
    q.name
    from(
        select id, name, row_number over (partition by name order by id desc) as row_num
from table
    ) q
        where q.row_num = 1
</code>```

versus

```<code>select
max(id) ,
name
from table
group by name
</code>```

(The result set should be the same)

This is assuming that no indexes are set.

UPDATE: I tested this, and the group by was faster.

答:
I had a table of about 4.5M rows, and I wrote both a MAX with GROUP BY as well as a ROW_NUMBER solution and tested them both.  The MAX requires two clustered scans of the table, one to aggregate, and a second to join to the rest of the columns whereas ROW_NUMBER only needed one.  (Obviously one or both of these could be indexed to minimize IO, but the point is that GROUP BY requires two index scans.)

According to the optimizer, in my case the ROW_NUMBER is about 60% more efficient according to the subtree cost.  And according to statistics IO, about 20% less CPU time.  However, in real elapsed time, the ROW_NUMBER solution takes about 80% more real time.  So the GROUP BY wins in my case.

This seems to match the other answers here.

Body:
Is there a performance difference between the following 2 queries, and if so, then which one is better?:

    select
    q.id,
    q.name
    from(
        select id, name, row_number over (partition by name order by id desc) as row_num
from table
    ) q
        where q.row_num = 1

versus

select
max(id) ,
name
from table
group by name

(The result set should be the same)

This is assuming that no indexes are set.

UPDATE: I tested this, and the group by was faster.


问:
Local APIC registers mapped in memory contain just 1's
I'm trying to write some code for a Linux kernel module that can read from and write to the local APIC on x86. I'm using the code snippet below to read from the Interrupt Command Register:

```<code>printk(KERN_ERR "APIC %p %d", (int32_t *)(APIC_BASE + 0x300),
                              *(volatile int32_t *)(APIC_BASE + 0x300));
</code>```

This is the output, which never changes:

```<code>APIC ffffffffff5f5300 -1
</code>```

Since I'm printing out a signed 32-bit integer, -1 indicates that the 32 bits I read were all 1's. This is unexpected since (to my understanding) bit 11 (the destination mode bit) needs to be 0 before I can write to the local APIC to send an IPI.

Is there something I am doing incorrectly? Are there any initialization steps that I need to take?

答:
It turns out that my computer is equipped with a newer x2APIC, rather than an xAPIC. x2APICs use MSRs to send IPIs rather than memory-mapped registers, which is what xAPICs use. Thus, the memory I was reading at APIC_BASE doesn't represent the state of the local APIC.

I'm going to rewrite my code to use MSRs, but I was able to test my existing code by setting my x2APIC to use the xAPIC's interface (i.e. use memory-mapped registers instead). This can be done by setting the nox2apic kernel parameter.

Body:
I'm trying to write some code for a Linux kernel module that can read from and write to the local APIC on x86. I'm using the code snippet below to read from the Interrupt Command Register:

printk(KERN_ERR "APIC %p %d", (int32_t *)(APIC_BASE + 0x300),
                              *(volatile int32_t *)(APIC_BASE + 0x300));

This is the output, which never changes:

APIC ffffffffff5f5300 -1

Since I'm printing out a signed 32-bit integer, -1 indicates that the 32 bits I read were all 1's. This is unexpected since (to my understanding) bit 11 (the destination mode bit) needs to be 0 before I can write to the local APIC to send an IPI.

Is there something I am doing incorrectly? Are there any initialization steps that I need to take?


问:
Django SelectDateWidget to show month and year only
Is there a different widget or argument that will allow django to only show/take the year and month input instead of year, month and day?

Currently using SelectDateWidget.

答:
There's a snippet here, which sets the day to 1 (presuming you've got a DateField that this value will end up in, you'll need to get some kind of day).

The code is like this (just in case Django snippets disappears):

```<code>import datetime
import re

from django.forms.widgets import Widget, Select
from django.utils.dates import MONTHS
from django.utils.safestring import mark_safe

__all__ = ('MonthYearWidget',)

RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$')

class MonthYearWidget(Widget):
    """
    A Widget that splits date input into two <select> boxes for month and year,
    with 'day' defaulting to the first of the month.

    Based on SelectDateWidget, in

    django/trunk/django/forms/extras/widgets.py

    """
    none_value = (0, '---')
    month_field = '%s_month'
    year_field = '%s_year'

    def __init__(self, attrs=None, years=None, required=True):
        # years is an optional list/tuple of years to use in the "year" select box.
        self.attrs = attrs or {}
        self.required = required
        if years:
            self.years = years
        else:
            this_year = datetime.date.today().year
            self.years = range(this_year, this_year+10)

    def render(self, name, value, attrs=None):
        try:
            year_val, month_val = value.year, value.month
        except AttributeError:
            year_val = month_val = None
            if isinstance(value, basestring):
                match = RE_DATE.match(value)
                if match:
                    year_val, month_val, day_val = [int(v) for v in match.groups()]

        output = []

        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        month_choices = MONTHS.items()
        if not (self.required and value):
            month_choices.append(self.none_value)
        month_choices.sort()
        local_attrs = self.build_attrs(id=self.month_field % id_)
        s = Select(choices=month_choices)
        select_html = s.render(self.month_field % name, month_val, local_attrs)
        output.append(select_html)

        year_choices = [(i, i) for i in self.years]
        if not (self.required and value):
            year_choices.insert(0, self.none_value)
        local_attrs['id'] = self.year_field % id_
        s = Select(choices=year_choices)
        select_html = s.render(self.year_field % name, year_val, local_attrs)
        output.append(select_html)

        return mark_safe(u'\n'.join(output))

    def id_for_label(self, id_):
        return '%s_month' % id_
    id_for_label = classmethod(id_for_label)

    def value_from_datadict(self, data, files, name):
        y = data.get(self.year_field % name)
        m = data.get(self.month_field % name)
        if y == m == "0":
            return None
        if y and m:
            return '%s-%s-%s' % (y, m, 1)
        return data.get(name, None)
</code>```

Body:
There's a snippet here, which sets the day to 1 (presuming you've got a DateField that this value will end up in, you'll need to get some kind of day).

The code is like this (just in case Django snippets disappears):

import datetime
import re

from django.forms.widgets import Widget, Select
from django.utils.dates import MONTHS
from django.utils.safestring import mark_safe

__all__ = ('MonthYearWidget',)

RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$')

class MonthYearWidget(Widget):
    """
    A Widget that splits date input into two <select> boxes for month and year,
    with 'day' defaulting to the first of the month.

    Based on SelectDateWidget, in

    django/trunk/django/forms/extras/widgets.py

    """
    none_value = (0, '---')
    month_field = '%s_month'
    year_field = '%s_year'

    def __init__(self, attrs=None, years=None, required=True):
        # years is an optional list/tuple of years to use in the "year" select box.
        self.attrs = attrs or {}
        self.required = required
        if years:
            self.years = years
        else:
            this_year = datetime.date.today().year
            self.years = range(this_year, this_year+10)

    def render(self, name, value, attrs=None):
        try:
            year_val, month_val = value.year, value.month
        except AttributeError:
            year_val = month_val = None
            if isinstance(value, basestring):
                match = RE_DATE.match(value)
                if match:
                    year_val, month_val, day_val = [int(v) for v in match.groups()]

        output = []

        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        month_choices = MONTHS.items()
        if not (self.required and value):
            month_choices.append(self.none_value)
        month_choices.sort()
        local_attrs = self.build_attrs(id=self.month_field % id_)
        s = Select(choices=month_choices)
        select_html = s.render(self.month_field % name, month_val, local_attrs)
        output.append(select_html)

        year_choices = [(i, i) for i in self.years]
        if not (self.required and value):
            year_choices.insert(0, self.none_value)
        local_attrs['id'] = self.year_field % id_
        s = Select(choices=year_choices)
        select_html = s.render(self.year_field % name, year_val, local_attrs)
        output.append(select_html)

        return mark_safe(u'\n'.join(output))

    def id_for_label(self, id_):
        return '%s_month' % id_
    id_for_label = classmethod(id_for_label)

    def value_from_datadict(self, data, files, name):
        y = data.get(self.year_field % name)
        m = data.get(self.month_field % name)
        if y == m == "0":
            return None
        if y and m:
            return '%s-%s-%s' % (y, m, 1)
        return data.get(name, None)


问:
Droped and recreated hive external table, but no data shown
First a hive external table is created:

```<code>create external table user_tables.test
(col1 string, col2 string)
partitioned by (date_partition date);
</code>```

records are inserted:

```<code>INSERT INTO TABLE user_tables.test
PARTITION (date_partition='2017-11-16') VALUES ('abc', 'xyz'), ('abc1', 'xyz1');
</code>```

Now, the table is dropped and recreated with the same script.
When I try-

```<code>SELECT * FROM user_tables.test WHERE date_partition='2017-11-16';`
</code>```

I get Done. 0 results.

答:
This is because the table you created is a partitioned table. The insert you ran would have created a partition for date_partition='2017-11-16'. When you drop and re-create the table, Hive looses the information about the partition, it only knows about the table.

Run the command below to get hive to re-create the partitions based on the data.

```<code>MSCK REPAIR TABLE user_tables.test;
</code>```

Now you will see the data when you run SELECT.

If you want to know the partitions in the table run the statement below:

```<code>SHOW PARTITIONS user_tables.test;
</code>```

Run this before and after MSCK to see the effect.

Body:
First a hive external table is created:

create external table user_tables.test
(col1 string, col2 string)
partitioned by (date_partition date);

records are inserted:

INSERT INTO TABLE user_tables.test
PARTITION (date_partition='2017-11-16') VALUES ('abc', 'xyz'), ('abc1', 'xyz1');

Now, the table is dropped and recreated with the same script.
When I try-

SELECT * FROM user_tables.test WHERE date_partition='2017-11-16';`

I get Done. 0 results.

Body:
This is because the table you created is a partitioned table. The insert you ran would have created a partition for date_partition='2017-11-16'. When you drop and re-create the table, Hive looses the information about the partition, it only knows about the table.

Run the command below to get hive to re-create the partitions based on the data.

MSCK REPAIR TABLE user_tables.test;

Now you will see the data when you run SELECT.

If you want to know the partitions in the table run the statement below:

SHOW PARTITIONS user_tables.test;

Run this before and after MSCK to see the effect.


问:
Adding a weighted least squares trendline in ggplot2
I am preparing a plot using ggplot2, and I want to add a trendline that is based on a weighted least squares estimation.

In base graphics this can be done by sending a WLS model to abline:

```<code>mod0 <- lm(ds$dMNP~ds$MNP)
mod1 <- lm(ds$dMNP~ds$MNP, weights = ds$Asset)

symbols(ds$dMNP~ds$MNP, circles=ds$r, inches=0.35)
#abline(mod0)
abline(mod1)
</code>```

in ggplot2 I set the argument weight in geom_smooth but nothing changes:

```<code>ggplot(ds, aes(x=MNP, y=dMNP, size=Asset) +
  geom_point(shape=21) +
  geom_smooth(method = "lm", weight="Asset", color="black", show.legend = FALSE)
</code>```

this gives me the same plot as

```<code>ggplot(ds, aes(x=MNP, y=dMNP, size=Asset) +
  geom_point(shape=21) +
  geom_smooth(method = "lm", color="black", show.legend = FALSE)
</code>```

答:
I'm late, but for posterity and clarity, here is the full solution:

```<code>ggplot(ds, aes(x = MNP, y = dMNP, size = Asset)) +
  geom_point(shape = 21) +
  geom_smooth(method = "lm", mapping = aes(weight = Asset),
              color = "black", show.legend = FALSE)
</code>```

Don't put the weight name in quotes.

Body:
I am preparing a plot using ggplot2, and I want to add a trendline that is based on a weighted least squares estimation.

In base graphics this can be done by sending a WLS model to abline:

mod0 <- lm(ds$dMNP~ds$MNP)
mod1 <- lm(ds$dMNP~ds$MNP, weights = ds$Asset)

symbols(ds$dMNP~ds$MNP, circles=ds$r, inches=0.35)
#abline(mod0)
abline(mod1)

in ggplot2 I set the argument weight in geom_smooth but nothing changes:

ggplot(ds, aes(x=MNP, y=dMNP, size=Asset) +
  geom_point(shape=21) +
  geom_smooth(method = "lm", weight="Asset", color="black", show.legend = FALSE)

this gives me the same plot as

ggplot(ds, aes(x=MNP, y=dMNP, size=Asset) +
  geom_point(shape=21) +
  geom_smooth(method = "lm", color="black", show.legend = FALSE)

Body:
I'm late, but for posterity and clarity, here is the full solution:

ggplot(ds, aes(x = MNP, y = dMNP, size = Asset)) +
  geom_point(shape = 21) +
  geom_smooth(method = "lm", mapping = aes(weight = Asset),
              color = "black", show.legend = FALSE)

Don't put the weight name in quotes.

ContentLicense: CC BY-SA 4.0


问:
What are JavaScript Objects and Properties?
Can anyone explain objects and properties to me in Javascript in layman's terms? The Javascript MDN documentation is confusing me.

I am trying to solve a problem in a Javascript tutorial about objects and properties The question is below and my attempt at the code, I think I followed the MDN as far as I can grasp it. Any help would be appreciated!

Question: Add the value of the property argument as a key on the object argument.
The value of the new property should be set to null.
Return object after adding the new property.

Input Example:

```<code>{}, 'hello'
{ x: 5 }, 'y'
</code>```

Output Example:

```<code>{ hello: null }
{ x: 5, y: null }
</code>```

note: the property name is NOT 'property'.  The name is the value of the argument called property (a string).

My code:
//NOTE: the function addProperty(object, property) was already in the console and I have to write the solution inside of it.

```<code>function addProperty(object, property) {
  // code here
  let result = addProperty({x: 5}, 'y');
  obj[property] = null;
  return obj;
}

addProperty(x, 'y');
</code>```

答:
This particular example is simple:

```<code>var one={};
var two={x:5};
function addProperty(object property){
  obj[property]=null;
  return obj;
}

addProperty(one, 'hello');
addProperty(two, 'y');
</code>```

Objects in javascript are really flexible, their properties can be added or removed, even when set from the very beginning.

If you take:

```<code>var x={};
</code>```

x will be an object with nothing in it, but if instead of that you write:

```<code>var x={
  inner:'b'
};
</code>```

x will be an object with a property called inner which value is 'b', now, if we want to access that property we could do something like this:

```<code>var valueOfInner=x.inner;
</code>```

or

```<code>var valueOfInner=x['inner'];
</code>```

The same if we want to change the value of that property:

```<code>x.inner=8;
</code>```

or

```<code>x['inner']=8;
</code>```

Now, you'll notice that when we use x.['inner'], we could very well use instead:

```<code>var propertyName='inner';
x[propertyName]=8;
</code>```

So you can access and modify a property of an object without actually knowing exactly which property you're manipulating.

Finally, if you're (willing or by accident) trying to set the value of a property that doesn't exists, the property will be automatically be created, for example:

```<code>x['blah']=456;
</code>```

Will create the property blah even when it wasn't defined at first.

Edit: yes, you can define the object and define its properties later:

```<code>var x={};
//more code or something
x['y']=777;//now x has a y property with the value 777
</code>```

Body:
Can anyone explain objects and properties to me in Javascript in layman's terms? The Javascript MDN documentation is confusing me.

I am trying to solve a problem in a Javascript tutorial about objects and properties The question is below and my attempt at the code, I think I followed the MDN as far as I can grasp it. Any help would be appreciated!

Question: Add the value of the property argument as a key on the object argument.
The value of the new property should be set to null.
Return object after adding the new property.

Input Example:

{}, 'hello'
{ x: 5 }, 'y'

Output Example:

{ hello: null }
{ x: 5, y: null }

note: the property name is NOT 'property'.  The name is the value of the argument called property (a string).

My code:
//NOTE: the function addProperty(object, property) was already in the console and I have to write the solution inside of it.

function addProperty(object, property) {
  // code here
  let result = addProperty({x: 5}, 'y');
  obj[property] = null;
  return obj;
}

addProperty(x, 'y');

Body:
This particular example is simple:

var one={};
var two={x:5};
function addProperty(object property){
  obj[property]=null;
  return obj;
}

addProperty(one, 'hello');
addProperty(two, 'y');

Objects in javascript are really flexible, their properties can be added or removed, even when set from the very beginning.

If you take:

var x={};

x will be an object with nothing in it, but if instead of that you write:

var x={
  inner:'b'
};

x will be an object with a property called inner which value is 'b', now, if we want to access that property we could do something like this:

var valueOfInner=x.inner;

or

var valueOfInner=x['inner'];

The same if we want to change the value of that property:

x.inner=8;

or

x['inner']=8;

Now, you'll notice that when we use x.['inner'], we could very well use instead:

var propertyName='inner';
x[propertyName]=8;

So you can access and modify a property of an object without actually knowing exactly which property you're manipulating.

Finally, if you're (willing or by accident) trying to set the value of a property that doesn't exists, the property will be automatically be created, for example:

x['blah']=456;

Will create the property blah even when it wasn't defined at first.

Edit: yes, you can define the object and define its properties later:

var x={};
//more code or something
x['y']=777;//now x has a y property with the value 777


问:
How to produce XML signature with no whitespaces and line-breaks in Java?
I work with the brazilian "Nota Fiscal Eletronica" project, in which they define a standart way to sign XML documents.

Recently, they started to require that there are absolutely no whitespaces between tags, including signature tags (*).

We happen to use apache's XMLSignature and I can't seem to produce an unindented signature.

If I remove the whitespaces after signing, the signature gets broken.

I cannot change the canonicalizer / transformers set either, since they're predefined.

I couldn't find an option or parameter in the XMLSignature API to control indentation or whitespaces.

Below is the code:

```<code>    // the element where to insert the signature
    Element element = ...;
    X509Certificate cert = ...;
    PrivateKey privateKey = ...;

    XMLSignature signer =
            new XMLSignature(doc, "http://xml-security",
            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);

    element.appendChild(signer.getElement());

    Transforms transforms = new Transforms(doc);

    // Define as regras de transformação e canonicalização do documento
    // XML, necessário para fazer a verificação do parsing e da
    // assinatura pelos destinatários
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); //, xpath.getElementPlusReturns());

    transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS); //,xpath.getElementPlusReturns());

    String id = "";

    id = ((Element) element.getElementsByTagName("infNFe").item(0)).getAttributeNode("Id").getNodeValue();

    signer.addDocument("#" + id, transforms,
                       Constants.ALGO_ID_DIGEST_SHA1);
    signer.addKeyInfo(cert);
    signer.sign(privateKey);
</code>```

And below is the resulting signature (snippet):

```<code><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#NFe43110189716583000165550010000076011492273645">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>fas0ra5uRskQgRHSrIYhEjFEjKQ=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
2RGltUZy0HfNoiKtVanAeN+JUPyglWDuQNnMudSgA7kESoHBZ/q/GMbc+xMSN1eV8u7+2PxSKl1T
Zl592FWmCSAkL8pwMujDxJ4iTLU20Hf0dNF7oGcyB+g9GgbipW2udq0kwJLz6HzXUD/Evf/0y+3T
NtsXeIaA6A29ttD/UEs=
</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>
MIIFqTCCBJGgAwIBAgIEQeNSuzANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJicjETMBEGA1UE
ChMKSUNQLUJyYXNpbDEgMB4GA1UECxMXQ2FpeGEgRWNvbm9taWNhIEZlZGVyYWwxFDASBgNVBAMT
C0FDIENBSVhBIFBKMB4XDTEwMDYwODE5MjQwNVoXDTExMDYwODE5NTQwNVowgYQxCzAJBgNVBAYT
AmJyMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMSAwHgYDVQQLExdDYWl4YSBFY29ub21pY2EgRmVkZXJh
bDEUMBIGA1UECxMLQUMgQ0FJWEEgUEoxKDAmBgNVBAMTH0EgQlVITEVSIFNBIENVUlRVTUU6NDA5
NDI0OTAwMTAwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOFxgvG35RQWgXec4zVrzoUHolnJ
fP76rpO2Vo40593W9Gf0WwHt36gVmli0ZeQitFmzFSoE5KhgXQGZg6RpV3WJUFcIrPBHPdqOSfiB
988kf962P+j8fZ38BNmo7TV9H9hMBkV9bD/QOe73wFDc+rT6/9io++Z+7/wup/3glKntAgMBAAGj
ggLOMIICyjAOBgNVHQ8BAf8EBAMCBeAwVwYDVR0gBFAwTjBMBgZgTAECAQkwQjBABggrBgEFBQcC
ARY0aHR0cDovL2ljcC5jYWl4YS5nb3YuYnIvcmVwb3NpdG9yaW8vZHBjYWNjYWl4YXBqLnBkZjAp
BgNVHSUEIjAgBggrBgEFBQcDAgYIKwYBBQUHAwQGCisGAQQBgjcUAgIwgbYGA1UdEQSBrjCBq4EV
YnVobGVyQGFidWhsZXIuY29tLmJyoD4GBWBMAQMEoDUEMzE0MDkxOTQ2NDA5NDI0OTAwMTAxMDg0
NDcwODE3NTAwMDAwODAzMjkyMjM1NlNTUCBSU6AeBgVgTAEDAqAVBBNOQUlSIEJVSExFUiBTQ0hO
RUNLoBkGBWBMAQMDoBAEDjg5NzE2NTgzMDAwMTY1oBcGBWBMAQMHoA4EDDAwMDAwMDAwMDAwMDCC
ATIGA1UdHwSCASkwggElMIGuoIGroIGohjJodHRwOi8vaWNwLmNhaXhhLmdvdi5ici9yZXBvc2l0
b3Jpby9BQ0NBSVhBUEoxLmNybIY0aHR0cDovL2ljcDIuY2FpeGEuZ292LmJyL3JlcG9zaXRvcmlv
Mi9BQ0NBSVhBUEoxLmNybIY8aHR0cDovL3JlcG9zaXRvcmlvLmljcGJyYXNpbC5nb3YuYnIvbGNy
L2NhaXhhL0FDQ0FJWEFQSjEuY3JsMHKgcKBupGwwajELMAkGA1UEBhMCYnIxEzARBgNVBAoTCklD
UC1CcmFzaWwxIDAeBgNVBAsTF0NhaXhhIEVjb25vbWljYSBGZWRlcmFsMRQwEgYDVQQDEwtBQyBD
QUlYQSBQSjEOMAwGA1UEAxMFQ1JMNDEwHwYDVR0jBBgwFoAUjkAvCv4T1ao5oHZ0htO8fcfx5c8w
CQYDVR0TBAIwADAZBgkqhkiG9n0HQQAEDDAKGwRWNy4xAwIDqDANBgkqhkiG9w0BAQUFAAOCAQEA
nZHUvdnZsiCIDjKm1zHehbtuDtDJha4O4FZ03J74Y+AxyAFs/4JED+xUvZ5jFuEsdqgA0V/dxUFy
Uz/ca10Ievd578GQdGwYl1GFhRtO/SlxeaOEf7eDdGOWXO3VmUA3NmNo0X8RRTIoifnhpDXu7RbN
5sijyH/uXyRFWX9XH2N0U/r3oJtNKXsvoUlbDrkalgkuLzLKsaEj0TkwisXO3cmMoWGuBpAZC+46
e4x/2vTqOvYkzZO+O9NLi0YWSYY7OJKiKBjMC6MzdlPM9VTkIwO9WvWEMdbU0/jhO2cMcVMzNZc1
r6ZmdTDrwqV3elSTkQtJ0RIZNgMJUn+Y8c7Aog==
</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</code>```

Notice the (unwanted) line-breaks.

Any help would be greatly appreciated.

Thanks a lot in advance.

(*) Clarification: the new rule forbids whitespaces (or any other text) between element-only tags. As an example, this would be allowed:

```<code><a><b>
  text
  inside
  tag
</b></a>
</code>```

while this would be forbidden:

```<code><a>
<b>text</b>
</a>
</code>```

because on the latter case, the whitespaces (line-breaks) are between two tags, or, in other words, placed inside an element-only tag.

答:
XML Signature signs part of an XML Document starting with a given element (i.e. a sub tree in DOM)  after it is normalized with a C14N algorithm. The standard C14N algorithm you use preserves line breaks and white spaces (see http://www.w3.org/TR/xml-c14n#Example-WhitespaceInContent).

So all line breaks in the signed part of the original document (including between last tag of data and the <Signature> tag, and between </Signature> and the next closing tag) *must be preserved so as not to alter the signature. The line breaks and spaces in the Signature element itself are not important and may be removed without altering the signature.

Here an example:

```<code><root id="signedpart">
  <data>
     ...
  </data>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
     <SignedInfo>
       <Reference URI="#signedpart">
          ...
       </Reference>
     </SignedInfo>
  </Signature>
</root>
</code>```

Here are your possible options:

define your own C14N algorithm that will remove spaces and line breaks by it self. I would discourage this as the other side must also use this non standard C14N algorithm.

remove line breaks an spaces from you XML before signing it (and potentially remove spaces in signature afterwards)

with the example this will give you the following signed XML:

```<code><root id="signedpart"><data>...</data><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
       <Reference URI="#signedpart">
          ...
       </Reference>
     </SignedInfo>
  </Signature></root>
</code>```

and after removing spaces in signature

```<code><root id="signedpart"><data>...</data><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><Reference URI="#signedpart">...</Reference></SignedInfo></Signature></root>
</code>```

Body:
I work with the brazilian "Nota Fiscal Eletronica" project, in which they define a standart way to sign XML documents.

Recently, they started to require that there are absolutely no whitespaces between tags, including signature tags (*).

We happen to use apache's XMLSignature and I can't seem to produce an unindented signature.

If I remove the whitespaces after signing, the signature gets broken.

I cannot change the canonicalizer / transformers set either, since they're predefined.

I couldn't find an option or parameter in the XMLSignature API to control indentation or whitespaces.

Below is the code:

    // the element where to insert the signature
    Element element = ...;
    X509Certificate cert = ...;
    PrivateKey privateKey = ...;

    XMLSignature signer =
            new XMLSignature(doc, "http://xml-security",
            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);

    element.appendChild(signer.getElement());

    Transforms transforms = new Transforms(doc);

    // Define as regras de transformação e canonicalização do documento
    // XML, necessário para fazer a verificação do parsing e da
    // assinatura pelos destinatários
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); //, xpath.getElementPlusReturns());

    transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS); //,xpath.getElementPlusReturns());

    String id = "";

    id = ((Element) element.getElementsByTagName("infNFe").item(0)).getAttributeNode("Id").getNodeValue();

    signer.addDocument("#" + id, transforms,
                       Constants.ALGO_ID_DIGEST_SHA1);
    signer.addKeyInfo(cert);
    signer.sign(privateKey);

And below is the resulting signature (snippet):

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#NFe43110189716583000165550010000076011492273645">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>fas0ra5uRskQgRHSrIYhEjFEjKQ=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
2RGltUZy0HfNoiKtVanAeN+JUPyglWDuQNnMudSgA7kESoHBZ/q/GMbc+xMSN1eV8u7+2PxSKl1T
Zl592FWmCSAkL8pwMujDxJ4iTLU20Hf0dNF7oGcyB+g9GgbipW2udq0kwJLz6HzXUD/Evf/0y+3T
NtsXeIaA6A29ttD/UEs=
</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>
MIIFqTCCBJGgAwIBAgIEQeNSuzANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJicjETMBEGA1UE
ChMKSUNQLUJyYXNpbDEgMB4GA1UECxMXQ2FpeGEgRWNvbm9taWNhIEZlZGVyYWwxFDASBgNVBAMT
C0FDIENBSVhBIFBKMB4XDTEwMDYwODE5MjQwNVoXDTExMDYwODE5NTQwNVowgYQxCzAJBgNVBAYT
AmJyMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMSAwHgYDVQQLExdDYWl4YSBFY29ub21pY2EgRmVkZXJh
bDEUMBIGA1UECxMLQUMgQ0FJWEEgUEoxKDAmBgNVBAMTH0EgQlVITEVSIFNBIENVUlRVTUU6NDA5
NDI0OTAwMTAwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOFxgvG35RQWgXec4zVrzoUHolnJ
fP76rpO2Vo40593W9Gf0WwHt36gVmli0ZeQitFmzFSoE5KhgXQGZg6RpV3WJUFcIrPBHPdqOSfiB
988kf962P+j8fZ38BNmo7TV9H9hMBkV9bD/QOe73wFDc+rT6/9io++Z+7/wup/3glKntAgMBAAGj
ggLOMIICyjAOBgNVHQ8BAf8EBAMCBeAwVwYDVR0gBFAwTjBMBgZgTAECAQkwQjBABggrBgEFBQcC
ARY0aHR0cDovL2ljcC5jYWl4YS5nb3YuYnIvcmVwb3NpdG9yaW8vZHBjYWNjYWl4YXBqLnBkZjAp
BgNVHSUEIjAgBggrBgEFBQcDAgYIKwYBBQUHAwQGCisGAQQBgjcUAgIwgbYGA1UdEQSBrjCBq4EV
YnVobGVyQGFidWhsZXIuY29tLmJyoD4GBWBMAQMEoDUEMzE0MDkxOTQ2NDA5NDI0OTAwMTAxMDg0
NDcwODE3NTAwMDAwODAzMjkyMjM1NlNTUCBSU6AeBgVgTAEDAqAVBBNOQUlSIEJVSExFUiBTQ0hO
RUNLoBkGBWBMAQMDoBAEDjg5NzE2NTgzMDAwMTY1oBcGBWBMAQMHoA4EDDAwMDAwMDAwMDAwMDCC
ATIGA1UdHwSCASkwggElMIGuoIGroIGohjJodHRwOi8vaWNwLmNhaXhhLmdvdi5ici9yZXBvc2l0
b3Jpby9BQ0NBSVhBUEoxLmNybIY0aHR0cDovL2ljcDIuY2FpeGEuZ292LmJyL3JlcG9zaXRvcmlv
Mi9BQ0NBSVhBUEoxLmNybIY8aHR0cDovL3JlcG9zaXRvcmlvLmljcGJyYXNpbC5nb3YuYnIvbGNy
L2NhaXhhL0FDQ0FJWEFQSjEuY3JsMHKgcKBupGwwajELMAkGA1UEBhMCYnIxEzARBgNVBAoTCklD
UC1CcmFzaWwxIDAeBgNVBAsTF0NhaXhhIEVjb25vbWljYSBGZWRlcmFsMRQwEgYDVQQDEwtBQyBD
QUlYQSBQSjEOMAwGA1UEAxMFQ1JMNDEwHwYDVR0jBBgwFoAUjkAvCv4T1ao5oHZ0htO8fcfx5c8w
CQYDVR0TBAIwADAZBgkqhkiG9n0HQQAEDDAKGwRWNy4xAwIDqDANBgkqhkiG9w0BAQUFAAOCAQEA
nZHUvdnZsiCIDjKm1zHehbtuDtDJha4O4FZ03J74Y+AxyAFs/4JED+xUvZ5jFuEsdqgA0V/dxUFy
Uz/ca10Ievd578GQdGwYl1GFhRtO/SlxeaOEf7eDdGOWXO3VmUA3NmNo0X8RRTIoifnhpDXu7RbN
5sijyH/uXyRFWX9XH2N0U/r3oJtNKXsvoUlbDrkalgkuLzLKsaEj0TkwisXO3cmMoWGuBpAZC+46
e4x/2vTqOvYkzZO+O9NLi0YWSYY7OJKiKBjMC6MzdlPM9VTkIwO9WvWEMdbU0/jhO2cMcVMzNZc1
r6ZmdTDrwqV3elSTkQtJ0RIZNgMJUn+Y8c7Aog==
</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>

Notice the (unwanted) line-breaks.

Any help would be greatly appreciated.

Thanks a lot in advance.

(*) Clarification: the new rule forbids whitespaces (or any other text) between element-only tags. As an example, this would be allowed:

  text
  inside
  tag

while this would be forbidden:

text

because on the latter case, the whitespaces (line-breaks) are between two tags, or, in other words, placed inside an element-only tag.

Body:
XML Signature signs part of an XML Document starting with a given element (i.e. a sub tree in DOM)  after it is normalized with a C14N algorithm. The standard C14N algorithm you use preserves line breaks and white spaces (see http://www.w3.org/TR/xml-c14n#Example-WhitespaceInContent).

So all line breaks in the signed part of the original document (including between last tag of data and the <Signature> tag, and between </Signature> and the next closing tag) *must be preserved so as not to alter the signature. The line breaks and spaces in the Signature element itself are not important and may be removed without altering the signature.

Here an example:

<root id="signedpart">
  <data>
     ...
  </data>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
     <SignedInfo>
       <Reference URI="#signedpart">
          ...
       </Reference>
     </SignedInfo>
  </Signature>
</root>

Here are your possible options:

define your own C14N algorithm that will remove spaces and line breaks by it self. I would discourage this as the other side must also use this non standard C14N algorithm.

remove line breaks an spaces from you XML before signing it (and potentially remove spaces in signature afterwards)

with the example this will give you the following signed XML:

<root id="signedpart"><data>...</data><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
       <Reference URI="#signedpart">
          ...
       </Reference>
     </SignedInfo>
  </Signature></root>

and after removing spaces in signature

<root id="signedpart"><data>...</data><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><Reference URI="#signedpart">...</Reference></SignedInfo></Signature></root>


问:
android, go back to the saved data after selection in the listview
In android studio, I have an activity called ADD that let the user enter his name and birthday. when the user click on ok button the data will be saved to SQLDatabase, and then the data will be displayed in another activity in a listview. what i want is: when the user is in listview activity and click on any item of this listview , i want to take him back to the ADD activity with the saved data not with the default data.<br>
anyone here have a solution please? </p>

答:
You can start ADD activity using startActivity() with Intent containing the required data and check for that intent data in onCreate() of ADD activity.
If intent data is null then it means user started that activity without clicking on list item and if you get intent data , then you can extract the values you put and populate the fields with those values.

Example = 1st case :

startActivity(new Intent(this, AddActivity.class));

2nd case(when you click on list item) :

startActivity(new Intent(this, AddActivity.class).putExtra("name", "your_name").putExtra("d_o_b", <your_date_of_birth>));

And then get these data in onCreate() using getIntent()

Check getIntent(). If it's null then it's the usual flow else you grab values from it using -

getIntent().getStringExtra("name")

and follow the same procedure for dob and popluate your views using these values

Body:
In android studio, I have an activity called ADD that let the user enter his name and birthday. when the user click on ok button the data will be saved to SQLDatabase, and then the data will be displayed in another activity in a listview. what i want is: when the user is in listview activity and click on any item of this listview , i want to take him back to the ADD activity with the saved data not with the default data.

anyone here have a solution please?


问:
Rails query all records whose all associated record has nil or some specific value in some specific fields
I have two models with a has_many and belongs_to relations:

```<code>class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end
</code>```

How do I find all those Parents whose all children have nil value in some specific field.

答:
Can you join the child table and then check for your attribute_to_test being nil?

@nillish_parents = Parent.joins(:children).where("child.attribute_to_test IS ?", nil)

```<code>@nillish_parents.each do |p|
    p.name
end
</code>```

Body:
I have two models with a has_many and belongs_to relations:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

How do I find all those Parents whose all children have nil value in some specific field.

Body:
Can you join the child table and then check for your attribute_to_test being nil?

@nillish_parents = Parent.joins(:children).where("child.attribute_to_test IS ?", nil)

@nillish_parents.each do |p|
    p.name
end


问:
Change background color but always get error that App has stopped
```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null object reference.
</code>```

This is what I get when I run the program and I don't know what to do.
I read the others post but still don't know what the problem is.I replaced the "v" in "public void onClick(View v)" with "findViewById" but still no working.

```<code>package com.example.gia.applumini;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
        bgElement.setBackgroundColor(Color.RED);
        myButtonListenerMethod();
    }

    public void myButtonListenerMethod() {
        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
                int color = ((ColorDrawable) bgElement.getBackground()).getColor();
                if (color == Color.RED) {
                    bgElement.setBackgroundColor(Color.BLUE);
                }
                else {
                    bgElement.setBackgroundColor(Color.RED);
                }
            }
        });
    }
}
</code>```

答:
Try to adjust your code to be like the following :</p>

```<code>public class MainActivity extends AppCompatActivity {

RelativeLayout bgElement;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bgElement = (RelativeLayout) findViewById(R.id.RELATIVELAYOUTID);
        bgElement.setBackgroundColor(Color.RED);
        myButtonListenerMethod();
    }

    public void myButtonListenerMethod() {
        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int color = ((ColorDrawable) bgElement.getBackground()).getColor();
                if (color == Color.RED) {
                    bgElement.setBackgroundColor(Color.BLUE);
                }
                else {
                    bgElement.setBackgroundColor(Color.RED);
                }
            }
        });
    }
}
</code>```

Body:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null object reference.

This is what I get when I run the program and I don't know what to do.
I read the others post but still don't know what the problem is.I replaced the "v" in "public void onClick(View v)" with "findViewById" but still no working.

package com.example.gia.applumini;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
        bgElement.setBackgroundColor(Color.RED);
        myButtonListenerMethod();
    }

    public void myButtonListenerMethod() {
        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
                int color = ((ColorDrawable) bgElement.getBackground()).getColor();
                if (color == Color.RED) {
                    bgElement.setBackgroundColor(Color.BLUE);
                }
                else {
                    bgElement.setBackgroundColor(Color.RED);
                }
            }
        });
    }
}

Body:
Try to adjust your code to be like the following :

public class MainActivity extends AppCompatActivity {

RelativeLayout bgElement;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bgElement = (RelativeLayout) findViewById(R.id.RELATIVELAYOUTID);
        bgElement.setBackgroundColor(Color.RED);
        myButtonListenerMethod();
    }

    public void myButtonListenerMethod() {
        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int color = ((ColorDrawable) bgElement.getBackground()).getColor();
                if (color == Color.RED) {
                    bgElement.setBackgroundColor(Color.BLUE);
                }
                else {
                    bgElement.setBackgroundColor(Color.RED);
                }
            }
        });
    }
}


问:
How to read variables from an external file?
I'm attempting to learn Python and at this point, I am very confused.  Here's what I'm attempting to do:

I have a Python script that needs to call variables from an external file.  The external data file cannot reside in the same folder as the Python script. The location of the data file is currently /Users/discoveryone/Documents (this will be running on a Macintosh). Here's the contents of the data file:

domains='apple.com', 'google.com', 'yahoo.com', 'aol.com', 'disney.com', 'mydomain.com', 'hotmail.com'
email='noone1@nowhere.com'
smtpserver='smtp.mydomain.com'
smtpport='465'
smtpto='noone1@nowhere.com'
smtpfrom='noone2@nowhere.com'
```

I need to call the all of the values in the domains field and then process them through a while loop individually and use the other data if need be.

Can someone please help me to call the external data file into my Python script?

答:
Assuming your file is called file.txt, you can add all those variables to the global scope with:

```<code>with open("/Users/discoveryone/Documents/file.txt") as f:
    for l in f:
        var, val = l.split("=")
        globals()[var] = val.strip().replace("'", "")
</code>```

and then you could access email for instance and it would have the value:

```<code>'noone1@nowhere.com'
</code>```

The only problem with this is that domains is only a string of the domains:

```<code>'apple.com, google.com, yahoo.com, aol.com, disney.com, mydomain.com, hotmail.com'
</code>```

to convert this to a list of domains, simply add the line:

```<code>domains = [d.strip() for d in domains.split(",")]
</code>```

which will modify domains to:

```<code>['apple.com', 'google.com', 'yahoo.com', 'aol.com', 'disney.com', 'mydomain.com', 'hotmail.com']
</code>```

Body:
I'm attempting to learn Python and at this point, I am very confused.  Here's what I'm attempting to do:

I have a Python script that needs to call variables from an external file.  The external data file cannot reside in the same folder as the Python script. The location of the data file is currently /Users/discoveryone/Documents (this will be running on a Macintosh). Here's the contents of the data file:

domains='apple.com', 'google.com', 'yahoo.com', 'aol.com', 'disney.com', 'mydomain.com', 'hotmail.com'
email='noone1@nowhere.com'
smtpserver='smtp.mydomain.com'
smtpport='465'
smtpto='noone1@nowhere.com'
smtpfrom='noone2@nowhere.com'

I need to call the all of the values in the domains field and then process them through a while loop individually and use the other data if need be.

Can someone please help me to call the external data file into my Python script?

Body:
Assuming your file is called file.txt, you can add all those variables to the global scope with:

with open("/Users/discoveryone/Documents/file.txt") as f:
    for l in f:
        var, val = l.split("=")
        globals()[var] = val.strip().replace("'", "")

and then you could access email for instance and it would have the value:

'noone1@nowhere.com'

The only problem with this is that domains is only a string of the domains:

'apple.com, google.com, yahoo.com, aol.com, disney.com, mydomain.com, hotmail.com'

to convert this to a list of domains, simply add the line:

domains = [d.strip() for d in domains.split(",")]

which will modify domains to:

['apple.com', 'google.com', 'yahoo.com', 'aol.com', 'disney.com', 'mydomain.com', 'hotmail.com']


问:
Prevent "Send error report to Microsoft"
I'm working on a rather large project, and its unlikely will catch everything. I've found the event that notifies me of unhandled exceptions, however I haven't found a way to programmatically shut off the windows error dialog. Ideally, if there is an unhandled exception, I would like to have that event fired, provide a dialog box telling the user that there is a problem, and then to close gracefully. Is there any way to do this? I realize I could wrap the highest layer in a try catch, but I was hoping for something a little more elegant. </p>

答: You sort of answered your own question. The best way to prevent the error dialog is to write code that handles your exceptions so the dialog will never appear. I would wager this is what Raymond Chen would suggest (if I may be so bold).</p>

OwnerDisplayName: Steve

LastEditorDisplayName: Rich B

OwnerDisplayName: Out Into Space


问:
Should I store high-throughput, structured sensor data in redux store?
I've recently started using React and so far I have built a couple of apps, including one realtime application for manipulating and visualising sensor data. This data consists in high-throughput, structured JSON frames coming from websockets at 100Hz-200Hz.

As my app is quickly growing in complexity, and after learning about Redux through official docs and Dan Abramov's courses, I have found the use of Redux very compelling to manage the visual state of the app, routing, server information, etc.

In my React-non-Redux app everything is kept in local state, but this had a cost in the architectural design. Now, I would like to start refactoring the app to integrate redux. With my limited knowledge at this point, I'm stuck at this architectural decision about  where to store the sensors streams' data and the impact on the application rendering and processing performance.

In redux docs there rules of thumb for determining what kind of data should be put into Redux:

Do other parts of the application care about this data? [YES]

Do you need to be able to create further derived data based on this
original data? [YES]

Is the same data being used to drive multiple components? [YES]

Is there value to you in being able to restore this state to a given
point in time (ie, time travel debugging)? [YES]

Do you want to cache the data (ie, use what's in state if it's
already there instead of re-requesting it)? [MAYBE]

There have been a couple of threads discussing this, but without any definitive answer. I'm also unable to comment on this (SO noob here):

Should I be concerned with the rate of state change in my React Redux app?

Visualizing ImmutableJS data from Redux store in a graph

I have discovered many different ramifications that I need to learn, including middleware, RxJS, etc. I would like to push development further, but as all of this will take time to grasp, I would like to refer to the community for some directions.

Thanks in advance!

答:
I'm currently using redux to provide data for widgets and I would say the incoming rate is somewhere around 80-90 hertz and I'm still getting 60 fps on widget canvas'. Like Dan said in his post, there is nothing inherently slow about using redux. However updating your UI 200 times a second is completely unnecessary, I would at least add some middleware (if you don't want to have a server) to redux to congregate updates to at most 60 times a second. Redux might not be that slow but trying to render 200 times a second certainly will be.

I will say however that I recently had to make the same decision you are and saving the datastreams in redux made accessing them across my application much simpler.

I found that using web workers was a good way of combining data into a single update. If you haven't already I would check them out https://developer.mozilla.org/en-US/docs/Web/API/Worker. If you decide to go in that direction it will probably help a lot with performance since the workers will be handling the websocket connections directly and causing action dispatches to redux in a more controlled manner.


问:
How do I add multiple inputs from a prompt in an array together?
I was instructed to create a program that takes 10 numbers from a user. Then it should display it and find its difference from the average (from the 10 numbers inputted.) I've messed around with the code for a while but I'm not sure what I'm doing wrong. When I open in browser, the calculations aren't correct. </p>

```<code>var number = new Array(10);
for(var i=0; i<10; i++) {
var number = prompt("PLEASE ENTER A NUMBER");
total =  parseInt(number);
average = total/10;
document.write("The difference from the average for the number, " + number +
"is equal to " + (number - average) +  "<br>");
}
</code>```

答:
At first you don't need an array at all, you just need the total summed up:

var total = 0;

for (var count = 1; count <= 10; count++) {
  const number = parseInt(prompt("A number (again):"));
  //increase total by the inputted number
  total += number;
  const average = total / count;
  document.body.innerHTML += `The ${count} number is ${number}, the average is ${average} and they differ by ${average - number}`;
}```

You may notice that I've used const as much as possible ( cause constant things are better to handle ), as well as a template literal ( the ${..} stuff ) which makes it more readable in my opinion.

Body:
I was instructed to create a program that takes 10 numbers from a user. Then it should display it and find its difference from the average (from the 10 numbers inputted.) I've messed around with the code for a while but I'm not sure what I'm doing wrong. When I open in browser, the calculations aren't correct.

var number = new Array(10);
for(var i=0; i<10; i++) {
var number = prompt("PLEASE ENTER A NUMBER");
total =  parseInt(number);
average = total/10;
document.write("The difference from the average for the number, " + number +
"is equal to " + (number - average) +  "
");
}

Body:
At first you don't need an array at all, you just need the total summed up:

var total = 0;

for (var count = 1; count <= 10; count++) {
  const number = parseInt(prompt("A number (again):"));
  //increase total by the inputted number
  total += number;
  const average = total / count;
  document.body.innerHTML += `The ${count} number is ${number}, the average is ${average} and they differ by ${average - number}`;
}

You may notice that I've used const as much as possible ( cause constant things are better to handle ), as well as a template literal ( the ${..} stuff ) which makes it more readable in my opinion.


问:
the performance of php fread and echo is very bad
I write a php script named 'download.php' to push files to client,

```<code>$fd = fopen($path, "rb");
if ($fd === false) {
    echo "404 file not found";
    return false;
}

Header("Content-type: image/png");

while (!feof($fd))
{
    $buf = fread($fd, 1024);
    if ($buf === false) {
        break;
    }
    echo $buf;
}

fclose($fd);
</code>```

When I test on chrome to download a 4M image, it will consume 1.4s.
the apache server is on my PC. if I put the image in www/ and download it directly, that only consume 44ms.

I tried to increase the bufsize of fread, but it just improve performance a little.

答: fpassthru($fd) is a much more efficient way to pass the contents of a stream to php://output without loading the entire file contents into memory</p>

Body:
I write a php script named 'download.php' to push files to client,

$fd = fopen($path, "rb");
if ($fd === false) {
    echo "404 file not found";
    return false;
}

Header("Content-type: image/png");

while (!feof($fd))
{
    $buf = fread($fd, 1024);
    if ($buf === false) {
        break;
    }
    echo $buf;
}

fclose($fd);

When I test on chrome to download a 4M image, it will consume 1.4s.
the apache server is on my PC. if I put the image in www/ and download it directly, that only consume 44ms.

I tried to increase the bufsize of fread, but it just improve performance a little.


问:
ARCore: Am I restrained to using large, flat surfaces?
I know that ARCore can detect flat surfaces like floors and tables, but can it detect other, less regular objects? Say I have a chair and a stool sitting on the ground in front of me. Could ARCore detect these 2 objects in any way? Am I restrained to using large, flat surfaces when designing AR experiences with ARCore?

If there is any documentation about detecting real-world objects I would much appreciate a pointer to it.

Any advice would be helpful. :) Thanks.

答:
ARCore can only detect horizontal surfaces at the moment.  Vertical surfaces like walls and objects are not supported.

However, Tango devices have better support through extra hardware like dual cameras and infrared sensors
Watch this https://www.youtube.com/watch?v=rFbcOGuDMPk