问:
Best way to query relational collections in mongodb?
For example, i have 2 collections:

First one is named as "Songs" and documents in this collection store all metadata about song like title, duration, release_date and other. Beside this, there are also artist and producer fields, these fields stores ids of relational documents from "Stars" collection.

Example of document in "Songs" collection:

```<code>{
   id: SONG_ID
   title: TITLE,
   duration: DURATION,
   release_date: ISO_DATE,
   ...
   artist: STAR_ID
   producer: STAR_ID
}
</code>```

Second one as you guess is "Stars" collection and documents in this collection store information about stars like fullname, date_of_birth and other.

Example of document in "Stars" collection:

```<code>{
   id: STAR_ID
   fullname: FULLNAME,
   date_of_birth: DATE_OF_BIRTH
   ...
}
</code>```

Suppose i want to find songs that (1 condition) have "love" word in their titles, (2 condition) released in 2017 year and (3 condition) from artists like Rihanna or Zara Larsson. Please note that my problem is different from simple left outer join. Note that in this query 3rd condition relates to information that stored in second collection "Stars", so i dont want just pollute artist and producer fields with information from "Stars" collection but also i want to choose songs with stars just like Rihanna or Zara Larsson.

What is the best and fastest way to do this?

Thanks for your help!

答:
You can use below aggregation query.

$match on release_date and $regex match on title.

$lookup to look up artist collection followed by $match on fullname for input values.

```<code>db.Songs.aggregate([
 { "$match":{ "release_date": { "$gte": ISODate("2017-01-01T00:00:00.000Z"), "$lt": ISODate("2018-01-01T00:00:00.000Z")}, title: { $regex: /love$/ } } },
 { "$lookup": {
       "from" : "Stars",
       "localField" : "artist",
       "foreignField" : "_id",
       "as" : "star"
    }
 },
 { "$match" : { "star.fullname" : { "$in": [ "Rihanna", "Zara Larsson" ] } } }
])
</code>```

Regex can make use of index when anchored. Compare with text search.

Body:
For example, i have 2 collections:

First one is named as "Songs" and documents in this collection store all metadata about song like title, duration, release_date and other. Beside this, there are also artist and producer fields, these fields stores ids of relational documents from "Stars" collection.

Example of document in "Songs" collection:

{
   id: SONG_ID
   title: TITLE,
   duration: DURATION,
   release_date: ISO_DATE,
   ...
   artist: STAR_ID
   producer: STAR_ID
}

Second one as you guess is "Stars" collection and documents in this collection store information about stars like fullname, date_of_birth and other.

Example of document in "Stars" collection:

{
   id: STAR_ID
   fullname: FULLNAME,
   date_of_birth: DATE_OF_BIRTH
   ...
}

Suppose i want to find songs that (1 condition) have "love" word in their titles, (2 condition) released in 2017 year and (3 condition) from artists like Rihanna or Zara Larsson. Please note that my problem is different from simple left outer join. Note that in this query 3rd condition relates to information that stored in second collection "Stars", so i dont want just pollute artist and producer fields with information from "Stars" collection but also i want to choose songs with stars just like Rihanna or Zara Larsson.

What is the best and fastest way to do this?

Thanks for your help!

Body:
You can use below aggregation query.

$match on release_date and $regex match on title.

$lookup to look up artist collection followed by $match on fullname for input values.

db.Songs.aggregate([
 { "$match":{ "release_date": { "$gte": ISODate("2017-01-01T00:00:00.000Z"), "$lt": ISODate("2018-01-01T00:00:00.000Z")}, title: { $regex: /love$/ } } },
 { "$lookup": {
       "from" : "Stars",
       "localField" : "artist",
       "foreignField" : "_id",
       "as" : "star"
    }
 },
 { "$match" : { "star.fullname" : { "$in": [ "Rihanna", "Zara Larsson" ] } } }
])

Regex can make use of index when anchored. Compare with text search.


来源: stackexchange

问:
how to send ajax request in jQuery with data encoded
when i send ajax request i got the error that

```<code> $.ajax({
                        type: "POST",
                        url: furl2,
                        cache: false,
                        contentType: "application/json;charset=utf-8",
                        data: { id: id, url: $("#id" + id + " .customURL").val() },
                        success: function (msg) {
                          //some code here
                        },
                    });
                }
</code>```

i got the error that id is undefined even i put them.

how i can send a ajax request to server using ajax.

答:
In JSON it's

```<code>String : value
</code>```

Try adding quotes around your field names, e.g.

```<code>{
  "type": "POST",
  "url": furl2,
  "something": "else",
  "fortytwo": 42
}
</code>```

Edit: There's a comma after your success function that seems to do nothing. Have you checked that?

OwnerDisplayName: Steven Spielberg

ContentLicense: CC BY-SA 2.5

Body:
when i send ajax request i got the error that

 $.ajax({
                        type: "POST",
                        url: furl2,
                        cache: false,
                        contentType: "application/json;charset=utf-8",
                        data: { id: id, url: $("#id" + id + " .customURL").val() },
                        success: function (msg) {
                          //some code here
                        },
                    });
                }

i got the error that id is undefined even i put them.

how i can send a ajax request to server using ajax.

Body:
In JSON it's

String : value

Try adding quotes around your field names, e.g.

{
  "type": "POST",
  "url": furl2,
  "something": "else",
  "fortytwo": 42
}

Edit: There's a comma after your success function that seems to do nothing. Have you checked that?


问:
ios keyboard is not hiding on resignfirstresponder
Added a subview on App delegate window, textfield is in subview, startDateTxtFld will open date picker but date picker remains behind the keyboard. keyboard does not hide on resignFirstResponder or self.view eneEditing setting as true.

```<code>-(void)textFieldDidBeginEditing:(UITextField *)textField
{

    if (textField == startDateTxtFld )
    {
        startDateSelected =YES;
        endDateSelected = NO;
//        [referenceNmbrTxtFld resignFirstResponder];
     //   [startDateTxtFld becomeFirstResponder];
        //textField.inputView=datePicker;
       // [self.view endEditing:YES];
       // [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
//       [APP_DELEGATE.window resignFirstResponder];
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        [UIView animateWithDuration:0.5 animations:^
        {
            [startDateTxtFld resignFirstResponder];
            _bottomGap4DatePicker.constant=0;
            datePicker.backgroundColor=[UIColor whiteColor];
           // [_subVw4DtPkr becomeFirstResponder];
        }];
       [self.navigationController.view endEditing:YES];
    }
    else if (textField == endDateTxtFld)
    {
        startDateSelected =NO;
        endDateSelected = YES;
       // [self.view endEditing:YES];
//        [referenceNmbrTxtFld resignFirstResponder];
       // [endDateTxtFld becomeFirstResponder];
      //  textField.inputView=datePicker;
      //  [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
//        [APP_DELEGATE.window resignFirstResponder];
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        [UIView animateWithDuration:0.5 animations:^
         {
            // [endDateTxtFld resignFirstResponder];
             _bottomGap4DatePicker.constant=0;
             datePicker.backgroundColor=[UIColor whiteColor];
             //[_subVw4DtPkr becomeFirstResponder];
         }];
        [self.navigationController.view endEditing:YES];
    }
   else
    {
        [textField becomeFirstResponder];
        _bottomGap4DatePicker.constant=[UIScreen mainScreen].bounds.size.height +_subVw4DtPkr.frame.size.height;
        _popUpVwConstraint.constant=-30;
    }

}
</code>```

答:
I tried all the solution, like adding

UITextFieldDelegate

tf_edit.returnKeyType = UIReturnKeyDone

```<code>- (BOOL)disablesAutomaticKeyboardDismissal
{
     return NO;
}
</code>```

Nothing helped.

textFieldShouldReturn was being called. but keyboard was not appearing. I read that it is going to some other textfield when I am clicking DONE button. But there was no other textfield. So instead of applying resignFirstResponder to my textfield name, I applied to the textfield which is a parameter of textFieldShouldReturn function and it worked. I am not sure if it is correct way. It worked for me.

```<code>-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //[tf_edit resignFirstResponder];
    [textField resignFirstResponder];
    return YES;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Added a subview on App delegate window, textfield is in subview, startDateTxtFld will open date picker but date picker remains behind the keyboard. keyboard does not hide on resignFirstResponder or self.view eneEditing setting as true.

-(void)textFieldDidBeginEditing:(UITextField *)textField
{

    if (textField == startDateTxtFld )
    {
        startDateSelected =YES;
        endDateSelected = NO;
//        [referenceNmbrTxtFld resignFirstResponder];
     //   [startDateTxtFld becomeFirstResponder];
        //textField.inputView=datePicker;
       // [self.view endEditing:YES];
       // [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
//       [APP_DELEGATE.window resignFirstResponder];
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        [UIView animateWithDuration:0.5 animations:^
        {
            [startDateTxtFld resignFirstResponder];
            _bottomGap4DatePicker.constant=0;
            datePicker.backgroundColor=[UIColor whiteColor];
           // [_subVw4DtPkr becomeFirstResponder];
        }];
       [self.navigationController.view endEditing:YES];
    }
    else if (textField == endDateTxtFld)
    {
        startDateSelected =NO;
        endDateSelected = YES;
       // [self.view endEditing:YES];
//        [referenceNmbrTxtFld resignFirstResponder];
       // [endDateTxtFld becomeFirstResponder];
      //  textField.inputView=datePicker;
      //  [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
//        [APP_DELEGATE.window resignFirstResponder];
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        [UIView animateWithDuration:0.5 animations:^
         {
            // [endDateTxtFld resignFirstResponder];
             _bottomGap4DatePicker.constant=0;
             datePicker.backgroundColor=[UIColor whiteColor];
             //[_subVw4DtPkr becomeFirstResponder];
         }];
        [self.navigationController.view endEditing:YES];
    }
   else
    {
        [textField becomeFirstResponder];
        _bottomGap4DatePicker.constant=[UIScreen mainScreen].bounds.size.height +_subVw4DtPkr.frame.size.height;
        _popUpVwConstraint.constant=-30;
    }

}

Body:
I tried all the solution, like adding

UITextFieldDelegate

tf_edit.returnKeyType = UIReturnKeyDone

- (BOOL)disablesAutomaticKeyboardDismissal
{
     return NO;
}

Nothing helped.

textFieldShouldReturn was being called. but keyboard was not appearing. I read that it is going to some other textfield when I am clicking DONE button. But there was no other textfield. So instead of applying resignFirstResponder to my textfield name, I applied to the textfield which is a parameter of textFieldShouldReturn function and it worked. I am not sure if it is correct way. It worked for me.

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //[tf_edit resignFirstResponder];
    [textField resignFirstResponder];
    return YES;
}


问:
Intellij plugin Fortran
I have installed Intellij IDEA Version 2017.1.4 and installed the Fortran plugin. However, I don't see an option of starting a Fortran project even after restarting IntelliJ. I see the plugin has been successfully installed though.

Is there a simple hello-world fortran example with Intellij?

Thank you

答:
No, you can't create a Fortran project in Intellij IDEA. You can use cmake to build you project and import such project in CLion. Here you can find some information about compiling Fortran project with CMake. Also several example projects can be easily found in the Internet.

General idea behind this is that IDE is not a build tool, so you are building your project with build tools and we are doing our best to support build tool that you're using. For now from all JetBrains IDEs only CLion supports build tool that is capable of compiling Fortran project (CMake). In the future CLion will support other build tools capable of doing this (make for example).

Title: Intellij plugin Fortran


问:
Login functionality in cassandra database
I have a user table(column family) with userId as primary key, it also has other details like emailId, password, username etc.

My doubt is when user login using emailId, how to look for password in the table as my primary key is userId not emailId?

or is it better to create emailId is primary key?

or additional table for mapping userId with emailId?

答:
Assuming your Cassandra version supports Materialized View (3.x), here is what can be easily done

Say your original table schema is the following with userId being the primary key

```<code>create table userdetails_by_id
(userId text primary key,
 emailId text,
 password text,
 username text);
</code>```

Create a materialized view, where emailId would be the primary key and would contain all the other fields from main table. Here is its definition

```<code>create materialized view userdetails_by_emailid
as select
userId,
emailId,
password,
username
from userdetails_by_id
where userId is not null and emailId is not null
primary key (emailId, userId);
</code>```

Now when the query is against userId, you can route it to the main table and query against emailId can be routed to the materialized view. This way Cassandra will keep the data in sync and extra application code isn't necessary to maintain two tables.

Body:
Assuming your Cassandra version supports Materialized View (3.x), here is what can be easily done

Say your original table schema is the following with userId being the primary key

create table userdetails_by_id
(userId text primary key,
 emailId text,
 password text,
 username text);

Create a materialized view, where emailId would be the primary key and would contain all the other fields from main table. Here is its definition

create materialized view userdetails_by_emailid
as select
userId,
emailId,
password,
username
from userdetails_by_id
where userId is not null and emailId is not null
primary key (emailId, userId);

Now when the query is against userId, you can route it to the main table and query against emailId can be routed to the materialized view. This way Cassandra will keep the data in sync and extra application code isn't necessary to maintain two tables.


问:
How to parse an XML document with Nokogiri
I am trying to parse an XML file using Nokogiri in Ruby on Rails:

```<code><ItemID>
    <SupplierPartID>GH-CF-BINDER</SupplierPartID>
  </ItemID>
  <ItemDetail>
    <UnitPrice><Money currency="USD"></Money></UnitPrice>
    <Description xml:lang="en">Ghent Contract Furniture Binder</Description>
    <UnitOfMeasure>Each</UnitOfMeasure>
    <Classification domain=""></Classification>
    <Extrinsic name="tag">GH-CF-BINDER</Extrinsic>
    <Extrinsic name="bin_number">103/18/9</Extrinsic>
    <Extrinsic name="billing email"></Extrinsic>
    <Extrinsic name="bill_code6"></Extrinsic>
    <Extrinsic name="prodcode"></Extrinsic>
    <Extrinsic name="stock_tag"></Extrinsic>
    <Extrinsic name="has_imprint">N</Extrinsic>
    <Extrinsic name="manuf_id">4117</Extrinsic>
    <Extrinsic name="bill_code1"></Extrinsic>

  </ItemDetail>
</code>```

When I try to parse, instead of receiving a blank value for some blank fields, it instead returns the "name => bill_code1" (for example).

So far my solution is like this but every XML file is slightly different in the layout of the extrinsic tags:

```<code>item_info_params['extrinsic_tag'] = item_info_to_xml['ItemOut']['ItemDetail']['Extrinsic']

#expands from the above param extrinsic_tag because there is 10 elemenets in it
item_info_params['tag'] = item_info_params['extrinsic_tag'][0]
item_info_params['price'] = item_info_params['extrinsic_tag'][1]
item_info_params['bin_number'] = item_info_params['extrinsic_tag'][2]
item_info_params['requested_delivery'] = item_info_params['extrinsic_tag'][3]
item_info_params['billing_email'] = item_info_params['extrinsic_tag'][4]
item_info_params['bill_code6'] = item_info_params['extrinsic_tag'][5]
item_info_params['prodcode'] = item_info_params['extrinsic_tag'][6]
item_info_params['stock_tag'] = item_info_params['extrinsic_tag'][7]
item_info_params['has_imprint'] = item_info_params['extrinsic_tag'][8]
item_info_params['manuf_id'] = item_info_params['extrinsic_tag'][9]
item_info_params['bill_code1'] = item_info_params['extrinsic_tag'][10]
item_info_params['order_id'] = order.id

customer = Customer.create(item_info_params)
</code>```

So, as stated above, item_info_params['bill_code1'] will be assigned to name => bill_code1 instead of a blank value.

It's confusing how to solve this problem.

答:
Meditate on this:

```<code>require 'nokogiri'

EXTRINSIC_NAMES = ['tag', 'bin_number', 'manuf_id']

doc = Nokogiri::XML(<<EOT)
      <ItemDetail>
        <UnitPrice><Money currency="USD"></Money></UnitPrice>
        <Description xml:lang="en">Ghent Contract Furniture Binder</Description>
        <UnitOfMeasure>Each</UnitOfMeasure>
        <Classification domain=""></Classification>
        <Extrinsic name="tag">GH-CF-BINDER</Extrinsic>
        <Extrinsic name="bin_number">103/18/9</Extrinsic>
        <Extrinsic name="billing email"></Extrinsic>
        <Extrinsic name="bill_code6"></Extrinsic>
        <Extrinsic name="prodcode"></Extrinsic>
        <Extrinsic name="stock_tag"></Extrinsic>
        <Extrinsic name="has_imprint">N</Extrinsic>
        <Extrinsic name="manuf_id">4117</Extrinsic>
        <Extrinsic name="bill_code1"></Extrinsic>

      </ItemDetail>
EOT

item_detail = doc.at('ItemDetail')

extrinsic_values = EXTRINSIC_NAMES.map { |name|
  [name, doc.at("Extrinsic[name=#{name}]").text]
}.to_h

extrinsic_values
# => {"tag"=>"GH-CF-BINDER", "bin_number"=>"103/18/9", "manuf_id"=>"4117"}
</code>```

Modify EXTRINSIC_NAMES to select which values you want.

If you want them all then it can be more simple:

```<code>extrinsic_values = doc.css('Extrinsic').map { |node|
  [node['name'], node.text]
}.to_h

extrinsic_values
# => {"tag"=>"GH-CF-BINDER",
#     "bin_number"=>"103/18/9",
#     "billing email"=>"",
#     "bill_code6"=>"",
#     "prodcode"=>"",
#     "stock_tag"=>"",
#     "has_imprint"=>"N",
#     "manuf_id"=>"4117",
#     "bill_code1"=>""}
</code>```

Either way, if your XML files are not formatted the same then you'll have to allow for that in your code.

Body:
I am trying to parse an XML file using Nokogiri in Ruby on Rails:

<ItemID>
    <SupplierPartID>GH-CF-BINDER</SupplierPartID>
  </ItemID>
  <ItemDetail>
    <UnitPrice><Money currency="USD"></Money></UnitPrice>
    <Description xml:lang="en">Ghent Contract Furniture Binder</Description>
    <UnitOfMeasure>Each</UnitOfMeasure>
    <Classification domain=""></Classification>
    <Extrinsic name="tag">GH-CF-BINDER</Extrinsic>
    <Extrinsic name="bin_number">103/18/9</Extrinsic>
    <Extrinsic name="billing email"></Extrinsic>
    <Extrinsic name="bill_code6"></Extrinsic>
    <Extrinsic name="prodcode"></Extrinsic>
    <Extrinsic name="stock_tag"></Extrinsic>
    <Extrinsic name="has_imprint">N</Extrinsic>
    <Extrinsic name="manuf_id">4117</Extrinsic>
    <Extrinsic name="bill_code1"></Extrinsic>

  </ItemDetail>

When I try to parse, instead of receiving a blank value for some blank fields, it instead returns the "name => bill_code1" (for example).

So far my solution is like this but every XML file is slightly different in the layout of the extrinsic tags:

item_info_params['extrinsic_tag'] = item_info_to_xml['ItemOut']['ItemDetail']['Extrinsic']

#expands from the above param extrinsic_tag because there is 10 elemenets in it
item_info_params['tag'] = item_info_params['extrinsic_tag'][0]
item_info_params['price'] = item_info_params['extrinsic_tag'][1]
item_info_params['bin_number'] = item_info_params['extrinsic_tag'][2]
item_info_params['requested_delivery'] = item_info_params['extrinsic_tag'][3]
item_info_params['billing_email'] = item_info_params['extrinsic_tag'][4]
item_info_params['bill_code6'] = item_info_params['extrinsic_tag'][5]
item_info_params['prodcode'] = item_info_params['extrinsic_tag'][6]
item_info_params['stock_tag'] = item_info_params['extrinsic_tag'][7]
item_info_params['has_imprint'] = item_info_params['extrinsic_tag'][8]
item_info_params['manuf_id'] = item_info_params['extrinsic_tag'][9]
item_info_params['bill_code1'] = item_info_params['extrinsic_tag'][10]
item_info_params['order_id'] = order.id

customer = Customer.create(item_info_params)

So, as stated above, item_info_params['bill_code1'] will be assigned to name => bill_code1 instead of a blank value.

It's confusing how to solve this problem.

Body:
Meditate on this:

require 'nokogiri'

EXTRINSIC_NAMES = ['tag', 'bin_number', 'manuf_id']

doc = Nokogiri::XML(<<EOT)
      <ItemDetail>
        <UnitPrice><Money currency="USD"></Money></UnitPrice>
        <Description xml:lang="en">Ghent Contract Furniture Binder</Description>
        <UnitOfMeasure>Each</UnitOfMeasure>
        <Classification domain=""></Classification>
        <Extrinsic name="tag">GH-CF-BINDER</Extrinsic>
        <Extrinsic name="bin_number">103/18/9</Extrinsic>
        <Extrinsic name="billing email"></Extrinsic>
        <Extrinsic name="bill_code6"></Extrinsic>
        <Extrinsic name="prodcode"></Extrinsic>
        <Extrinsic name="stock_tag"></Extrinsic>
        <Extrinsic name="has_imprint">N</Extrinsic>
        <Extrinsic name="manuf_id">4117</Extrinsic>
        <Extrinsic name="bill_code1"></Extrinsic>

      </ItemDetail>
EOT

item_detail = doc.at('ItemDetail')

extrinsic_values = EXTRINSIC_NAMES.map { |name|
  [name, doc.at("Extrinsic[name=#{name}]").text]
}.to_h

extrinsic_values
# => {"tag"=>"GH-CF-BINDER", "bin_number"=>"103/18/9", "manuf_id"=>"4117"}

Modify EXTRINSIC_NAMES to select which values you want.

If you want them all then it can be more simple:

extrinsic_values = doc.css('Extrinsic').map { |node|
  [node['name'], node.text]
}.to_h

extrinsic_values
# => {"tag"=>"GH-CF-BINDER",
#     "bin_number"=>"103/18/9",
#     "billing email"=>"",
#     "bill_code6"=>"",
#     "prodcode"=>"",
#     "stock_tag"=>"",
#     "has_imprint"=>"N",
#     "manuf_id"=>"4117",
#     "bill_code1"=>""}

Either way, if your XML files are not formatted the same then you'll have to allow for that in your code.


问:
Amazon AWS Elastic Transcode createJob and readJob not returning Input DetectedProperties data
I have some trouble with PHP AWS SDK

I need to get original video file dimensions, width and height. Reading documentation these data could be retrieved by reading result structure from createJob and readJob functions, but in "Input" section I get only one parameter, "Key" as the original input file name. Anyone use this function?

I start from HLS sample php from AWS official site. I have functions to create job with DASH (fmp4 container) and HLS (ts container). I use 5 presets to make 5 different version of a video input. 5 version for 5 resolution, from 420 to 1920. Everithing works well, but I'm not able to get "DetectedProperties" information

Info about the returned structure at
http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/get-job.html

reading documentation seems that information I need to get about the source video must be placed in the response. But I get the response and the structure I expect to see is different. No "DetectedProperties" present.

This is the documentation about for example createJob:
http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-elastictranscoder-2012-09-25.html#createjob

What I would ask for to anyone knows deeply the PHP SDK is why the documentation says that I will found DetectedProperties in the result, data that must be automatically added from the Elastic Transcoder using the source file to encode, and I get a result without it.

I think it something like an issue, or if not the documentation is really poor about this. I search in web for hours something useful to solve the problem. And I write here because I found nothing...

Thanks to everyone could help

答: Thank you! you saved my time, calling readJob after 'jobComplete' is great solution</p>

ContentLicense: CC BY-SA 4.0


问:
Why are jagged arrays in C# defined in the opposite way?
Let's say I have a type called T. Now let's say I make an array of type T, it gives me T[]. In code, it gives:

```<code>var myArray = new T[10];
</code>```

With a length of 10. So, we can see that this makes an array that contains 10 items of type T. This works if T is int, string, BinaryWriter or anything standard. But let's say T is an array type, like int[] or string[].

Then, if we want to define an array of 10 items of type T (int[]), it should give something like this:

```<code>var myArray = new int[][10];
</code>```

By replacing T by int[] in the previous example. But this gives a syntax error, because the correct syntax in C# is:

```<code>var myArray = new int[10][];
</code>```

Which, if we followed the logic of the first example, should give an array containing an undefined amount of arrays containing 10 integers.

The same applies for any dimension of jagged arrays:

```<code>var myArray = new int[][][10];
</code>```

Is wrong because the syntactically correct way is:

```<code>var myArray = new int[10][][];
</code>```

This isn't a personal preference or a code style debate, but simply logic: why is the syntax different when we define arrays of array types, than when we define arrays of anything else?

答:
This way, the initialization syntax mirrors the access syntax.

```<code>var myArray = new int[NUM_ROWS][];
...
/* Initialize rows of myArray */
...
var x = myArray[0][5]; /* Should this be row 0, col 5; or row 5, col 0? */
</code>```

It would be counterintuitive for myArray[0][5] to be parsed as (myArray[5])[0] since the indices would be inverted left-to-right, so we instead have myArray[0][5] parsed as (myArray[0])[5].

As such, in myArray[i][j], i corresponds to the index into the two-dimensional array, and j corresponds to the index into the one-dimensional array myArray[i].

Now, i can range from 0 to NUM_ROWS-1, so it is symmetrical with the access syntax to initialize var myArray = new int[NUM_ROWS][]. This way, the left set of brackets still corresponds to the length of the two-dimensional array, and the right set of brackets still corresponds to the one-dimensional array.

Edit: I see someone posted in the comments a link to an article where Eric Lippert goes through a more elaborate example and justification.

Body:
Let's say I have a type called T. Now let's say I make an array of type T, it gives me T[]. In code, it gives:

var myArray = new T[10];

With a length of 10. So, we can see that this makes an array that contains 10 items of type T. This works if T is int, string, BinaryWriter or anything standard. But let's say T is an array type, like int[] or string[].

Then, if we want to define an array of 10 items of type T (int[]), it should give something like this:

var myArray = new int[][10];

By replacing T by int[] in the previous example. But this gives a syntax error, because the correct syntax in C# is:

var myArray = new int[10][];

Which, if we followed the logic of the first example, should give an array containing an undefined amount of arrays containing 10 integers.

The same applies for any dimension of jagged arrays:

var myArray = new int[][][10];

Is wrong because the syntactically correct way is:

var myArray = new int[10][][];

This isn't a personal preference or a code style debate, but simply logic: why is the syntax different when we define arrays of array types, than when we define arrays of anything else?

Body:
This way, the initialization syntax mirrors the access syntax.

var myArray = new int[NUM_ROWS][];
...
/* Initialize rows of myArray */
...
var x = myArray[0][5]; /* Should this be row 0, col 5; or row 5, col 0? */

It would be counterintuitive for myArray[0][5] to be parsed as (myArray[5])[0] since the indices would be inverted left-to-right, so we instead have myArray[0][5] parsed as (myArray[0])[5].

As such, in myArray[i][j], i corresponds to the index into the two-dimensional array, and j corresponds to the index into the one-dimensional array myArray[i].

Now, i can range from 0 to NUM_ROWS-1, so it is symmetrical with the access syntax to initialize var myArray = new int[NUM_ROWS][]. This way, the left set of brackets still corresponds to the length of the two-dimensional array, and the right set of brackets still corresponds to the one-dimensional array.

Edit: I see someone posted in the comments a link to an article where Eric Lippert goes through a more elaborate example and justification.


问:
What are the different calling conventions in C/C++ and what do each mean?
There are different calling conventions available in C/C++: stdcall, extern, pascal, etc. How many such calling conventions are available, and what do each mean? Are there any links that describe these?

答:
Simple answer: I use cdecl, stdcall, and fastcall. I seldom use fastcall. stdcall is used to call Windows API functions.

Detailed answer (Stolen from Wikipedia):

cdecl - In cdecl, subroutine arguments are passed on the stack. Integer values and memory addresses are returned in the EAX register, floating point values in the ST0 x87 register. Registers EAX, ECX, and EDX are caller-saved, and the rest are callee-saved. The x87 floating point registers ST0 to ST7 must be empty (popped or freed) when calling a new function, and ST1 to ST7 must be empty on exiting a function. ST0 must also be empty when not used for returning a value.

syscall - This is similar to cdecl in that arguments are pushed right-to-left. EAX, ECX, and EDX are not preserved. The size of the parameter list in doublewords is passed in AL.

pascal -  the parameters are pushed on the stack in left-to-right order (opposite of cdecl), and the callee is responsible for balancing the stack before return.

stdcall - The stdcall[4] calling convention is a variation on the Pascal calling convention in which the callee is responsible for cleaning up the stack, but the parameters are pushed onto the stack in right-to-left order, as in the _cdecl calling convention. Registers EAX, ECX, and EDX are designated for use within the function. Return values are stored in the EAX register.

fastcall -  __fastcall convention (aka __msfastcall) passes the first two arguments (evaluated left to right) that fit into ECX and EDX. Remaining arguments are pushed onto the stack from right to left.

vectorcall - In Visual Studio 2013, Microsoft introduced the __vectorcall calling convention in response to efficiency concerns from game, graphic, video/audio, and codec developers.[7] For IA-32 and x64 code, __vectorcall is similar to __fastcall and the original x64 calling conventions respectively, but extends them to support passing vector arguments using SIMD registers. For x64, when any of the first six arguments are vector types (float, double, __m128, __m256, etc.), they are passed in via the corresponding XMM/YMM registers. Similarly for IA-32, up to six XMM/YMM registers are allocated sequentially for vector type arguments from left to right regardless of position. Additionally, __vectorcall adds support for passing homogeneous vector aggregate (HVA) values, which are composite types consisting solely of up to four identical vector types, using the same six registers. Once the registers have been allocated for vector type arguments, the unused registers are allocated to HVA arguments from left to right regardless of position. Resulting vector type and HVA values are returned using the first four XMM/YMM registers.

safecall - n Delphi and Free Pascal on Microsoft Windows, the safecall calling convention encapsulates COM (Component Object Model) error handling, thus exceptions aren't leaked out to the caller, but are reported in the HRESULT return value, as required by COM/OLE. When calling a safecall function from Delphi code, Delphi also automatically checks the returned HRESULT and raises an exception if necessary.

The safecall calling convention is the same as the stdcall calling convention, except that exceptions are passed back to the caller in EAX as a HResult (instead of in FS:[0]), while the function result is passed by reference on the stack as though it were a final "out" parameter. When calling a Delphi function from Delphi this calling convention will appear just like any other calling convention, because although exceptions are passed back in EAX, they are automatically converted back to proper exceptions by the caller. When using COM objects created in other languages, the HResults will be automatically raised as exceptions, and the result for Get functions is in the result rather than a parameter. When creating COM objects in Delphi with safecall, there is no need to worry about HResults, as exceptions can be raised as normal but will be seen as HResults in other languages.

Microsoft X64 Calling Convention - The Microsoft x64 calling convention[12][13] is followed on Windows and pre-boot UEFI (for long mode on x86-64). It uses registers RCX, RDX, R8, R9 for the first four integer or pointer arguments (in that order), and XMM0, XMM1, XMM2, XMM3 are used for floating point arguments. Additional arguments are pushed onto the stack (right to left). Integer return values (similar to x86) are returned in RAX if 64 bits or less. Floating point return values are returned in XMM0. Parameters less than 64 bits long are not zero extended; the high bits are not zeroed.

When compiling for the x64 architecture in a Windows context (whether using Microsoft or non-Microsoft tools), there is only one calling convention – the one described here, so that stdcall, thiscall, cdecl, fastcall, etc., are now all one and the same.

In the Microsoft x64 calling convention, it is the caller's responsibility to allocate 32 bytes of "shadow space" on the stack right before calling the function (regardless of the actual number of parameters used), and to pop the stack after the call. The shadow space is used to spill RCX, RDX, R8, and R9,[14] but must be made available to all functions, even those with fewer than four parameters.

The registers RAX, RCX, RDX, R8, R9, R10, R11 are considered volatile (caller-saved).[15]

The registers RBX, RBP, RDI, RSI, RSP, R12, R13, R14, and R15 are considered nonvolatile (callee-saved).[15]

For example, a function taking 5 integer arguments will take the first to fourth in registers, and the fifth will be pushed on the top of the shadow space. So when the called function is entered, the stack will be composed of (in ascending order) the return address, followed by the shadow space (32 bytes) followed by the fifth parameter.

In x86-64, Visual Studio 2008 stores floating point numbers in XMM6 and XMM7 (as well as XMM8 through XMM15); consequently, for x86-64, user-written assembly language routines must preserve XMM6 and XMM7 (as compared to x86 wherein user-written assembly language routines did not need to preserve XMM6 and XMM7). In other words, user-written assembly language routines must be updated to save/restore XMM6 and XMM7 before/after the function when being ported from x86 to x86-64.


问:
What is the difference between link and rich type in oEmbed?
I would like to add embed info to my site using oEmbed tag. I am confused between link type and rich type on which context I should use both.

Here is the oEmbed documentation link which doesn't make me clear.

Any advice in this regard is much appreciated ! Thanks in advance :-)

答:
Link type can be used when you wish to provide generic meta data about the url title, author_name etc... without providing html content or url associated with the requested url

Rich  type can be used when you would like to provide html content (which could be embedded within external sites) along with width and height of the iframe.


问:
Load data from table using PHP & AJAX
I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:

{data: [{IdProduct: "1", Name: "Name here..........",…}]}

For example I want to select only Name, I tried doing this:

```<code>function LoadProductos() {

$.ajax({
    url: '../../class/loadProd.php',
    method: 'POST',
    success: function (data) {
      var aRC = JSON.parse(data);

      for (var i = 0; i < aRC.length; i++) {
        console.log(aRC[i].Name);
      }
    }

  });
}
</code>```

But this doesn't shows anything, how can I do this? This is my PHP code:

```<code>while($row = mysqli_fetch_array($registros)) {

    $table.='{
        "IdProduct":"'.$row['IdProduct'].'",
        "Name":"'.$row['Name'].'",
        "Description":"'.$row['Description'].'",
        "ImagePath":"'.$row['ImagePath'].'"
    },';

    $table = substr($table, 0, strlen($table) -1);

    echo '{"data":['.$table.']}';
}
</code>```

答:
In you PHP file make changes according to this:-

```<code>$outp = array();
$outp = $res->fetch_all(MYSQLI_ASSOC);
</code>```

For make sure that json_encode don't return null

```<code>function utf8ize($d) {
 if (is_array($d)) {
    foreach ($d as $k => $v) {
        $d[$k] = utf8ize($v);
    }
} else if (is_string ($d)) {
    return utf8_encode($d);
}
return $d;
}
echo json_encode(utf8ize($outp));
</code>```

You JavaScript is okay You just need to change code in PHP.

Title: Load data from table using PHP & AJAX

Body:
I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:

{data: [{IdProduct: "1", Name: "Name here..........",…}]}

For example I want to select only Name, I tried doing this:

function LoadProductos() {

$.ajax({
    url: '../../class/loadProd.php',
    method: 'POST',
    success: function (data) {
      var aRC = JSON.parse(data);

      for (var i = 0; i < aRC.length; i++) {
        console.log(aRC[i].Name);
      }
    }

  });
}

But this doesn't shows anything, how can I do this? This is my PHP code:

while($row = mysqli_fetch_array($registros)) {

    $table.='{
        "IdProduct":"'.$row['IdProduct'].'",
        "Name":"'.$row['Name'].'",
        "Description":"'.$row['Description'].'",
        "ImagePath":"'.$row['ImagePath'].'"
    },';

    $table = substr($table, 0, strlen($table) -1);

    echo '{"data":['.$table.']}';
}

Body:
In you PHP file make changes according to this:-

$outp = array();
$outp = $res->fetch_all(MYSQLI_ASSOC);

For make sure that json_encode don't return null

function utf8ize($d) {
 if (is_array($d)) {
    foreach ($d as $k => $v) {
        $d[$k] = utf8ize($v);
    }
} else if (is_string ($d)) {
    return utf8_encode($d);
}
return $d;
}
echo json_encode(utf8ize($outp));

You JavaScript is okay You just need to change code in PHP.


问:
How can I determine if a div is scrolled to the bottom?
How do I determine, without using jQuery or any other JavaScript library, if a div with a vertical scrollbar is scrolled all the way to the bottom?

My question is not how to scroll to the bottom. I know how to do that. I want to determine if the the div is scrolled to the bottom already.

This does not work:

```<code>if (objDiv.scrollTop == objDiv.scrollHeight)
</code>```

答:
Little late to this party, but none of the above answers seem to work particularly well when...

Display scaling is applied to the OS for UHD displays

Scaling/zoom is applied to the browser

To accommodate for all eventualities, you will need to round up the calculated scroll position:

```<code>Math.ceil(element.scrollHeight - element.scrollTop) === element.clientHeight
</code>```

Body:
How do I determine, without using jQuery or any other JavaScript library, if a div with a vertical scrollbar is scrolled all the way to the bottom?

My question is not how to scroll to the bottom. I know how to do that. I want to determine if the the div is scrolled to the bottom already.

This does not work:

if (objDiv.scrollTop == objDiv.scrollHeight)

LastEditorDisplayName: Roger Pate

Body:
Little late to this party, but none of the above answers seem to work particularly well when...

Display scaling is applied to the OS for UHD displays

Scaling/zoom is applied to the browser

To accommodate for all eventualities, you will need to round up the calculated scroll position:

Math.ceil(element.scrollHeight - element.scrollTop) === element.clientHeight


问:
Combination in R
How to write a logic to display all possible "N" digit combinations of
"A" & "B" where "A" and "B" forms a pair and "B" can only be inserted if we already have a non paired "A".

For ex :

```<code>when N=2, output should be ["AB"]
when N=4, output should be ["AABB","ABAB"]
when N=6, output should be ["AAABBB","AABBAB","AABABB","ABABAB","ABAABB"]
</code>```

答:
I believe this should get you what you are looking for.</p>

```<code># Number of combinations
n <- 6

# Create dataframe of all combinations for 1 and -1 taken n number of times
# For calculations 1 = A and -1 = B
df <- expand.grid(rep(list(c(1,-1)), n))

# Select only rows that have 1 as first value
df <- df[df[,1] == 1,]

# Set first value for all rows as "A"
df[,1] <- "A"

# Set value for first calculation column as 1
df$s <- 1

# Loop through all columns starting with 2
for(i in 2:n){
  # Get name of current column
  cur.col <- colnames(df)[i]

  # Get the difference between the number of 1 and -1 for current column and the running total
  df$s2 <- apply(df[,c(cur.col,"s")], 1, sum)

  # Remove any rows with a negative value
  df <- df[df$s2 >= 0,]

  # Set running total to current total
  df$s <- df$s2

  # Set values for current column
  df[,i] <- sapply(as.character(df[,i]), switch, "1" = "A", "-1" = "B")

  # Check if current column is last column
  if(i == n){
    # Only select rows that have a total of zero, indicating that row has a pairs of AB values
    df <- df[df$s2 == 0, 1:n]
  }
}

# Get vector of combinations
combos <- unname(apply(df[,1:n], 1, paste0, collapse = ""))
</code>```

Title: Combination in R

Body:
How to write a logic to display all possible "N" digit combinations of
"A" & "B" where "A" and "B" forms a pair and "B" can only be inserted if we already have a non paired "A".

For ex :

when N=2, output should be ["AB"]
when N=4, output should be ["AABB","ABAB"]
when N=6, output should be ["AAABBB","AABBAB","AABABB","ABABAB","ABAABB"]

Body:
I believe this should get you what you are looking for.

# Number of combinations
n <- 6

# Create dataframe of all combinations for 1 and -1 taken n number of times
# For calculations 1 = A and -1 = B
df <- expand.grid(rep(list(c(1,-1)), n))

# Select only rows that have 1 as first value
df <- df[df[,1] == 1,]

# Set first value for all rows as "A"
df[,1] <- "A"

# Set value for first calculation column as 1
df$s <- 1

# Loop through all columns starting with 2
for(i in 2:n){
  # Get name of current column
  cur.col <- colnames(df)[i]

  # Get the difference between the number of 1 and -1 for current column and the running total
  df$s2 <- apply(df[,c(cur.col,"s")], 1, sum)

  # Remove any rows with a negative value
  df <- df[df$s2 >= 0,]

  # Set running total to current total
  df$s <- df$s2

  # Set values for current column
  df[,i] <- sapply(as.character(df[,i]), switch, "1" = "A", "-1" = "B")

  # Check if current column is last column
  if(i == n){
    # Only select rows that have a total of zero, indicating that row has a pairs of AB values
    df <- df[df$s2 == 0, 1:n]
  }
}

# Get vector of combinations
combos <- unname(apply(df[,1:n], 1, paste0, collapse = ""))


问:
Natvis TreeItems definition not working on map<int,int>
I'm having trouble with the natvis extension of visual studio 2015.
In my efforts I need to access a map, but the TreeItems node of natvis does not seem to work for me. I'm actually using the sample code:

```<code><?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">

  <Type Name="std::map<*>">
    <DisplayString>{{size = {_Mysize}}}</DisplayString>
    <Expand>
      <Item Name="[size]">_Mysize</Item>
      <Item Name="[comp]">comp</Item>
      <TreeItems>
        <Size>_Mysize</Size>
        <HeadPointer>_Myhead->_Parent</HeadPointer>
        <LeftPointer>_Left</LeftPointer>
        <RightPointer>_Right</RightPointer>
        <ValueNode Condition="!((bool)_Isnil)">_Myval</ValueNode>
      </TreeItems>
    </Expand>
  </Type>
</AutoVisualizer>
</code>```

But I get this error on a map<int,int>:

```<code>Error: Function std::_Tree_comp_alloc<std::_Tmap_traits<int,int,std::less<int>,std::allocator<std::pair<int const ,int> >,0> >::_Mysize has no address, possibly due to compiler optimizations.
    Error while evaluating '_Mysize' in the context of type 'Program.exe!std::map<int,int,std::less<int>,std::allocator<std::pair<int const ,int> > >'.
</code>```

I'm building in debug mode and I double checked, that optimizations are disabled (\Od)

Maybe the natvis definition for msvc2015 has changed, but I couldn't find anything.
Maybe the sample code is not supposed to work, but I find it hard to get things started from a not working example.

答:
I guess the implementation of std::map has changed and the natvis example is not up-to-date.

The following is working for me on Visual Studio 2017:

```<code><Type Name="std::map<*>">
    <DisplayString>{{size = {_Mypair._Myval2._Myval2._Mysize}}}</DisplayString>
    <Expand>
      <Item Name="[size]">_Mypair._Myval2._Myval2._Mysize</Item>
      <Item Name="[comp]">_Mypair</Item>
      <Item Name="[first element]">_Mypair._Myval2._Myval2._Myhead</Item>
      <TreeItems>
        <Size>_Mypair._Myval2._Myval2._Mysize</Size>
        <HeadPointer>_Mypair._Myval2._Myval2._Myhead->_Parent</HeadPointer>
        <LeftPointer>_Left</LeftPointer>
        <RightPointer>_Right</RightPointer>
        <ValueNode Condition="!((bool)_Isnil)">_Myval</ValueNode>
      </TreeItems>
    </Expand>
  </Type>
</code>```

Body:
I'm having trouble with the natvis extension of visual studio 2015.
In my efforts I need to access a map, but the TreeItems node of natvis does not seem to work for me. I'm actually using the sample code:

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">

  <Type Name="std::map<*>">
    <DisplayString>{{size = {_Mysize}}}</DisplayString>
    <Expand>
      <Item Name="[size]">_Mysize</Item>
      <Item Name="[comp]">comp</Item>
      <TreeItems>
        <Size>_Mysize</Size>
        <HeadPointer>_Myhead->_Parent</HeadPointer>
        <LeftPointer>_Left</LeftPointer>
        <RightPointer>_Right</RightPointer>
        <ValueNode Condition="!((bool)_Isnil)">_Myval</ValueNode>
      </TreeItems>
    </Expand>
  </Type>
</AutoVisualizer>

But I get this error on a map<int,int>:

Error: Function std::_Tree_comp_alloc<std::_Tmap_traits<int,int,std::less<int>,std::allocator<std::pair<int const ,int> >,0> >::_Mysize has no address, possibly due to compiler optimizations.
    Error while evaluating '_Mysize' in the context of type 'Program.exe!std::map<int,int,std::less<int>,std::allocator<std::pair<int const ,int> > >'.

I'm building in debug mode and I double checked, that optimizations are disabled (\Od)

Maybe the natvis definition for msvc2015 has changed, but I couldn't find anything.
Maybe the sample code is not supposed to work, but I find it hard to get things started from a not working example.

Body:
I guess the implementation of std::map has changed and the natvis example is not up-to-date.

The following is working for me on Visual Studio 2017:

<Type Name="std::map&lt;*&gt;">
    <DisplayString>{{size = {_Mypair._Myval2._Myval2._Mysize}}}</DisplayString>
    <Expand>
      <Item Name="[size]">_Mypair._Myval2._Myval2._Mysize</Item>
      <Item Name="[comp]">_Mypair</Item>
      <Item Name="[first element]">_Mypair._Myval2._Myval2._Myhead</Item>
      <TreeItems>
        <Size>_Mypair._Myval2._Myval2._Mysize</Size>
        <HeadPointer>_Mypair._Myval2._Myval2._Myhead-&gt;_Parent</HeadPointer>
        <LeftPointer>_Left</LeftPointer>
        <RightPointer>_Right</RightPointer>
        <ValueNode Condition="!((bool)_Isnil)">_Myval</ValueNode>
      </TreeItems>
    </Expand>
  </Type>


问:
Issues Pushing to Github (HTTP/SSH)
I have two separate issues and solving either of them would be a huge help to me. I'm trying to push some changes I made to my git repo and I can't seem to get it two work.

The first way I've tried to do it is by using the command I'd been doing up until now:

```<code>git push
</code>```

but this would get hung up around 30% of the way through the commit. Following some posts I found online, I've convinced myself that this is a problem with the HTTP connection. I tried using:

```<code>git push --verbose --progress
</code>```

and it always gets stuck at

```<code>Pushing to https://github.com/my-account/my-repo.git
Counting objects: 87, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (66/66), done.
POST git-receive-pack (chunked)476.45 MiB | 29.64 MiB/s
</code>```

I don't have any big files, so I'm not sure what the hang up is.
After looking at some StackOverflow pages, I tried using:

```<code>git config http.postBuffer 524288000
</code>```

which is (I think) supposed to stop it from chunking the data to buffer and allow bigger files to go through, but I got no change.
I then tried updating my version of git (it was at 2.10.something and is now 2.13.1), but that didn't change anything.

Someone suggested using SSH, but I can't seem to get my SSH key to work. I tried using:

```<code>git push -v ssh://my-account@github.com/my-repo.git
</code>```

but I always get the error:

```<code>Pushing to ssh://my-account@github.com/my-repo.git
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

So I went to great lengths trying to get this thing working, even going so far as to regenerate my keys and reregister it with my account, making sure to edit the config to make sure it's all working. It's verified; the command

```<code>ssh -T git@github.com
</code>```

returns

```<code>Hi my-account! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

but, of course,

```<code>git push -v ssh://my-account@github.com/my-repo.git
</code>```

returns the same error as before, Permission Denied. Any ideas on how to fix either the issue with the SSH verification or with the HTTP buffering problem?

答: Github is using a single user for ssh and the name of the user is part of the path, such as git@github.com:my-account/repo.git.

Title: Issues Pushing to Github (HTTP/SSH)

Body:
I have two separate issues and solving either of them would be a huge help to me. I'm trying to push some changes I made to my git repo and I can't seem to get it two work.

The first way I've tried to do it is by using the command I'd been doing up until now:

git push

but this would get hung up around 30% of the way through the commit. Following some posts I found online, I've convinced myself that this is a problem with the HTTP connection. I tried using:

git push --verbose --progress

and it always gets stuck at

Pushing to https://github.com/my-account/my-repo.git
Counting objects: 87, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (66/66), done.
POST git-receive-pack (chunked)476.45 MiB | 29.64 MiB/s

I don't have any big files, so I'm not sure what the hang up is.
After looking at some StackOverflow pages, I tried using:

git config http.postBuffer 524288000

which is (I think) supposed to stop it from chunking the data to buffer and allow bigger files to go through, but I got no change.
I then tried updating my version of git (it was at 2.10.something and is now 2.13.1), but that didn't change anything.

Someone suggested using SSH, but I can't seem to get my SSH key to work. I tried using:

git push -v ssh://my-account@github.com/my-repo.git

but I always get the error:

Pushing to ssh://my-account@github.com/my-repo.git
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

So I went to great lengths trying to get this thing working, even going so far as to regenerate my keys and reregister it with my account, making sure to edit the config to make sure it's all working. It's verified; the command

ssh -T git@github.com

returns

Hi my-account! You've successfully authenticated, but GitHub does not provide shell access.

but, of course,

git push -v ssh://my-account@github.com/my-repo.git

returns the same error as before, Permission Denied. Any ideas on how to fix either the issue with the SSH verification or with the HTTP buffering problem?


问:
Spring @Cacheable double-checked locking (infinispan backend)
I recently started using Spring's @Cacheable annotation in an application to cache the result of some expensive operations. The code I want to replace is making extensive use of the double-checked locking pattern to ensure consistency of the cache and execution of the expensive routines only once like this:

```<code>final String key = SomeClass.computeKey(input)
String cachedValue = mCache.get(key);
if (cachedValue == null) {
    synchronized (mCache) {
        cachedValue = mCache.get(key);
        if (cachedValue == null) {
            cachedValue = expensiveComputing(input);  // must not be executed twice
            mCache.put(key, cachedValue);
        }
    }
}
</code>```

The above was replaced by:

```<code>@Cacheable(value="someCache", key="T(SomeClass).computeKey(#input)")
public String expensiveComputing(Object input) {
    // must not be executed twice
}
</code>```

Sometimes there is a second cache in place to cache the lock-object for the actual lookup to avoid extensive synchronization on the whole cache during computation of the cache value.

I already read infinispan's docu on locking and am still wondering whether I need to take care of these aspects myself or if infinispan guarantees for the expected behavior.

According to the docu infinispan creates a new lock for each cache entry by default since 5.0 (I'm using 8.2.6). That is the 2 level caching of lock-object and cache value should be unnecessary, If I got this correctly?! But what about the double-checked locking pattern? Can this be removed as well? And will the expensiveComputing routine still be called only once in a heavily concurrent environment?

答:
Short answer

This is supported with Spring 4.3+ and Infinispan 9.0+ with sync=true in @Cacheable (see this Spring ticket and this Infinispan ticket)

Long answer

Pre-Spring 4.3, simply annotating the method with @Cacheable will not synchronize the code itself. All it does is wrap the methods into a proxy (see o.s.c.a.JCacheCacheAspect and o.s.c.j.i.JCacheAspectSupport for details) which doesn't include any additional synchronization when it tries to get the value from cache before invoking the method body.

So it's entirely possible for the expensive computation to occur twice. The additional synchronization is up to the programmer in this case. So the double-checked locking is still useful.

There is another option: as Infinispan provides its caching library as a JCache (JSR-107) provider, you may consider, instead of using the default org.infinispan.jcache.annotation.InjectedCacheResultInterceptor, writing your own implementation of org.infinispan.jcache.annotation.AbstractCacheResultInterceptor, which will take care of the locking. For example, your implementation of the class may have some dictionary to decide what kinds of InvocationContext require such locking.

Actually, it looks like using @Cacheable in this case brings more pain than gain. Creating a cache from transaction manager and using it to have some control over transactions like they do in Infinispan tutorials seems to be easier and more concise.

Since Spring 4.3, @Cacheable has a sync attribute which hints that the whole operation must be synchronized. Infinispan supports this since version 9.0.

Body:
I recently started using Spring's @Cacheable annotation in an application to cache the result of some expensive operations. The code I want to replace is making extensive use of the double-checked locking pattern to ensure consistency of the cache and execution of the expensive routines only once like this:

final String key = SomeClass.computeKey(input)
String cachedValue = mCache.get(key);
if (cachedValue == null) {
    synchronized (mCache) {
        cachedValue = mCache.get(key);
        if (cachedValue == null) {
            cachedValue = expensiveComputing(input);  // must not be executed twice
            mCache.put(key, cachedValue);
        }
    }
}

The above was replaced by:

@Cacheable(value="someCache", key="T(SomeClass).computeKey(#input)")
public String expensiveComputing(Object input) {
    // must not be executed twice
}

Sometimes there is a second cache in place to cache the lock-object for the actual lookup to avoid extensive synchronization on the whole cache during computation of the cache value.

I already read infinispan's docu on locking and am still wondering whether I need to take care of these aspects myself or if infinispan guarantees for the expected behavior.

According to the docu infinispan creates a new lock for each cache entry by default since 5.0 (I'm using 8.2.6). That is the 2 level caching of lock-object and cache value should be unnecessary, If I got this correctly?! But what about the double-checked locking pattern? Can this be removed as well? And will the expensiveComputing routine still be called only once in a heavily concurrent environment?


问:
Saving Single Sheet as CSV File
I am new at VBA and I have tried to do some research on this topic but with no luck. I have a workbook with multiple sheets but I only want to save sheet 6 as a CSV file to a certain location without opening a new file. How would I go about that using VBA linked to something like a button? thanks</p>

答:
Create a button and link it to this macro:</p>

```<code>Sub Sheet6ToCSV()
  Application.ScreenUpdating = False:  Application.EnableEvents = False:  Application.DisplayAlerts = False
  On Error GoTo Cleanup

  Dim fold As String: fold = "C:\SO\"
  Dim fName  As String: fName = "MySheet6"

  Worksheets("Sheet6").Copy
  With ActiveWorkbook
    .SaveAs fold & fName
    .Close False
  End With

Cleanup:
  Application.ScreenUpdating = True:  Application.EnableEvents = True: Application.DisplayAlerts = True
End Sub
</code>```

Title: Saving Single Sheet as CSV File

Body:
Create a button and link it to this macro:

Sub Sheet6ToCSV()
  Application.ScreenUpdating = False:  Application.EnableEvents = False:  Application.DisplayAlerts = False
  On Error GoTo Cleanup

  Dim fold As String: fold = "C:\SO\"
  Dim fName  As String: fName = "MySheet6"

  Worksheets("Sheet6").Copy
  With ActiveWorkbook
    .SaveAs fold & fName
    .Close False
  End With

Cleanup:
  Application.ScreenUpdating = True:  Application.EnableEvents = True: Application.DisplayAlerts = True
End Sub


问:
android.support.test.espresso.NoActivityResumedException: No activities in stage RESUMED
I'm trying to write test cases for my activities. I have several activities and there is no issue for one of them while I'm getting following error when I try to run tests over other ActivityTest classes.

android.support.test.espresso.NoActivityResumedException: No
  activities in stage RESUMED. Did you forget to launch the activity.
  (test.getActivity() or similar)?

This is my class that all my test cases fails:

```<code>@RunWith(AndroidJUnit4.class)
@LargeTest
public class LocatingActivityTest
{
    @Rule
    public ActivityTestRule<LocatingActivity> mActivityTestRule = new ActivityTestRule<>(LocatingActivity.class);

    private LocatingActivity mLocatingActivity;

    @Before
    public void setup()
    {
        mLocatingActivity = mActivityTestRule.getActivity();
    }

    @Test
    public void viewsMustBeVisible()
    {
        onView(withId(R.id.locating_text)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.sonarView)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.locating_cancel_booking)).check(matches(isCompletelyDisplayed()));

        onView(withId(R.id.locating_list_view)).check(matches(isDisplayed()));
    }

    @Test
    public void viewsMustBeEnabled()
    {
        onView(withId(R.id.tvNoDriverFound)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.tvNextSearch)).check(matches(not(isCompletelyDisplayed())));
    }
}
</code>```

However this is my another class that all of its test cases passes:

```<code>@RunWith(AndroidJUnit4.class)
@LargeTest
public class BookingActivityTest
{
    @Rule
    public IntentsTestRule<BookingTaxiActivity> mActivityTestRule = new IntentsTestRule<>(BookingTaxiActivity.class);

    private BookingTaxiActivity mBookingTaxiActivity;

    @Before
    public void setup()
    {
        mBookingTaxiActivity = mActivityTestRule.getActivity();
    }

    @Test
    public void viewsMustBeVisible()
    {
        onView(withId(R.id.booking_pick_up_layout)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.booking_drop_off_layout)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.fab_booking)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.booking_estimated_fare)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.ibMenu)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.booking_toolbar)).check(matches(isCompletelyDisplayed()));

        onView(withId(R.id.booking_taxi_type_picker)).check(matches(isDisplayed()));
    }

    @Test
    public void viewsMustBeEnabled()
    {
        // These Views are off the screen
        onView(withId(R.id.tag_widget)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.payment_btn)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.current_pickup_view)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.advance_pickup_view)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.booking_notes_btn)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.promo_code_btn)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.taxi_warning)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.booking_book_now)).check(matches(not(isCompletelyDisplayed())));
    }
}
</code>```

I have no idea why tests of above class passes while other classes fails.

答:
If the run device is in lock mode, and/or activity inactive, will trigger this error. Make sure your device is on and app/test is able to run in foreground!
The easiest fix ever(at least for me)!</p>

Body:
I'm trying to write test cases for my activities. I have several activities and there is no issue for one of them while I'm getting following error when I try to run tests over other ActivityTest classes.

android.support.test.espresso.NoActivityResumedException: No
  activities in stage RESUMED. Did you forget to launch the activity.
  (test.getActivity() or similar)?

This is my class that all my test cases fails:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class LocatingActivityTest
{
    @Rule
    public ActivityTestRule<LocatingActivity> mActivityTestRule = new ActivityTestRule<>(LocatingActivity.class);

    private LocatingActivity mLocatingActivity;

    @Before
    public void setup()
    {
        mLocatingActivity = mActivityTestRule.getActivity();
    }

    @Test
    public void viewsMustBeVisible()
    {
        onView(withId(R.id.locating_text)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.sonarView)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.locating_cancel_booking)).check(matches(isCompletelyDisplayed()));

        onView(withId(R.id.locating_list_view)).check(matches(isDisplayed()));
    }

    @Test
    public void viewsMustBeEnabled()
    {
        onView(withId(R.id.tvNoDriverFound)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.tvNextSearch)).check(matches(not(isCompletelyDisplayed())));
    }
}

However this is my another class that all of its test cases passes:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class BookingActivityTest
{
    @Rule
    public IntentsTestRule<BookingTaxiActivity> mActivityTestRule = new IntentsTestRule<>(BookingTaxiActivity.class);

    private BookingTaxiActivity mBookingTaxiActivity;

    @Before
    public void setup()
    {
        mBookingTaxiActivity = mActivityTestRule.getActivity();
    }

    @Test
    public void viewsMustBeVisible()
    {
        onView(withId(R.id.booking_pick_up_layout)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.booking_drop_off_layout)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.fab_booking)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.booking_estimated_fare)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.ibMenu)).check(matches(isCompletelyDisplayed()));
        onView(withId(R.id.booking_toolbar)).check(matches(isCompletelyDisplayed()));

        onView(withId(R.id.booking_taxi_type_picker)).check(matches(isDisplayed()));
    }

    @Test
    public void viewsMustBeEnabled()
    {
        // These Views are off the screen
        onView(withId(R.id.tag_widget)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.payment_btn)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.current_pickup_view)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.advance_pickup_view)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.booking_notes_btn)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.promo_code_btn)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.taxi_warning)).check(matches(not(isCompletelyDisplayed())));
        onView(withId(R.id.booking_book_now)).check(matches(not(isCompletelyDisplayed())));
    }
}

I have no idea why tests of above class passes while other classes fails.


问:
Dynamically changing a style in Polymer 2.0
I'm writing a proof of concept Polymer 2.0 web component where I want to change the colour of a piece of text depending on the user input.

I've tried using Polymer 2.0's this.updateStyles({...}) and Polymer.updateStyles({...}) but neither is updating the text which is output.

e.g.

```<code>Polymer.updateStyles({'--tool-colour': 'green'});
</code>```

I've written a plunker which demonstrates the problem here.

I'm probably missing something simple, can someone help me out?

答:
The "problem" is as Jordan Running stated that your webcomponentsjs is not loading.

The real thing is that you can't use updateStyles without webcomponentsjs which is rather unfortunate as there are situations where you probably won't need it at all.

In this case you could do
this.setAttribute('style', '--tool-colour: red');
but then again this won't work in browsers needing webcomponentsjs.

what I ended up doing create an behavior that either uses setAttributes (with merging for styles) or updateStyles depending on what is available. It code looks like this.

```<code>if (!window.ShadyCSS || (window.ShadyCSS && window.ShadyCSS.nativeCss === true)) {
    var newStyleString = '';
    for (var key in newStyle) {
        if (newStyle.hasOwnProperty(key)) {
            newStyleString += key + ': ' + newStyle[key] + ';';
        }
    }
    this.setAttribute('style', newStyleString);
} else {
    ShadyCSS.styleSubtree(this, newStyle);
}
</code>```

So for usage I just write this.updateStyles({'--tool-colour': 'green'}); as my behavior overwrites updateStyles.

The full code you can find here
https://github.com/daKmoR/grain-update-inline-style-behavior.
It's a little more as it also adds support for inline styles on IE11.

Body:
I'm writing a proof of concept Polymer 2.0 web component where I want to change the colour of a piece of text depending on the user input.

I've tried using Polymer 2.0's this.updateStyles({...}) and Polymer.updateStyles({...}) but neither is updating the text which is output.

e.g.

Polymer.updateStyles({'--tool-colour': 'green'});

I've written a plunker which demonstrates the problem here.

I'm probably missing something simple, can someone help me out?

Body:
The "problem" is as Jordan Running stated that your webcomponentsjs is not loading.

The real thing is that you can't use updateStyles without webcomponentsjs which is rather unfortunate as there are situations where you probably won't need it at all.

In this case you could do
this.setAttribute('style', '--tool-colour: red');
but then again this won't work in browsers needing webcomponentsjs.

what I ended up doing create an behavior that either uses setAttributes (with merging for styles) or updateStyles depending on what is available. It code looks like this.

if (!window.ShadyCSS || (window.ShadyCSS && window.ShadyCSS.nativeCss === true)) {
    var newStyleString = '';
    for (var key in newStyle) {
        if (newStyle.hasOwnProperty(key)) {
            newStyleString += key + ': ' + newStyle[key] + ';';
        }
    }
    this.setAttribute('style', newStyleString);
} else {
    ShadyCSS.styleSubtree(this, newStyle);
}

So for usage I just write this.updateStyles({'--tool-colour': 'green'}); as my behavior overwrites updateStyles.

The full code you can find here
https://github.com/daKmoR/grain-update-inline-style-behavior.
It's a little more as it also adds support for inline styles on IE11.


问:
add + button before a row
How can i add green + button before a row in group table see in image

答:
You can refer to this sample code link
http://developer.apple.com/library/ios/#samplecode/ListAdder/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010275</p>

Title: add + button before a row


问:
SCNScene is nil when loading using `named: `
I am using the following code to render a scene in scenekit and it works perfectly when the dae file is loaded from art.scnassests folder.

```<code>let scene = SCNScene(named: "art.scnassets/idle.dae")
</code>```

However I want to download the asset and apply it and I am getting an error

```<code>let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let scene = SCNScene(named: documentsURL.absoluteString+"idle.dae")
</code>```

A file named idle.dae exists in the folder.

I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value

How to load the downloaded asset and apply dynamically?  What am I doing wrong?  Any pointers please? I am a noob to iOS programming.

答:
Unless something has changed for iOS 11, you won't be able to download and instantiate a DAE file at runtime on iOS. They are compressed/compiled at build time using a utility named scntool.

Can you instead use one of the file formats supported by Model I/O? See https://developer.apple.com/videos/play/wwdc2015/602/?time=320 for the original list (Alembic .abc, Polygon .ply Triangles .stl, WaveFront .obj), and https://developer.apple.com/videos/play/wwdc2017/610/ for a quick discussion of Pixar's USD (Universal Scene Description).

If you're stuck with DAE files, Frederik Jacques has an article at https://the-nerd.be/2014/11/07/dynamically-load-collada-files-in-scenekit-at-runtime/ which outlines his experience reverse engineering the DAE processing pipeline. His technique allows downloaded SCN files which have been processed from DAE files on a server.
See also Load uncompressed collada file using iOS Scene Kit (with comments by an authoritative source) and https://forums.developer.apple.com/thread/38010.

Body:
I am using the following code to render a scene in scenekit and it works perfectly when the dae file is loaded from art.scnassests folder.

let scene = SCNScene(named: "art.scnassets/idle.dae")

However I want to download the asset and apply it and I am getting an error

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let scene = SCNScene(named: documentsURL.absoluteString+"idle.dae")

A file named idle.dae exists in the folder.

I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value

How to load the downloaded asset and apply dynamically?  What am I doing wrong?  Any pointers please? I am a noob to iOS programming.


问:
Swift JSON parsing and printing a specified value from an array
Hi I'm trying to get data from a certain JSON API. I can gat a snapshot of all values from the API, which is shown below. But I can't manage to put a specifiek row in a variable. This is the JSON form which I get. I want to print the "Description" value.Can someone help me with this?

And Hier is my code:

```<code>func apiRequest() {
    let config = URLSessionConfiguration.default
    let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
    let password = "G23@rE9t1#"
    let loginString = String(format: "%@:%@", username, password)
    let userPasswordData = loginString.data(using: String.Encoding.utf8)
    let base64EncodedCredential = userPasswordData?.base64EncodedString()
    let authString = "Basic " + (base64EncodedCredential)!

    print(authString)
    config.httpAdditionalHeaders = ["Authorization" : authString]
    let session = URLSession(configuration: config)

    var running = false
    let url = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")

    let task = session.dataTask(with: url! as URL) {
        ( data, response, error) in
        if let taskHeader = response as? HTTPURLResponse {
            print(taskHeader.statusCode)
        }
        if error != nil {
            print("There is an error!!!")
            print(error)
        } else {
            if let content = data {
                do {
                    let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(array)

                    if let items = array["items"] {
                         if let description = items["Description"] as? [[String:Any]]{
                            print(description as Any)
                         }
                    }
                }
                catch {
                    print("Error: Could not get any data")
                }
            }
        }
        running = false
    }

    running = true
    task.resume()

    while running {
        print("waiting...")
        sleep(1)
    }
}
</code>```

答:
Looks like items is an array that needs to be looped through.  Here is some sample code, but I want to warn you that this code is not tested for your data.

```<code>if let items = array["items"] as? [[String: AnyObject]] {
    for item in items {
        if let description = item["Description"] as? String{
            print("Description: \(description)")
        }
    }
}
</code>```

This code above, or some variation of it, should get you on the right track.

Body:
Hi I'm trying to get data from a certain JSON API. I can gat a snapshot of all values from the API, which is shown below. But I can't manage to put a specifiek row in a variable. This is the JSON form which I get. I want to print the "Description" value.Can someone help me with this?

And Hier is my code:

func apiRequest() {
    let config = URLSessionConfiguration.default
    let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
    let password = "G23@rE9t1#"
    let loginString = String(format: "%@:%@", username, password)
    let userPasswordData = loginString.data(using: String.Encoding.utf8)
    let base64EncodedCredential = userPasswordData?.base64EncodedString()
    let authString = "Basic " + (base64EncodedCredential)!

    print(authString)
    config.httpAdditionalHeaders = ["Authorization" : authString]
    let session = URLSession(configuration: config)

    var running = false
    let url = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")

    let task = session.dataTask(with: url! as URL) {
        ( data, response, error) in
        if let taskHeader = response as? HTTPURLResponse {
            print(taskHeader.statusCode)
        }
        if error != nil {
            print("There is an error!!!")
            print(error)
        } else {
            if let content = data {
                do {
                    let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(array)

                    if let items = array["items"] {
                         if let description = items["Description"] as? [[String:Any]]{
                            print(description as Any)
                         }
                    }
                }
                catch {
                    print("Error: Could not get any data")
                }
            }
        }
        running = false
    }

    running = true
    task.resume()

    while running {
        print("waiting...")
        sleep(1)
    }
}

Body:
Looks like items is an array that needs to be looped through.  Here is some sample code, but I want to warn you that this code is not tested for your data.

if let items = array["items"] as? [[String: AnyObject]] {
    for item in items {
        if let description = item["Description"] as? String{
            print("Description: \(description)")
        }
    }
}

This code above, or some variation of it, should get you on the right track.


问:
Mysql selet multiple values
As seen in the code below i have to select multiple values to be exported to my database. '_shipping_first_name' AND '_shipping_last_name'

How is it possible to make the MySQL work with two values connected?

```<code>SELECT meta_value FROM `wpd2_postmeta`
WHERE meta_key='_shipping_first_name'(value 2 here)
AND post_id='12017'
</code>```

答: SELECT meta_value FROM wpd2_postmeta where meta_key=concat('_shipping_first_name', value2) and post_id='12017'

Title: Mysql selet multiple values

Body:
As seen in the code below i have to select multiple values to be exported to my database. '_shipping_first_name' AND '_shipping_last_name'

How is it possible to make the MySQL work with two values connected?

SELECT meta_value FROM `wpd2_postmeta`
WHERE meta_key='_shipping_first_name'(value 2 here)
AND post_id='12017'


问:
Lua Integer type
i really need to have an integer type in Lua.

What i mean by integer type is a type defining the usual operators (/ * + etc) and behaving like an integer, the internal representation doesn't matter.

Doing such a thing with tables is very simple, the problem is, i tried that, and the performance is terribly poor (of course). Here is my partial implementation :

```<code>function num_op(a, b, calc_func)
    local atype = pytype(a)
    local btype = pytype(b)
    local a_val, b_val

    a_val = (atype == "Integer" or atype == "Double") and a[1] or a
    b_val = (btype == "Integer" or btype == "Double") and b[1] or b
    val = calc_func(a_val, b_val)

    if atype == "Integer" and btype == "Integer" then
        return Integer:create(val)
    else
        return Double:create(val)
    end
end

numeric_mt = {
    __add = function(a, b)
        return num_op(a, b, function(a,b) return a + b end)
    end,

    __sub = function(a, b)
        return num_op(a, b, function(a,b) return a - b end)
    end,

    __div = function(a, b)
        return num_op(a, b, function(a,b) return a / b end)
    end,

    __mul = function(a, b)
        return num_op(a, b, function(a,b) return a * b end)
    end,

    __tostring = function(a)
        return tostring(a[1])
    end
}

-----------------------------
-- Integer type definition --
-----------------------------

Integer = {}
Integer_mt = table.copy(numeric_mt)
Integer_mt["__index"] = Integer

function Integer:create(value)
    local new_inst = {math.floor(value)}
    setmetatable(new_inst, Integer_mt)
    return new_inst
end

function Integer:className()
    return "Integer"
end
</code>```

The main performance penalty from what i gather is (of course) the very numerous allocations. LuaJit is able to optimize the operators functions quite well, but not the metatables allocations.

Do anybody think it would be possible to do better with a custom c implementation and userdata ? Or is what i'm pursuing impossible to attain ?

NB : i know lua doesn't have integers. I also know that i can obtain the same results using the math lib. What i want is complete transparency when using integers, except for the creation phase.

EDIT : I'm gonna add additional information in here so that everything is still centralized

@Mud: I need, to a certain degree to have transparent mixed arithmetics in the same way you have in python/ruby/etc, but with the best performance possible. I'm using luaJIT as a target for a compiler, with regular Lua as a fallback for platforms not supported by luaJIT. This is very important for the performance characteristics.

It means that i would like to be able to do this:

```<code>a = int(5) -- Integer value
b = int(2) -- Another Integer
c = 2      -- Double
d = a / b  -- == 2 , integer arithmetics
e = a / c  -- == 2.5, floating point arithmetics
</code>```

I can reach that to a certain point, with the implementation showed above. The problem is that i'm slowing operations on every numbers, since regular numbers are boxed too. I could overload the metatable of numbers with the debug lib, but

I don't know how reliable this feature is for use in production quality software

It will still slow down the performance of numbers since, to be able to have an unified interface to numbers, i'll have to use (number):get(), which will slow down operation in any case.

I rolled my own Integer implementation in C last night. The thing is, although it is an improvement over my naive implementation in regular lua, and also and improvement over inline calls to math.floor, it's much less clear when using LuaJIT, where inline calls are still a lot faster than the C implementation.

Another solution would be to always use unboxed numbers, and use some kind of type propagation in my compiler to track integers and use proper inline operations on them when needed, but the complexity of this solution is a lot bigger, and kind of defeats the whole purpose of using Lua/LuaJIT as a backend.

I'm gonna try your implementation, but i doubt it will be better than inline calls in LuaJIT. It may very well be that what i'm shooting for (having both transparent operation of double and integers, and performance close to inline calls on luaJIT) is plain impossible. Thank you very much for your help.

@miky : Thanks, this is looking nice, but i doubt i can patch luaJIT with it, and if i can't, it looses all its interrest for my goal.

答: You can try one of the arbitrary precision libraries listed at http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/ . In particular, lbn is integer-only and fast but you need OpenSSL. For a simple self-contained library, see lbc.</p>

Title: Lua Integer type

Body:
i really need to have an integer type in Lua.

What i mean by integer type is a type defining the usual operators (/ * + etc) and behaving like an integer, the internal representation doesn't matter.

Doing such a thing with tables is very simple, the problem is, i tried that, and the performance is terribly poor (of course). Here is my partial implementation :

function num_op(a, b, calc_func)
    local atype = pytype(a)
    local btype = pytype(b)
    local a_val, b_val

    a_val = (atype == "Integer" or atype == "Double") and a[1] or a
    b_val = (btype == "Integer" or btype == "Double") and b[1] or b
    val = calc_func(a_val, b_val)

    if atype == "Integer" and btype == "Integer" then
        return Integer:create(val)
    else
        return Double:create(val)
    end
end

numeric_mt = {
    __add = function(a, b)
        return num_op(a, b, function(a,b) return a + b end)
    end,

    __sub = function(a, b)
        return num_op(a, b, function(a,b) return a - b end)
    end,

    __div = function(a, b)
        return num_op(a, b, function(a,b) return a / b end)
    end,

    __mul = function(a, b)
        return num_op(a, b, function(a,b) return a * b end)
    end,

    __tostring = function(a)
        return tostring(a[1])
    end
}

-----------------------------
-- Integer type definition --
-----------------------------

Integer = {}
Integer_mt = table.copy(numeric_mt)
Integer_mt["__index"] = Integer

function Integer:create(value)
    local new_inst = {math.floor(value)}
    setmetatable(new_inst, Integer_mt)
    return new_inst
end

function Integer:className()
    return "Integer"
end

The main performance penalty from what i gather is (of course) the very numerous allocations. LuaJit is able to optimize the operators functions quite well, but not the metatables allocations.

Do anybody think it would be possible to do better with a custom c implementation and userdata ? Or is what i'm pursuing impossible to attain ?

NB : i know lua doesn't have integers. I also know that i can obtain the same results using the math lib. What i want is complete transparency when using integers, except for the creation phase.

EDIT : I'm gonna add additional information in here so that everything is still centralized

@Mud: I need, to a certain degree to have transparent mixed arithmetics in the same way you have in python/ruby/etc, but with the best performance possible. I'm using luaJIT as a target for a compiler, with regular Lua as a fallback for platforms not supported by luaJIT. This is very important for the performance characteristics.

It means that i would like to be able to do this:

a = int(5) -- Integer value
b = int(2) -- Another Integer
c = 2      -- Double
d = a / b  -- == 2 , integer arithmetics
e = a / c  -- == 2.5, floating point arithmetics

I can reach that to a certain point, with the implementation showed above. The problem is that i'm slowing operations on every numbers, since regular numbers are boxed too. I could overload the metatable of numbers with the debug lib, but

I don't know how reliable this feature is for use in production quality software

It will still slow down the performance of numbers since, to be able to have an unified interface to numbers, i'll have to use (number):get(), which will slow down operation in any case.

I rolled my own Integer implementation in C last night. The thing is, although it is an improvement over my naive implementation in regular lua, and also and improvement over inline calls to math.floor, it's much less clear when using LuaJIT, where inline calls are still a lot faster than the C implementation.

Another solution would be to always use unboxed numbers, and use some kind of type propagation in my compiler to track integers and use proper inline operations on them when needed, but the complexity of this solution is a lot bigger, and kind of defeats the whole purpose of using Lua/LuaJIT as a backend.

I'm gonna try your implementation, but i doubt it will be better than inline calls in LuaJIT. It may very well be that what i'm shooting for (having both transparent operation of double and integers, and performance close to inline calls on luaJIT) is plain impossible. Thank you very much for your help.

@miky : Thanks, this is looking nice, but i doubt i can patch luaJIT with it, and if i can't, it looses all its interrest for my goal.


问:
Android: how to get application label in UsageStats
I am able to get the usage statistics of the app using the UsgaeStatsManager like below

```<code>UsageStatsManager usm = getUsageStatsManager(context);
Calendar calendar = Calendar.getInstance();
long endTime = calendar.getTimeInMillis();
calendar.add(Calendar.DATE, -1);
long startTime = calendar.getTimeInMillis();

List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);

for (UsageStats u : usageStatsList){
   Log.d(TAG, "Pkg: " + u.getPackageName() +  "\t" + "ForegroundTime: "
                + u.getTotalTimeInForeground() + " milliseconds") ;
}
</code>```

When I get the output then it comes like below:

```<code>Pkg:com.skype.raiderForeground used time in ms:23922
Pkg:com.google.android.youtubeForeground used time in ms:0
Pkg:com.sec.android.app.chromecustomizationsForeground used time in ms:0
Pkg:com.whatsappForeground used time in ms:1665723
.
.
.
</code>```

Which is correct but I want to get this list with names of apps in more user readable format like

```<code>Pkg:skype Foreground used time in ms:23922
Pkg:youtube Foreground used time in ms:0
Pkg:whatsapp Foreground used time in ms:1665723
</code>```

I am wondering if we have any api similar to api applicationInfo.loadLabel(getPackageManager()).toString(); in PackageManager which gives the user readable package name instead of technical name of package. Or, is there any other way to print the simple name of the package ?

答:
You can use this method to get the AppName using package name

```<code>private String getAppNameFromPackage(String packageName, Context context) {
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> pkgAppsList = context.getPackageManager()
                .queryIntentActivities(mainIntent, 0);

        for (ResolveInfo app : pkgAppsList) {
            if (app.activityInfo.packageName.equals(packageName)) {
                return app.activityInfo.loadLabel(context.getPackageManager()).toString();
            }
        }
        return null;
    }
</code>```

You can print for loop like this,

```<code>for (UsageStats u : usageStatsList){
    Log.d(TAG, "Pkg: " + getAppNameFromPackage(u.getPackageName(), context) +  "\t" + "ForegroundTime: "
            + u.getTotalTimeInForeground() + " milliseconds") ;
}
</code>```

It will give result like

```<code>Pkg:skype Foreground used time in ms:23922
Pkg:youtube Foreground used time in ms:0
Pkg:whatsapp Foreground used time in ms:1665723
</code>```

Body:
I am able to get the usage statistics of the app using the UsgaeStatsManager like below

UsageStatsManager usm = getUsageStatsManager(context);
Calendar calendar = Calendar.getInstance();
long endTime = calendar.getTimeInMillis();
calendar.add(Calendar.DATE, -1);
long startTime = calendar.getTimeInMillis();

List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);

for (UsageStats u : usageStatsList){
   Log.d(TAG, "Pkg: " + u.getPackageName() +  "\t" + "ForegroundTime: "
                + u.getTotalTimeInForeground() + " milliseconds") ;
}

When I get the output then it comes like below:

Pkg:com.skype.raiderForeground used time in ms:23922
Pkg:com.google.android.youtubeForeground used time in ms:0
Pkg:com.sec.android.app.chromecustomizationsForeground used time in ms:0
Pkg:com.whatsappForeground used time in ms:1665723
.
.
.

Which is correct but I want to get this list with names of apps in more user readable format like

Pkg:skype Foreground used time in ms:23922
Pkg:youtube Foreground used time in ms:0
Pkg:whatsapp Foreground used time in ms:1665723

I am wondering if we have any api similar to api applicationInfo.loadLabel(getPackageManager()).toString(); in PackageManager which gives the user readable package name instead of technical name of package. Or, is there any other way to print the simple name of the package ?

Body:
You can use this method to get the AppName using package name

private String getAppNameFromPackage(String packageName, Context context) {
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> pkgAppsList = context.getPackageManager()
                .queryIntentActivities(mainIntent, 0);

        for (ResolveInfo app : pkgAppsList) {
            if (app.activityInfo.packageName.equals(packageName)) {
                return app.activityInfo.loadLabel(context.getPackageManager()).toString();
            }
        }
        return null;
    }

You can print for loop like this,

for (UsageStats u : usageStatsList){
    Log.d(TAG, "Pkg: " + getAppNameFromPackage(u.getPackageName(), context) +  "\t" + "ForegroundTime: "
            + u.getTotalTimeInForeground() + " milliseconds") ;
}

It will give result like

Pkg:skype Foreground used time in ms:23922
Pkg:youtube Foreground used time in ms:0
Pkg:whatsapp Foreground used time in ms:1665723


问:
Simple Stack, how to initialize Node at 0 instead of null
I am trying to implement a very simple stack, however, it seems that I need to use a node for this. I have the below which compiles and works fine, however, it throws a lot of errors until someone makes the first push. I am in a situation where I cannot control what is in the consumer's main method, so I think it would be best to avoid these errors and just initialize a new stack object with an initial value of zero. Unfortunately, I cannot figure out just how to do that. Would anyone here be able to advise me?</p>

```<code>import java.util.*;

public class StackQ {
    Node top;

public StackQ() {
    top=null;
}

class Node {
    public int x = 0;
    public Node next;
    Node(int d) {x=d; next=null;}
    public int getData() {return x;}
}

public int pop() {
    if(top!=null) {
        int item = top.x;
        top = top.next;
        return item;
        }
    return -1;
}

public void push(int x) {
    Node t = new Node(x);
    t.next = this.top;
    this.top = t;
}

public int top() {
    if (top == null) throw new EmptyStackException();
    return top.x;
}

public static void main(String[] args) {
    StackQ mainStack = new StackQ();
}

}
</code>```

答:
If they're using top() without putting anything in the stack, they are using your stack wrong.  Seriously, they should be getting an exception.  It's up to them to not use your stack that way, and it's up to them to properly handle that exception.

But if you really wanted to always start your stack with a 0 in it (which, to be perfectly clear, I am advising against doing) just put that in your constructor.

```<code>public StackQ() {
    top=new Node(0);
}
</code>```

Body:
I am trying to implement a very simple stack, however, it seems that I need to use a node for this. I have the below which compiles and works fine, however, it throws a lot of errors until someone makes the first push. I am in a situation where I cannot control what is in the consumer's main method, so I think it would be best to avoid these errors and just initialize a new stack object with an initial value of zero. Unfortunately, I cannot figure out just how to do that. Would anyone here be able to advise me?

import java.util.*;

public class StackQ {
    Node top;

public StackQ() {
    top=null;
}

class Node {
    public int x = 0;
    public Node next;
    Node(int d) {x=d; next=null;}
    public int getData() {return x;}
}

public int pop() {
    if(top!=null) {
        int item = top.x;
        top = top.next;
        return item;
        }
    return -1;
}

public void push(int x) {
    Node t = new Node(x);
    t.next = this.top;
    this.top = t;
}

public int top() {
    if (top == null) throw new EmptyStackException();
    return top.x;
}

public static void main(String[] args) {
    StackQ mainStack = new StackQ();
}

}

Body:
If they're using top() without putting anything in the stack, they are using your stack wrong.  Seriously, they should be getting an exception.  It's up to them to not use your stack that way, and it's up to them to properly handle that exception.

But if you really wanted to always start your stack with a 0 in it (which, to be perfectly clear, I am advising against doing) just put that in your constructor.

public StackQ() {
    top=new Node(0);
}


问:
how to Add a Button on the home screen in android?
I want to add a button on the home screen and want to code in the click event of that button.
I have an application which has an activate button,As soon as this activate button is clicked i want that a Button gets created on the home screen and i want to code some database queries in its click event.I have already created that application,Now i want to place the button on the home screen.How do i do that.

Thanks in Anticipation.

答:
If you are using xml layout for it add the button widget you needed and set it's visibility by   android:visibility="gone",when you clicked the first button  to activate the button to display,make it to visible by getting the id of the corresponding button
  for eg: btn2.setVisibility(View.VISIBLE);</p>