问:
How do I put 2D array to use?
I've used i and j array to hold values, is there a way to combine both by using multidimension array or condense another way?</p>

```<code>Dim iArray
Dim jArray
With wks.Range("B2:B" & p)
    iArray = .Value
End With
With CreateObject("scripting.dictionary")
.comparemode = 2
    For Each item In iArray
        If Not .exists(item) Then
        .Add item, Nothing
        End If
    Next
        If .Count Then
            Me.Search1.List = Application.Transpose(.keys)
        End If
End With

With wks.Range("c2:c" & p)
    jArray = .Value
End With
With CreateObject("scripting.dictionary")
.comparemode = 1
    For Each item In jArray
        If Not .exists(item) Then
        .Add item, Nothing
        End If
    Next
        If .Count Then
            Me.Search2.List = Application.Transpose(.keys)
        End If
End With
</code>```

答:
You should consider extracting that functionality to a standalone sub which you can cell with parameters:

```<code>Sub ListUniquesFromRange(rng As Range, lst As Object)
    Dim iArray, v
    If rng.Columns.Count > 1 Then
        MsgBox "single-column range only!", vbCritical
        Exit Sub
    End If
    iArray = rng.Value
    With CreateObject("scripting.dictionary")
        .comparemode = 2
        For Each v In iArray
            If Not .exists(v) Then .Add v, Nothing
        Next
        If .Count Then
            lst.List = Application.Transpose(.keys)
        End If
    End With
End Sub
</code>```

Then you can do this:

```<code>ListUniquesFromRange wks.Range("B2:B" & p), Me.Search1
ListUniquesFromRange wks.Range("C2:C" & p), Me.Search2
</code>```

Title: How do I put 2D array to use?

Body:
I've used i and j array to hold values, is there a way to combine both by using multidimension array or condense another way?

Dim iArray
Dim jArray
With wks.Range("B2:B" & p)
    iArray = .Value
End With
With CreateObject("scripting.dictionary")
.comparemode = 2
    For Each item In iArray
        If Not .exists(item) Then
        .Add item, Nothing
        End If
    Next
        If .Count Then
            Me.Search1.List = Application.Transpose(.keys)
        End If
End With

With wks.Range("c2:c" & p)
    jArray = .Value
End With
With CreateObject("scripting.dictionary")
.comparemode = 1
    For Each item In jArray
        If Not .exists(item) Then
        .Add item, Nothing
        End If
    Next
        If .Count Then
            Me.Search2.List = Application.Transpose(.keys)
        End If
End With

Body:
You should consider extracting that functionality to a standalone sub which you can cell with parameters:

Sub ListUniquesFromRange(rng As Range, lst As Object)
    Dim iArray, v
    If rng.Columns.Count > 1 Then
        MsgBox "single-column range only!", vbCritical
        Exit Sub
    End If
    iArray = rng.Value
    With CreateObject("scripting.dictionary")
        .comparemode = 2
        For Each v In iArray
            If Not .exists(v) Then .Add v, Nothing
        Next
        If .Count Then
            lst.List = Application.Transpose(.keys)
        End If
    End With
End Sub

Then you can do this:

ListUniquesFromRange wks.Range("B2:B" & p), Me.Search1
ListUniquesFromRange wks.Range("C2:C" & p), Me.Search2


来源: stackexchange

问:
Saving slope of each iteration from a loop in R
Have data variables (tcons and tleave). Trying to modify the below loop to extract/save the slopes for each iteration and plot the slope values as a histogram. Not sure how to find/ save the slopes. Any help would be appreciated.</p>

```<code>plot(tcons,tleave, xlab="Time spent with conspecific (seconds)", ylab =
"Time taken to leave a refuge (seconds)", main="Time spent with
conspecific vs Time taken to leave refuge")

for(i in 1:10000) {print
  (abline(lm(sample(tcons)~tleave), col="lightgrey"))
    print(i)}
</code>```

答:
```<code>model1 <- lm(sample(tcons)~tleave)
slope <- model1$coefficients[2]
</code>```

Then loop through and save as needed

ContentLicense: CC BY-SA 3.0

Body:
Have data variables (tcons and tleave). Trying to modify the below loop to extract/save the slopes for each iteration and plot the slope values as a histogram. Not sure how to find/ save the slopes. Any help would be appreciated.

plot(tcons,tleave, xlab="Time spent with conspecific (seconds)", ylab =
"Time taken to leave a refuge (seconds)", main="Time spent with
conspecific vs Time taken to leave refuge")

for(i in 1:10000) {print
  (abline(lm(sample(tcons)~tleave), col="lightgrey"))
    print(i)}

Body:
model1 <- lm(sample(tcons)~tleave)
slope <- model1$coefficients[2]

Then loop through and save as needed


问:
DataTables: How do I disable row selection for editable columns
I have a simple datable in which I have made one column (no. 4) editable using jeditable similarly to the example on the datatables.net:

```<code>oTable.$('td:eq(4)').editable(function(value, settings) {
var valueOld = oTable.fnGetData(this);
if(valueOld != value) {
    alert("changed");
}
else {
    alert ("unchanged");
}
    return(value);
},
{
type    : 'textarea',
submit:'OK'
});
</code>```

I also want to be able to select a row by clicking on it (again as per the example on datatables.net):

```<code>$('#example tr').click( function() {
    $(this).toggleClass('row_selected');
});
</code>```

However, it does not make sense that the row is selected when the user clicks on column 4 of that row because that cell is editable.  How do I disable row selection when clicking on this editable column?

I am not using TableTools.

答:
Though this question was asked and answered when the older version was prevalent, for anyone using the current version, this works well:

```<code>select: {
  style:    'os',   //default but you have to specify it, no idea why
  selector: 'tr:not(.no-select) td'
}
</code>```

Then manage which rows are unselectable by tacking the no-select class on them.

Via https://datatables.net/forums/discussion/30597/prevent-row-selection

Side note: don't know whether the style re-definition is still an issue. You can try w/o and see if the wheels come off.

Body:
I have a simple datable in which I have made one column (no. 4) editable using jeditable similarly to the example on the datatables.net:

oTable.$('td:eq(4)').editable(function(value, settings) {
var valueOld = oTable.fnGetData(this);
if(valueOld != value) {
    alert("changed");
}
else {
    alert ("unchanged");
}
    return(value);
},
{
type    : 'textarea',
submit:'OK'
});

I also want to be able to select a row by clicking on it (again as per the example on datatables.net):

$('#example tr').click( function() {
    $(this).toggleClass('row_selected');
});

However, it does not make sense that the row is selected when the user clicks on column 4 of that row because that cell is editable.  How do I disable row selection when clicking on this editable column?

I am not using TableTools.

Body:
Though this question was asked and answered when the older version was prevalent, for anyone using the current version, this works well:

select: {
  style:    'os',   //default but you have to specify it, no idea why
  selector: 'tr:not(.no-select) td'
}

Then manage which rows are unselectable by tacking the no-select class on them.

Via https://datatables.net/forums/discussion/30597/prevent-row-selection

Side note: don't know whether the style re-definition is still an issue. You can try w/o and see if the wheels come off.


答:
Ignoring the wrong model formulation, here's how you can save all the coefficients into a list and then merge this list into a data.frame. Now each coefficient is a variable.</p>

```<code>N <- 10000
out <- vector("list", N)

for(i in 1:N) {
  mdl <- lm(sample(tcons)~tleave)
  out[i] <- coef(mdl)
}

out <- do.call(rbind, out)

hist(out[, 2]) # you can then plot histogram from slope, for example
</code>```

Title: Saving slope of each iteration from a loop in R

Body:
Ignoring the wrong model formulation, here's how you can save all the coefficients into a list and then merge this list into a data.frame. Now each coefficient is a variable.

N <- 10000
out <- vector("list", N)

for(i in 1:N) {
  mdl <- lm(sample(tcons)~tleave)
  out[i] <- coef(mdl)
}

out <- do.call(rbind, out)

hist(out[, 2]) # you can then plot histogram from slope, for example


问:
Saving CKAsset from Core Data
I have some data like pictures, stored in Core Data as binary data and marked as "Allows External Storage". I'd like to write this data to the CloudKit. Is it possible to get URLs for this data and pass it to CKAsset, or transform somehow this data to CKAsset without double writing this data to some temporary files? Thank you.</p>

答:
Accessing external binary data directly is not supported and there's no API for it. Unofficially it's not hard to figure out what directory the files are stored in, but it's not useful because

Filenames are UUIDs, and there's no documented way to link a managed object to a UUID, so you don't know which file to use.

The option is to allow external storage, so there's no guarantee that an external file exists. Some instances may not use external storage.

I'm not sure what CKAsset requires but you'll have to look up the binary data via the managed object first.

Title: Saving CKAsset from Core Data


问:
get element from inside webview javascript chrome app
I've been searching on google for a while now and I couldn't really find much regarding this topic so I wanted to know if it's even possible:

Can I get an html element from a loaded page inside a <webview> and
  store it's attributes for later use outside of my <webview>?

答: You can use webview.executeScript along with postMessage to communicate the data back out of the webview</p>


问:
.htaccess if statements for different .htpasswd files
I'm not entirely sure this is possible, but I have an application that is hosted on a few different URLs and a few different subdomains.

Each of these has a basic protected section (using htpasswd).

I'd love to be able to have ONE htaccess file, rather than having a bunch of different ones that point to different files.

I have the following file structure:

.htaccess
.htpasswd-domainone
.htpasswd-domaintwo
.htpasswd-domainthree

Is there a way to do something like this?

```<code><If "%{HTTP_HOST} == 'domainone'">
AuthUserFile /file/location/.htpasswd-domainone
</If>

<If "%{HTTP_HOST} == 'domaintwo'">
AuthUserFile /file/location/.htpasswd-domaintwo
</If>

<If "%{HTTP_HOST} == 'domainthree'">
AuthUserFile /file/location/.htpasswd-domainthree
</If>
</code>```

Taking subdomains into account?

答:
Assuming Apache 2.4, the following works:</p>

```<code>Options -Indexes

AuthName Login
AuthType Basic
require valid-user

<If "%{HTTP_HOST} == 'sub.domain1.com'">
AuthUserFile /var/www/html/admin/.htpasswd-domain1
Deny from all
Satisfy any
</If>
<ElseIf "%{HTTP_HOST} == 'sub2.domain1.com'">
AuthUserFile /var/www/html/admin/.htpasswd-domain2
Deny from all
Satisfy any
</ElseIf>
<Else>
Allow from all
Satisfy any
</Else>
</code>```

Body:
I'm not entirely sure this is possible, but I have an application that is hosted on a few different URLs and a few different subdomains.

Each of these has a basic protected section (using htpasswd).

I'd love to be able to have ONE htaccess file, rather than having a bunch of different ones that point to different files.

I have the following file structure:

.htaccess
.htpasswd-domainone
.htpasswd-domaintwo
.htpasswd-domainthree

Is there a way to do something like this?

<If "%{HTTP_HOST} == 'domainone'">
AuthUserFile /file/location/.htpasswd-domainone
</If>

<If "%{HTTP_HOST} == 'domaintwo'">
AuthUserFile /file/location/.htpasswd-domaintwo
</If>

<If "%{HTTP_HOST} == 'domainthree'">
AuthUserFile /file/location/.htpasswd-domainthree
</If>

Taking subdomains into account?

Body:
Assuming Apache 2.4, the following works:

Options -Indexes

AuthName Login
AuthType Basic
require valid-user

<If "%{HTTP_HOST} == 'sub.domain1.com'">
AuthUserFile /var/www/html/admin/.htpasswd-domain1
Deny from all
Satisfy any
</If>
<ElseIf "%{HTTP_HOST} == 'sub2.domain1.com'">
AuthUserFile /var/www/html/admin/.htpasswd-domain2
Deny from all
Satisfy any
</ElseIf>
<Else>
Allow from all
Satisfy any
</Else>


问:
Django fixture with all possible combinations?
I am trying to test a statistics function, which counts what type of objects I have in my database. For this I would like to create at least one instance of each possible combination of model fields. Random test data requires a lot of test objects to make sure all possible combinations are met.

Here is a shortened example from one of my models:

```<code>class Member(models.Model)
    is_active = models.BooleanField()
    name = models.CharField()
    balance = models.IntegerField()
    division = models.ForeignKey(Division, on_delete=models.CASCADE)

Class Division(models.Model)
    name = models.CharField()
</code>```

This is how I'm doing it right now using django_dynamic_fixture:

```<code>from django.test import TestCase
from django_dynamic_fixture import G
from members.models import Member

class StatisticsTestCase(TestCase):
    def setUp(self):
        for is_active in [True, False]:
            for balance in [-100, 0, 100]:
                for division in Division.objects.all()
                    G(Member, is_active=is_active, balance=balance, division=division)
</code>```

But this looks pretty bad and is hard to read. Is there a simpler way with better to read code to create all possible combinations of properties of an object?

I'm open to different test data generators as long as they work nicely with Python 3 and Django.

答:
Sara's answer is a good step forward, but I am still not satisfied by the code readability, so I am answering my own question.

```<code>variants = {
    'is_active': [True, False],
    'balance': [-100, 0, 100],
    'division': list(Division.objects.all())
}

names = sorted(variants)
products = [dict(zip(names, prod)) for prod in it.product(*(variants[name] for name in names))]

for combination in products:
    G(Member, **combination)
</code>```

Now anyone wanting to change this test can easily see which property is tested with which values. Thanks go to this q&a for the dict solution.

Body:
I am trying to test a statistics function, which counts what type of objects I have in my database. For this I would like to create at least one instance of each possible combination of model fields. Random test data requires a lot of test objects to make sure all possible combinations are met.

Here is a shortened example from one of my models:

class Member(models.Model)
    is_active = models.BooleanField()
    name = models.CharField()
    balance = models.IntegerField()
    division = models.ForeignKey(Division, on_delete=models.CASCADE)

Class Division(models.Model)
    name = models.CharField()

This is how I'm doing it right now using django_dynamic_fixture:

from django.test import TestCase
from django_dynamic_fixture import G
from members.models import Member

class StatisticsTestCase(TestCase):
    def setUp(self):
        for is_active in [True, False]:
            for balance in [-100, 0, 100]:
                for division in Division.objects.all()
                    G(Member, is_active=is_active, balance=balance, division=division)

But this looks pretty bad and is hard to read. Is there a simpler way with better to read code to create all possible combinations of properties of an object?

I'm open to different test data generators as long as they work nicely with Python 3 and Django.

Body:
Sara's answer is a good step forward, but I am still not satisfied by the code readability, so I am answering my own question.

variants = {
    'is_active': [True, False],
    'balance': [-100, 0, 100],
    'division': list(Division.objects.all())
}

names = sorted(variants)
products = [dict(zip(names, prod)) for prod in it.product(*(variants[name] for name in names))]

for combination in products:
    G(Member, **combination)

Now anyone wanting to change this test can easily see which property is tested with which values. Thanks go to this q&a for the dict solution.


问:
Changing the array's value through a function
The function saves the new string and sets it at position 2. But when I run the last "for" there are just some strange symbols.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

void edit(int target, char *listf[]){

    char *name[1];

    printf("\nInsert the new name: \n");
    scanf("%s", &name[0]);
    listf[target] = &name[0];

    printf("\nThe information has change!\n");
    printf("Name: %s\n", listf[target]);
    system("pause");   }

int main() {
    char *listf[3] = {"Alpha", "Beta", "Omega"};

    int i;
    int target = 2;

    for(i = 0; i < 3; i++){
        printf("%s\n", listf[i]);
    }

    edit(target,listf);
    printf(" \n\n");

    for(i = 0; i < 3; i++){
        printf("%s\n", listf[i]);
    }

    return 0; }
</code>```

答:
There are two problems with your code. First, the char name is an array of pointers, essentially. And those pointers.......they are not pointing to allocated memory, just garbage data. If you want to make good use of it, you have to assign a pointer to an allocated memory. Now, normally, when you use a function like scanf, they assume that the pointer you given to it(in this case &name[0]) have allocated memory to store the input string. But if you dont do this, your pointer would be pointing to a random address in the memory, possibly editing some other memory cells and causing your program to behave very strangely. So how do you solve this? I'm not claiming my solution to be perfect, but just use a plain char array, preferably a large one, to store the input string. Like this-

```<code>char name[1000];
</code>```

The second problem is this line-

```<code>listf[target] = &name[0];
</code>```

The thing here is that the data the name array is pointing to, is temporary. It will only last as long as the function edit() runs. Why? A simple way to say this is that, name belongs to the edit() function. So when edit() terminates, so does everything along with it. Meaning char name wont store whatever you put into it. This is the reason why you were getting strange symbols. So you have to put the contents of the input in another place in the memory. So you'll have to use malloc() here. Here's my fixed version of the edit function-

```<code>void edit(int target, char *listf[]){

char name[1000];

printf("\nInsert the new name: \n");
scanf("%s", name);

//figure out the length of the string and allocate memory accordingly
int len = strlen(name);
char* new_name = malloc(len * sizeof(char));

printf("Test %d\n", len * sizeof(char));

//copy the contents of name to new_name
strcpy(new_name,name);
listf[target] = new_name;

printf("\nThe information has change!\n");
printf("Name: %s\n", listf[target]);
system("pause");

}
</code>```

Body:
The function saves the new string and sets it at position 2. But when I run the last "for" there are just some strange symbols.

#include <stdio.h>
#include <stdlib.h>

void edit(int target, char *listf[]){

    char *name[1];

    printf("\nInsert the new name: \n");
    scanf("%s", &name[0]);
    listf[target] = &name[0];

    printf("\nThe information has change!\n");
    printf("Name: %s\n", listf[target]);
    system("pause");   }

int main() {
    char *listf[3] = {"Alpha", "Beta", "Omega"};

    int i;
    int target = 2;

    for(i = 0; i < 3; i++){
        printf("%s\n", listf[i]);
    }

    edit(target,listf);
    printf(" \n\n");

    for(i = 0; i < 3; i++){
        printf("%s\n", listf[i]);
    }

    return 0; }

Body:
There are two problems with your code. First, the char name is an array of pointers, essentially. And those pointers.......they are not pointing to allocated memory, just garbage data. If you want to make good use of it, you have to assign a pointer to an allocated memory. Now, normally, when you use a function like scanf, they assume that the pointer you given to it(in this case &name[0]) have allocated memory to store the input string. But if you dont do this, your pointer would be pointing to a random address in the memory, possibly editing some other memory cells and causing your program to behave very strangely. So how do you solve this? I'm not claiming my solution to be perfect, but just use a plain char array, preferably a large one, to store the input string. Like this-

char name[1000];

The second problem is this line-

listf[target] = &name[0];

The thing here is that the data the name array is pointing to, is temporary. It will only last as long as the function edit() runs. Why? A simple way to say this is that, name belongs to the edit() function. So when edit() terminates, so does everything along with it. Meaning char name wont store whatever you put into it. This is the reason why you were getting strange symbols. So you have to put the contents of the input in another place in the memory. So you'll have to use malloc() here. Here's my fixed version of the edit function-

void edit(int target, char *listf[]){

char name[1000];

printf("\nInsert the new name: \n");
scanf("%s", name);

//figure out the length of the string and allocate memory accordingly
int len = strlen(name);
char* new_name = malloc(len * sizeof(char));

printf("Test %d\n", len * sizeof(char));

//copy the contents of name to new_name
strcpy(new_name,name);
listf[target] = new_name;

printf("\nThe information has change!\n");
printf("Name: %s\n", listf[target]);
system("pause");

}


问:
Word comparison algorithm
I am doing a CSV Import tool for the project I'm working on.
The client needs to be able to enter the data in excel, export them as CSV and upload them to the database.
For example I have this CSV record:

```<code>   1,   John Doe,     ACME Comapny   (the typo is on purpose)
</code>```

Of course, the companies are kept in a separate table and linked with a foreign key, so I need to discover the correct company ID before inserting.
I plan to do this by comparing the company names in the database with the company names in the CSV.
the comparison should return 0 if the strings are exactly the same, and return some value that gets bigger as the strings get more different, but strcmp doesn't cut it here because:

"Acme Company" and "Acme Comapny" should have a very small difference index, but
"Acme Company" and "Cmea Mpnyaco" should have a very big difference index
Or "Acme Company" and "Acme Comp." should also have a small difference index, even though the character count is different.
Also, "Acme Company" and "Company Acme" should return 0.

So if the client makes a type while entering data, i could prompt him to choose the name he most probably wanted to insert.

Is there a known algorithm to do this, or maybe we can invent one :)
?

答:
I have actually implemented a similar system. I used the Levenshtein distance (as other posters already suggested), with some modifications. The problem with unmodified edit distance (applied to whole strings) is that it is sensitive to word reordering, so "Acme Digital Incorporated World Company" will match poorly against "Digital Incorporated  World Company Acme" and such reorderings were quite common in my data.

I modified it so that if the edit distance of whole strings was too big, the algorithm fell back to matching words against each other to find a good word-to-word match (quadratic cost, but there was a cutoff if there were too many words, so it worked OK).

OwnerDisplayName: Discodancer

ContentLicense: CC BY-SA 2.5

Title: Word comparison algorithm

Body:
I am doing a CSV Import tool for the project I'm working on.
The client needs to be able to enter the data in excel, export them as CSV and upload them to the database.
For example I have this CSV record:

   1,   John Doe,     ACME Comapny   (the typo is on purpose)

Of course, the companies are kept in a separate table and linked with a foreign key, so I need to discover the correct company ID before inserting.
I plan to do this by comparing the company names in the database with the company names in the CSV.
the comparison should return 0 if the strings are exactly the same, and return some value that gets bigger as the strings get more different, but strcmp doesn't cut it here because:

"Acme Company" and "Acme Comapny" should have a very small difference index, but
"Acme Company" and "Cmea Mpnyaco" should have a very big difference index
Or "Acme Company" and "Acme Comp." should also have a small difference index, even though the character count is different.
Also, "Acme Company" and "Company Acme" should return 0.

So if the client makes a type while entering data, i could prompt him to choose the name he most probably wanted to insert.

Is there a known algorithm to do this, or maybe we can invent one :)
?

OwnerDisplayName: Rafał Dowgird


问:
Magento: template based on attribute set
I want to create different product views based on the attribute set the product belongs to:
does Magento provide a way to do this?

- UPDATE -

Following dan.codes suggestion I've added

```<code>$update->addHandle('PRODUCT_ATTRIBUTE_SET_ID_'.$product->getAttributeSetId());
</code>```

to Mage_Catalog_ProductController (I duplicated ProductController.php and put it in local/Mage/Catalog/controllers/).

Then I added this to catalog.xml

```<code><PRODUCT_ATTRIBUTE_SET_ID_9> // PRODUCT ID of Book Attribute Set
    <label>Catalog Product View (Book)</label>
    <reference name="product.info">
        <block type="catalog/product_view_type_book" name="product.info.book" as="product_type_data" template="catalog/product/view/attribute_set/book.phtml">
            <block type="core/text_list" name="product.info.book.extra" as="product_type_data_extra"/>
        </block>
    </reference>
</PRODUCT_ATTRIBUTE_SET_ID_9>
</code>```

just after

```<code><PRODUCT_TYPE_virtual translate="label" module="catalog">
    <label>Catalog Product View (Virtual)</label>
    <reference name="product.info">
        <block type="catalog/product_view_type_virtual" name="product.info.virtual" as="product_type_data" template="catalog/product/view/type/virtual.phtml">
            <block type="core/text_list" name="product.info.virtual.extra" as="product_type_data_extra"/>
        </block>
    </reference>
</PRODUCT_TYPE_virtual>
</code>```

I then created catalog/product/view/attribute_set/book.phtml, but it is not displayed in my product view page.

- UPDATE MAGENTO 1.5 -

I've noticed that the handler update has moved in the last Magento release.

```<code>$update->addHandle('PRODUCT_TYPE_'.$product->getTypeId());
$update->addHandle('PRODUCT_'.$product->getId());
</code>```

is in Mage/Catalog/Helper/Product/View.php now.

I've tested and it still works great!

答:
No it doesn't but you can extend the functionality to do so by extending the _initProductLayout method in Mage_Catalog_ProductController under where the code is this

```<code>    $update = $this->getLayout()->getUpdate();
    $update->addHandle('default');
    $this->addActionLayoutHandles();

    $update->addHandle('PRODUCT_TYPE_'.$product->getTypeId());
    $update->addHandle('PRODUCT_'.$product->getId());
</code>```

You could add

```<code>$update->addHandle('PRODUCT_ATTRIBUTE_SET_ID_'.$product->getAttributeSetId());
</code>```

Then in your layout.xml you could have

```<code><PRODUCT_ATTRIBUTE_SET_ID_IDHERE>
  <reference name="root">
            <action method="setTemplate"><template>template/path/here.html</template></action>
        </reference>
</PRODUCT_ATTRIBUTE_SET_ID_IDHERE>
</code>```

Body:
I want to create different product views based on the attribute set the product belongs to:
does Magento provide a way to do this?

- UPDATE -

Following dan.codes suggestion I've added

$update->addHandle('PRODUCT_ATTRIBUTE_SET_ID_'.$product->getAttributeSetId());

to Mage_Catalog_ProductController (I duplicated ProductController.php and put it in local/Mage/Catalog/controllers/).

Then I added this to catalog.xml

<PRODUCT_ATTRIBUTE_SET_ID_9> // PRODUCT ID of Book Attribute Set
    Catalog Product View (Book)
    <reference name="product.info">
        <block type="catalog/product_view_type_book" name="product.info.book" as="product_type_data" template="catalog/product/view/attribute_set/book.phtml">
            <block type="core/text_list" name="product.info.book.extra" as="product_type_data_extra"/>
        </block>
    </reference>
</PRODUCT_ATTRIBUTE_SET_ID_9>

just after

<PRODUCT_TYPE_virtual translate="label" module="catalog">
    Catalog Product View (Virtual)
    <reference name="product.info">
        <block type="catalog/product_view_type_virtual" name="product.info.virtual" as="product_type_data" template="catalog/product/view/type/virtual.phtml">
            <block type="core/text_list" name="product.info.virtual.extra" as="product_type_data_extra"/>
        </block>
    </reference>
</PRODUCT_TYPE_virtual>

I then created catalog/product/view/attribute_set/book.phtml, but it is not displayed in my product view page.

- UPDATE MAGENTO 1.5 -

I've noticed that the handler update has moved in the last Magento release.

$update->addHandle('PRODUCT_TYPE_'.$product->getTypeId());
$update->addHandle('PRODUCT_'.$product->getId());

is in Mage/Catalog/Helper/Product/View.php now.

I've tested and it still works great!

Body:
No it doesn't but you can extend the functionality to do so by extending the _initProductLayout method in Mage_Catalog_ProductController under where the code is this

    $update = $this->getLayout()->getUpdate();
    $update->addHandle('default');
    $this->addActionLayoutHandles();

    $update->addHandle('PRODUCT_TYPE_'.$product->getTypeId());
    $update->addHandle('PRODUCT_'.$product->getId());

You could add

$update->addHandle('PRODUCT_ATTRIBUTE_SET_ID_'.$product->getAttributeSetId());

Then in your layout.xml you could have

<PRODUCT_ATTRIBUTE_SET_ID_IDHERE>
  <reference name="root">
            <action method="setTemplate"><template>template/path/here.html</template></action>
        </reference>
</PRODUCT_ATTRIBUTE_SET_ID_IDHERE>


问:
Why doesn't Android Studio recognize the ActionCodeSettings class when trying to implement Firebase Auth email verification?
I have successfully implemented the Firebase Authentication and have that working fine. I want to be able to send out Email verification emails and password reset emails but the code snippet I copied from Firebase Docs has the ActionCodeSettings class and it is not being recognized. I think it's supposed to be apart of the framework that comes with Firebase Auth???</p>

```<code>   private void sendVerEmail(){
    FirebaseUser user = mAuth.getCurrentUser();
    String url = "http://www.example.com/verify?uid=" + user.getUid();

    ActionCodeSettings actionCodeSettings = ActionCodeSettings.newBuilder()
            .setUrl(url)
            .setIOSBundleId("com.example.ios")
            // The default for this is populated with the current android package name.
            .setAndroidPackageName("com.example.android", false, null)
            .build();

    user.sendEmailVerification(actionCodeSettings)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "Email sent.");
                    }
                }
            });
}
</code>```

答:
You must be using an old version when this class was not supported. This was added to SDK Version 11.4.0: https://firebase.google.com/support/release-notes/android#20170918

Better upgrade to the latest version.

Body:
I have successfully implemented the Firebase Authentication and have that working fine. I want to be able to send out Email verification emails and password reset emails but the code snippet I copied from Firebase Docs has the ActionCodeSettings class and it is not being recognized. I think it's supposed to be apart of the framework that comes with Firebase Auth???

   private void sendVerEmail(){
    FirebaseUser user = mAuth.getCurrentUser();
    String url = "http://www.example.com/verify?uid=" + user.getUid();

    ActionCodeSettings actionCodeSettings = ActionCodeSettings.newBuilder()
            .setUrl(url)
            .setIOSBundleId("com.example.ios")
            // The default for this is populated with the current android package name.
            .setAndroidPackageName("com.example.android", false, null)
            .build();

    user.sendEmailVerification(actionCodeSettings)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "Email sent.");
                    }
                }
            });
}


问:
How provide default value in date in primeng
I have calendar dropdown, it is working. However, I want to provide default date in it. How can it  do that.

Following is my component as follows:

```<code>import {HttpClient} from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { routerTransition } from '../../router.animations';
import { isNumber } from '@ng-bootstrap/ng-bootstrap/util/util';

@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.scss'],
    animations: [routerTransition()]
})
export class DashboardComponent implements OnInit {
   value= new Date();
   today_date: string;

   ngOnInit() {
      this.today_date = this.value.getFullYear() + '-' + this.value.getMonth() + '-' + this.value.getDate();
      console.log(this.today_date)
   }
}
</code>```

HTML code is as follows:

```<code><div>
     <p-calendar (ngModel)="today_date" [inputStyle]="{'width':'100%'}" dateFormat="yy-mm-dd"></p-calendar>
</div>
</code>```

It is not picking date up. Console.log out is '2017/10/17'

答:
To my understanding, value of p-calendar is of type Date. So a string wouldn't work. Here's what I have for mine and it works quite well:

```<code>TS
import * as moment from "moment"; //I use MomentJS and I recommend it also. The snippet is based on MomentJS as well.
calendarDate: Date;
ngOnInit() {
 this.calendarDate = moment().toDate();
}

HTML
<p-calendar [ngModel]="calendarDate"></p-calendar>
</code>```

EDIT: You have a wrong syntax in your HTML template. (ngModel) does not make any sense. It should be [ngModel] for Property Binding, or (ngModelChange) for Event Binding, or [(ngModel)] for two-way binding.

Body:
I have calendar dropdown, it is working. However, I want to provide default date in it. How can it  do that.

Following is my component as follows:

import {HttpClient} from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { routerTransition } from '../../router.animations';
import { isNumber } from '@ng-bootstrap/ng-bootstrap/util/util';

@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.scss'],
    animations: [routerTransition()]
})
export class DashboardComponent implements OnInit {
   value= new Date();
   today_date: string;

   ngOnInit() {
      this.today_date = this.value.getFullYear() + '-' + this.value.getMonth() + '-' + this.value.getDate();
      console.log(this.today_date)
   }
}

HTML code is as follows:

It is not picking date up. Console.log out is '2017/10/17'

Body:
To my understanding, value of p-calendar is of type Date. So a string wouldn't work. Here's what I have for mine and it works quite well:

TS
import * as moment from "moment"; //I use MomentJS and I recommend it also. The snippet is based on MomentJS as well.
calendarDate: Date;
ngOnInit() {
 this.calendarDate = moment().toDate();
}

HTML
<p-calendar [ngModel]="calendarDate"></p-calendar>

EDIT: You have a wrong syntax in your HTML template. (ngModel) does not make any sense. It should be [ngModel] for Property Binding, or (ngModelChange) for Event Binding, or [(ngModel)] for two-way binding.


问:
How to call onchage function in another function
How can I call onchage function in another function?

My first function:

```<code>$('.input-number').change(function() {
// my code here
}
</code>```

and my second function:

```<code>$(function(){
        $(document).on('change', '.destination', function() {
            // my code here
            $.ajax({
                    url: 'myurl',
                    data: mydata,
                    type: "post",
                    success: function(data){
                        // my code here
                        // here i must call $('.input-number').change(function()) to refresh my first code
                    }
            });
</code>```

答:
You need to trigger the event programmatically using trigger() method.

```<code>$('.input-number').trigger('change');

// or use shorthandler
$('.input-number').change();
</code>```

Body:
How can I call onchage function in another function?

My first function:

$('.input-number').change(function() {
// my code here
}

and my second function:

$(function(){
        $(document).on('change', '.destination', function() {
            // my code here
            $.ajax({
                    url: 'myurl',
                    data: mydata,
                    type: "post",
                    success: function(data){
                        // my code here
                        // here i must call $('.input-number').change(function()) to refresh my first code
                    }
            });

Body:
You need to trigger the event programmatically using trigger() method.

$('.input-number').trigger('change');

// or use shorthandler
$('.input-number').change();


答:
Personally I would use a Date Dimension table and use that table as the basis for the query. I find it far easier to use tabular data for these types of calculations as it leads to SQL that's easier to read and maintain. There's a great article on creating a Date Dimension table in PostgreSQL at https://medium.com/@duffn/creating-a-date-dimension-table-in-postgresql-af3f8e2941ac, though you could get away with a much simpler version of this table.

Ultimately what you would do is use the Date table as the base for the SELECT cols FROM table section and then join against that, or probably use Common Table Expressions, to create the calculations.

I'll write up a solution to that if you would like demonstrating how you could create such a query.

Title: PostgreSQL Crosstab generate_series of weeks for columns

Body:
From a table of "time entries" I'm trying to create a report of weekly totals for each user.

Sample of the table:

+-----+---------+-------------------------+--------------+
| id  | user_id | start_time              | hours_worked |
+-----+---------+-------------------------+--------------+
| 997 | 6       | 2018-01-01 03:05:00 UTC | 1.0          |
| 996 | 6       | 2017-12-01 05:05:00 UTC | 1.0          |
| 998 | 6       | 2017-12-01 05:05:00 UTC | 1.5          |
| 999 | 20      | 2017-11-15 19:00:00 UTC | 1.0          |
| 995 | 6       | 2017-11-11 20:47:42 UTC | 0.04         |
+-----+---------+-------------------------+--------------+

Right now I can run the following and basically get what I need

SELECT COALESCE(SUM(time_entries.hours_worked),0) AS total,
  time_entries.user_id,
  week::date

--Using generate_series here to account for weeks with no time entries when
--doing the join

FROM generate_series( (DATE_TRUNC('week', '2017-11-01 00:00:00'::date)),
                      (DATE_TRUNC('week', '2017-12-31 23:59:59.999999'::date)),
                      interval '7 day') as week LEFT JOIN time_entries
ON DATE_TRUNC('week', time_entries.start_time) = week

GROUP BY week, time_entries.user_id
ORDER BY week

This will return

+-------+---------+------------+
| total | user_id | week       |
+-------+---------+------------+
| 14.08 | 5       | 2017-10-30 |
| 21.92 | 6       | 2017-10-30 |
| 10.92 | 7       | 2017-10-30 |
| 14.26 | 8       | 2017-10-30 |
| 14.78 | 10      | 2017-10-30 |
| 14.08 | 13      | 2017-10-30 |
| 15.83 | 15      | 2017-10-30 |
| 8.75  | 5       | 2017-11-06 |
| 10.53 | 6       | 2017-11-06 |
| 13.73 | 7       | 2017-11-06 |
| 14.26 | 8       | 2017-11-06 |
| 19.45 | 10      | 2017-11-06 |
| 15.95 | 13      | 2017-11-06 |
| 14.16 | 15      | 2017-11-06 |
| 1.00  | 20      | 2017-11-13 |
| 0     |         | 2017-11-20 |
| 2.50  | 6       | 2017-11-27 |
| 0     |         | 2017-12-04 |
| 0     |         | 2017-12-11 |
| 0     |         | 2017-12-18 |
| 0     |         | 2017-12-25 |
+-------+---------+------------+

However, this is difficult to parse particularly when there's no data for a week.  What I would like is a pivot or crosstab table where the weeks are the columns and the rows are the users.  And to include nulls from each (for instance if a user had no entries in that week or week without entries from any user).

Something like this

+---------+---------------+--------------+--------------+
| user_id | 2017-10-30    | 2017-11-06   | 2017-11-13   |
+---------+---------------+--------------+--------------+
| 6       | 4.0           | 1.0          | 0            |
| 7       | 4.0           | 1.0          | 0            |
| 8       | 4.0           | 0            | 0            |
| 9       | 0             | 1.0          | 0            |
| 10      | 4.0           | 0.04         | 0            |
+---------+---------------+--------------+--------------+

I've been looking around online and it seems that "dynamically" generating a list of columns for crosstab is difficult.  I'd rather not hard code them, which seems weird to do anyway for dates.  Or use something like this case with week number.

Should I look for another solution besides crosstab?  If I could get the series of weeks for each user including all nulls I think that would be good enough.  It just seems that right now my join strategy isn't returning that.


问:
manifest.xml XML Parsing Error: not well-formed
I'm a newbie, I use the android sdk on ubuntu and downloaded a few free android apps, when I tried to load them onto the sdk using eclipse, it gives an XML parser error. I am unable to view the source code of the application too.

If I try opening the xml file using a browser, I get

```<code>XML Parsing Error: not well-formed
Location: file:///home/Downloads/apks/BlueFTP.apk_FILES/AndroidManifest.xml
Line Number 1, Column 1:
</code>```

Has anyone encountered such a problem? Any solutions please?

Content of manifest.xml

```<code>  <    ü      >                        4   @   N   Z   x   ž   ²   À   Ô   æ   ô     6  R  p  Œ  ¤  ¶      $  8  b  n  ˆ  œ  ¬  Ê  Ú    &  j  z  ¼  ô  >  J  T  v  ˆ     ¼    l  ~  Ô  *  >  ˆ  Ô  ê    4  H  j  ¤  à  (  l  Â   v e r s i o n N a m e    v e r s i o n C o d e    i c o n    l a b e l    n a m e
 c o n f i g C h a n g e s    s c r e e n O r i e n t a t i o n    m i m e T y p e    t h e m e    e x p o r t e d    e n a b l e d    v a l u e
 m i n S d k V e r s i o n    t a r g e t S d k V e r s i o n    s m a l l S c r e e n s
 n o r m a l S c r e e n s    l a r g e S c r e e n s
 a n y D e n s i t y    a n d r o i d   * h t t p : / / s c h e m a s . a n d r o i d . c o m / a p k / r e s / a n d r o i d        p a c k a g e    m a n i f e s t    i t . m e d i e v a l . b l u e f t p    2 . 5 0    a p p l i c a t i o n    a c t i v i t y    . A M a i n
 i n t e n t - f i l t e r    a c t i o n    a n d r o i d . i n t e n t . a c t i o n . M A I N    c a t e g o r y     a n d r o i d . i n t e n t . c a t e g o r y . L A U N C H E R    . A S e n d    a n d r o i d . i n t e n t . c a t e g o r y . D E F A U L T    a n d r o i d . i n t e n t . a c t i o n . S E N D   # a n d r o i d . i n t e n t . a c t i o n . S E N D _ M U L T I P L E    d a t a    * / *    . A C o n t a c t P i c k e r    . A A b o u t
 . A S e t t i n g s    . B u g s M e s s a g e   * . b l u e t o o t h _ s e r v e r s . o p p _ s e r v e r . N o t i f y M e x O P P   * . b l u e t o o t h _ s e r v e r s . f t p _ s e r v e r . N o t i f y M e x F T P    s e r v i c e   ) . b l u e t o o t h _ s e r v e r s . o p p _ s e r v e r . O P P _ S e r v i c e   ) . b l u e t o o t h _ s e r v e r s . f t p _ s e r v e r . F T P _ S e r v i c e    r e c e i v e r   # . b l u e t o o t h _ s e r v e r s . S e r v i c e s L a u n c h e r   $ a n d r o i d . i n t e n t . a c t i o n . B O O T _ C O M P L E T E D        m e t a - d a t a    A D M O B _ P U B L I S H E R _ I D    a 1 4 a a e 1 d 0 8 3 a 7 1 0    u s e s - s d k    u s e s - p e r m i s s i o n    a n d r o i d . p e r m i s s i o n . I N T E R N E T    a n d r o i d . p e r m i s s i o n . B L U E T O O T H   " a n d r o i d . p e r m i s s i o n . B L U E T O O T H _ A D M I N     a n d r o i d . p e r m i s s i o n . R E A D _ C O N T A C T S   ) a n d r o i d . p e r m i s s i o n . W R I T E _ E X T E R N A L _ S T O R A G E    s u p p o r t s - s c r e e n s     € P        &     $ p„…†l        ÿÿÿÿ       `      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ                    ÿÿÿÿ            L      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ         ÿÿÿÿ  ,  t      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ                       ÿ
</code>```

答:
You can't extract APKs and load the resulting files into Eclipse to examine an app's source code. This is why the XML file is giving you XML parsing errors - it's not XML; it's the compiled form of XML.

All Android apps consist of human-readable Java source code and text XML documents. When compiled, these files get reduced to computer-readable Java classes and binary XML. These are then compressed into an APK and delivered to devices.

You can not reverse this process without the use of a decompiler, and even with a decompiler you will only get an approximation of the input.

If you want to learn how to program Android apps, may I suggest exploring the sample apps included in the SDK.

Body:
I'm a newbie, I use the android sdk on ubuntu and downloaded a few free android apps, when I tried to load them onto the sdk using eclipse, it gives an XML parser error. I am unable to view the source code of the application too.

If I try opening the xml file using a browser, I get

XML Parsing Error: not well-formed
Location: file:///home/Downloads/apks/BlueFTP.apk_FILES/AndroidManifest.xml
Line Number 1, Column 1:

Has anyone encountered such a problem? Any solutions please?

Content of manifest.xml

  <    ü      >                        4   @   N   Z   x   ž   ²   À   Ô   æ   ô     6  R  p  Œ  ¤  ¶      $  8  b  n  ˆ  œ  ¬  Ê  Ú    &  j  z  ¼  ô  >  J  T  v  ˆ     ¼    l  ~  Ô  *  >  ˆ  Ô  ê    4  H  j  ¤  à  (  l  Â   v e r s i o n N a m e    v e r s i o n C o d e    i c o n    l a b e l    n a m e
 c o n f i g C h a n g e s    s c r e e n O r i e n t a t i o n    m i m e T y p e    t h e m e    e x p o r t e d    e n a b l e d    v a l u e
 m i n S d k V e r s i o n    t a r g e t S d k V e r s i o n    s m a l l S c r e e n s
 n o r m a l S c r e e n s    l a r g e S c r e e n s
 a n y D e n s i t y    a n d r o i d   * h t t p : / / s c h e m a s . a n d r o i d . c o m / a p k / r e s / a n d r o i d        p a c k a g e    m a n i f e s t    i t . m e d i e v a l . b l u e f t p    2 . 5 0    a p p l i c a t i o n    a c t i v i t y    . A M a i n
 i n t e n t - f i l t e r    a c t i o n    a n d r o i d . i n t e n t . a c t i o n . M A I N    c a t e g o r y     a n d r o i d . i n t e n t . c a t e g o r y . L A U N C H E R    . A S e n d    a n d r o i d . i n t e n t . c a t e g o r y . D E F A U L T    a n d r o i d . i n t e n t . a c t i o n . S E N D   # a n d r o i d . i n t e n t . a c t i o n . S E N D _ M U L T I P L E    d a t a    * / *    . A C o n t a c t P i c k e r    . A A b o u t
 . A S e t t i n g s    . B u g s M e s s a g e   * . b l u e t o o t h _ s e r v e r s . o p p _ s e r v e r . N o t i f y M e x O P P   * . b l u e t o o t h _ s e r v e r s . f t p _ s e r v e r . N o t i f y M e x F T P    s e r v i c e   ) . b l u e t o o t h _ s e r v e r s . o p p _ s e r v e r . O P P _ S e r v i c e   ) . b l u e t o o t h _ s e r v e r s . f t p _ s e r v e r . F T P _ S e r v i c e    r e c e i v e r   # . b l u e t o o t h _ s e r v e r s . S e r v i c e s L a u n c h e r   $ a n d r o i d . i n t e n t . a c t i o n . B O O T _ C O M P L E T E D        m e t a - d a t a    A D M O B _ P U B L I S H E R _ I D    a 1 4 a a e 1 d 0 8 3 a 7 1 0    u s e s - s d k    u s e s - p e r m i s s i o n    a n d r o i d . p e r m i s s i o n . I N T E R N E T    a n d r o i d . p e r m i s s i o n . B L U E T O O T H   " a n d r o i d . p e r m i s s i o n . B L U E T O O T H _ A D M I N     a n d r o i d . p e r m i s s i o n . R E A D _ C O N T A C T S   ) a n d r o i d . p e r m i s s i o n . W R I T E _ E X T E R N A L _ S T O R A G E    s u p p o r t s - s c r e e n s     € P        &     $ p„…†l        ÿÿÿÿ       `      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ                    ÿÿÿÿ            L      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ         ÿÿÿÿ  ,  t      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ                       ÿ


问:
Add accuracy to data frame based on several predicted values and known actual values
I have a data frame

```<code>testdf <- data.frame(predicted1 = c(1, 0, 1, 3, 2, 1, 1, 0, 1, 0), predicted2 = c(1, 0, 2, 2, 2, 1, 1, 0, 0, 0), predicted3 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), actual = c(1, 0, 2, 3, 2, 1, 1, 1, 0, 0))
</code>```

I want to add another column to this data frame which tells me the total percentage accuracy when looking at all predicted values. So for example, row 1 of this would have an accuracy of 100%, because all prediction columns predicted the correct value (1).

How can this be done?

Thanks!

答:
We can compare with the 'actual' get the rowMeans, multiply by 100 and round if needed

```<code>round(100*rowMeans(testdf[1:3] == testdf$actual), 2)
</code>```

Body:
I have a data frame

testdf <- data.frame(predicted1 = c(1, 0, 1, 3, 2, 1, 1, 0, 1, 0), predicted2 = c(1, 0, 2, 2, 2, 1, 1, 0, 0, 0), predicted3 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), actual = c(1, 0, 2, 3, 2, 1, 1, 1, 0, 0))

I want to add another column to this data frame which tells me the total percentage accuracy when looking at all predicted values. So for example, row 1 of this would have an accuracy of 100%, because all prediction columns predicted the correct value (1).

How can this be done?

Thanks!

Body:
We can compare with the 'actual' get the rowMeans, multiply by 100 and round if needed

round(100*rowMeans(testdf[1:3] == testdf$actual), 2)


问:
Visual Studio 2017 Indent Guide Coloring
In Visual Studio 2015, I had coloring for the indent guides like this.

I can't seem to find this feature in Visual Studio 2017.  Is there an extension that does this?

There's an option in the Fonts and Colors to change the color for all Guidelines.  But what I want is the same in 2015 where it's automatically color coded (blue, green, teal, purple, etc.) depending on the type/level of the braces.

答:
This really should be a comment, but as I do not have enough reputation to make it, an "answer" it is.

A uservoice was added to solicit feedback on missing features of the current Structure Visualizer added to VS2017. If you have an interest in seeing these features restored, please vote.

Improve the Structure Visualizer in Visual Studio 2017


问:
Safari SVG transform-origin zoom animation
I have an inline SVG which is being animated, however when you zoom in or out in the browser the object which is being rotated no longer rotates at its centre point.

It works fine in Chrome.

http://codepen.io/chrismorrison/pen/rmLXWw

```<code>#rays {
  animation: spin 6s linear infinite;
  -webkit-transform-origin: center center;
  transform-origin: center center;
}

@keyframes spin {
  from {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
    -webkit-transform-origin: center center;
    transform-origin: center center;
  }
  to {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transform-origin: center center;
    transform-origin: center center;
  }
}
</code>```

答: I know this is late, but I found the same issue. If you use transform-box: fill-box;, the object will rotate on its axis properly in Safari.

Body:
I have an inline SVG which is being animated, however when you zoom in or out in the browser the object which is being rotated no longer rotates at its centre point.

It works fine in Chrome.

http://codepen.io/chrismorrison/pen/rmLXWw

#rays {
  animation: spin 6s linear infinite;
  -webkit-transform-origin: center center;
  transform-origin: center center;
}

@keyframes spin {
  from {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
    -webkit-transform-origin: center center;
    transform-origin: center center;
  }
  to {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transform-origin: center center;
    transform-origin: center center;
  }
}


问:
Give the code below, I was told that if a hash is called and pass through as argument, I can't return Nil. Can anyone explain to me how come?
```<code>def key_for_min_value(name_hash)

name_hash.max_by {|k, v| 0-v}[0]

end
</code>```

This was my code to fulfill the test suite for finding the lowest value of a hash (this was for one of my lessons online).

I know there are much easier ways to do this but I had some restrictions, as you can see below:

**A Few Restrictions:
We want you to build this on your own. Some of the following methods are helpful but off limits for this exercise. (We'll cover a few below in more depth in subsequent lessons).

I could not use keys, values, min, sort, min_by to make it pass.

This code returned the key with the lowest value (a hash of key ==> integers) but here was the requirement I could not figure out.

If the method is called and passed an argument of an empty hash, it should return nil.

Only first month programming, so this may be obvious but is there a way to return nil for an empty hash, and keep my existing code intact?

Thanks for your help

答:
To a beginner programmer I would recommend to print all intermediate results of expressions, or work in IRB.

```<code>def key_for_min_value(name_hash)
    puts
    puts "in key_for_min_value with parameter #{name_hash}"
#    puts "about to return nil" if name_hash.empty?
#    return nil if name_hash.empty?

    name_hash.max_by { | item | puts "item=#{item}" }

    max = name_hash.max_by do | k, v |
        puts "k=#{k}  v=#{v}  0 - v = #{0 - v}"
        0 - v
    end
    puts "max=#{max.inspect}, class of value returned by max_by : #{max.class}"

    result = name_hash.max_by {|k, v| 0-v}[0]
    puts "result=#{result.inspect}"
    result
end

key_for_min_value({a: 1, b: 2, c: 3})
key_for_min_value({})
</code>```

Execution :

```<code>$ ruby -w t.rb

in key_for_min_value with parameter {:a=>1, :b=>2, :c=>3}
item=[:a, 1]
item=[:b, 2]
item=[:c, 3]
k=a  v=1  0 - v = -1
k=b  v=2  0 - v = -2
k=c  v=3  0 - v = -3
max=[:a, 1], class of value returned by max_by : Array
result=:a

in key_for_min_value with parameter {}
max=nil, class of value returned by max_by : NilClass
t.rb:15:in `key_for_min_value': undefined method `[]' for nil:NilClass (NoMethodError)
    from t.rb:21:in `<main>'
</code>```

The documentation of enum.max_by says :

Returns the item corresponding to the largest value returned by the
  block.

But if the enum is empty, it returns nil, from which you fetch element [0], which causes the error because there is no such method in the NilClass.

If you add return nil if name_hash.empty? at the beginning of the method, you prevent it to happen (with two uncommented lines) :

```<code>$ ruby -w t.rb

in key_for_min_value with parameter {:a=>1, :b=>2, :c=>3}
...
in key_for_min_value with parameter {}
about to return nil
</code>```

Body:
def key_for_min_value(name_hash)

name_hash.max_by {|k, v| 0-v}[0]

end

This was my code to fulfill the test suite for finding the lowest value of a hash (this was for one of my lessons online).

I know there are much easier ways to do this but I had some restrictions, as you can see below:

**A Few Restrictions:
We want you to build this on your own. Some of the following methods are helpful but off limits for this exercise. (We'll cover a few below in more depth in subsequent lessons).

I could not use keys, values, min, sort, min_by to make it pass.

This code returned the key with the lowest value (a hash of key ==> integers) but here was the requirement I could not figure out.

If the method is called and passed an argument of an empty hash, it should return nil.

Only first month programming, so this may be obvious but is there a way to return nil for an empty hash, and keep my existing code intact?

Thanks for your help

Body:
To a beginner programmer I would recommend to print all intermediate results of expressions, or work in IRB.

def key_for_min_value(name_hash)
    puts
    puts "in key_for_min_value with parameter #{name_hash}"
#    puts "about to return nil" if name_hash.empty?
#    return nil if name_hash.empty?

    name_hash.max_by { | item | puts "item=#{item}" }

    max = name_hash.max_by do | k, v |
        puts "k=#{k}  v=#{v}  0 - v = #{0 - v}"
        0 - v
    end
    puts "max=#{max.inspect}, class of value returned by max_by : #{max.class}"

    result = name_hash.max_by {|k, v| 0-v}[0]
    puts "result=#{result.inspect}"
    result
end

key_for_min_value({a: 1, b: 2, c: 3})
key_for_min_value({})

Execution :

$ ruby -w t.rb

in key_for_min_value with parameter {:a=>1, :b=>2, :c=>3}
item=[:a, 1]
item=[:b, 2]
item=[:c, 3]
k=a  v=1  0 - v = -1
k=b  v=2  0 - v = -2
k=c  v=3  0 - v = -3
max=[:a, 1], class of value returned by max_by : Array
result=:a

in key_for_min_value with parameter {}
max=nil, class of value returned by max_by : NilClass
t.rb:15:in `key_for_min_value': undefined method `[]' for nil:NilClass (NoMethodError)
    from t.rb:21:in `<main>'

The documentation of enum.max_by says :

Returns the item corresponding to the largest value returned by the
  block.

But if the enum is empty, it returns nil, from which you fetch element [0], which causes the error because there is no such method in the NilClass.

If you add return nil if name_hash.empty? at the beginning of the method, you prevent it to happen (with two uncommented lines) :

$ ruby -w t.rb

in key_for_min_value with parameter {:a=>1, :b=>2, :c=>3}
...
in key_for_min_value with parameter {}
about to return nil


问:
Change Admin Account of Fabric
I tried to change admin account to my own.
Because the person who has the admin account has left. Our company is using Gmail as a corporate email, and unfortunately emails of people with admin accounts have been deleted.

Let me know what I can do

thanks.

答: Thanks! For this you will need to contact support through your Fabric dashboard. We will have two people from your organization verify that we can change someone to admin. After that you'll be back up and running. Thanks! -Todd from Fabric</p>

Title: Change Admin Account of Fabric


问:
jprogressbar visible and working on button click
```<code>public NewJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
  jProgressBar1.setVisible(false);

}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    jButton1.setEnabled(false);
    jProgressBar1.setVisible(true);
   repaint();
   for(int i=0;i<=100;i+=5){
          jProgressBar1.setValue(i);
         // jProgressBar1.setIndeterminate(false);
          try{
              jProgressBar1.paintImmediately(0, 0, 100, 100);//0, 1, 100, 10
          Thread.sleep(100);
          jProgressBar1.setStringPainted(true);

     }catch(Exception e){}
    }
</code>```

I use above code for using a Jprogressbar in a JDialog. If I use this I can see a progressbar after completing its process(100 %) and also I don't want to show the progressbar upto buttonclick.

答:
Use a separate Thread for running your task.  The progress bar doesn't have a chance to get painted on the GUI thread.  You need something like SwingWorker to help you out.

Add the progress bar to the GUI after the button click.

Refer to the Java tutorial for a walk through on how to set it up.

Body:
public NewJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
  jProgressBar1.setVisible(false);

}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    jButton1.setEnabled(false);
    jProgressBar1.setVisible(true);
   repaint();
   for(int i=0;i<=100;i+=5){
          jProgressBar1.setValue(i);
         // jProgressBar1.setIndeterminate(false);
          try{
              jProgressBar1.paintImmediately(0, 0, 100, 100);//0, 1, 100, 10
          Thread.sleep(100);
          jProgressBar1.setStringPainted(true);

     }catch(Exception e){}
    }

I use above code for using a Jprogressbar in a JDialog. If I use this I can see a progressbar after completing its process(100 %) and also I don't want to show the progressbar upto buttonclick.


问:
Delete a cache in controller
I would like to delete a cache defined into my User.model

This is my cache method (into UserModel) :

```<code>def cached_favgroups
  Rails.cache.fetch([self, "fav_groups"]) {fav_groups.to_a}
end
</code>```

And this is my code to delete it (into GroupController):

```<code>def something
  expire_fragment(current_user.cache_key+"/fav_groups")
end
</code>```

The code generated with this line is :

```<code>Cache delete: views/users/1-20171116091341756594/fav_groups
</code>```

Instead of this :

```<code>Cache delete: users/1-20171116091341756594/fav_groups
</code>```

Do you know how I can change my code to erase the first part of my path (views/)

答:
You have to change </p>

```<code>expire_fragment(current_user.cache_key+"/fav_groups")
</code>```

<p>Into </p>

```<code>Rails.cache.delete(current_user.cache_key+"/fav_groups")
</code>```

Title: Delete a cache in controller

Body:
I would like to delete a cache defined into my User.model

This is my cache method (into UserModel) :

def cached_favgroups
  Rails.cache.fetch([self, "fav_groups"]) {fav_groups.to_a}
end

And this is my code to delete it (into GroupController):

def something
  expire_fragment(current_user.cache_key+"/fav_groups")
end

The code generated with this line is :

Cache delete: views/users/1-20171116091341756594/fav_groups

Instead of this :

Cache delete: users/1-20171116091341756594/fav_groups

Do you know how I can change my code to erase the first part of my path (views/)

Body:
You have to change

expire_fragment(current_user.cache_key+"/fav_groups")

Into

Rails.cache.delete(current_user.cache_key+"/fav_groups")


问:
FB Litho: How to set custom font for Text
My question is how to set a custom font for Text component in Facebook's UI framework Litho?

The following is my Text component:

```<code> Text.create(componentContext)
                .flexGrow(1f)
                .verticalGravity(VerticalGravity.CENTER)
                .text("MY APP")
                .textSizeDip(25)
                .textAlignment(Layout.Alignment.ALIGN_CENTER)
</code>```

答:
To use the typeface prop, you must first obtain a Typeface object, which is significantly easier if you can use Support Library v26, which introduces Fonts in XML ... it's pretty simple to do so from a ComponentContext even inside your onCreateLayout method (though presumably you may wish to cache the Typeface):

```<code>Text.create(c)
    .typeface(ResourcesCompat.getFont(
        c.getApplicationContext, R.font.my_cool_font)
    .text("Check out my cool font")
    .build()
</code>```

There is also a Typeface.Builder class available if you do not have access to Support v26, which gives you a few options about how to specify the desired font.

Body:
My question is how to set a custom font for Text component in Facebook's UI framework Litho?

The following is my Text component:

 Text.create(componentContext)
                .flexGrow(1f)
                .verticalGravity(VerticalGravity.CENTER)
                .text("MY APP")
                .textSizeDip(25)
                .textAlignment(Layout.Alignment.ALIGN_CENTER)

Body:
To use the typeface prop, you must first obtain a Typeface object, which is significantly easier if you can use Support Library v26, which introduces Fonts in XML ... it's pretty simple to do so from a ComponentContext even inside your onCreateLayout method (though presumably you may wish to cache the Typeface):

Text.create(c)
    .typeface(ResourcesCompat.getFont(
        c.getApplicationContext, R.font.my_cool_font)
    .text("Check out my cool font")
    .build()

There is also a Typeface.Builder class available if you do not have access to Support v26, which gives you a few options about how to specify the desired font.


问:
Xcode 9: Could not attach to pid
I've been facing an issue (frequently) with the recent major release of the iOS application development tool - Xcode 9-beta.

It's showing me the following error frequently while running/debugging app in Simulator (iOS 11).

Could not attach to pid : “2370”

Ensure <project title> is not already running, and <system username> has permission to debug it.

Here is a snapshot for the same issue:

What would be permanent solution of this issue, as it's disturbing frequently?

答: Still not a permanent solution, but I had to quit and restart Xcode as the other solutions did not work for me. </p>

ContentLicense: CC BY-SA 4.0

Title: Xcode 9: Could not attach to pid


问:
"ModuleNotFoundError: No module named <package>" in my Docker container
I'm trying to run a python script in a Docker container, and i don't know why, python can't find any of the python's module. I thaught it has something to do with the PYTHONPATH env variable, so i tried to add it in the Dockerfile like this : ENV PYTHONPATH $PYTHONPATH

But it didn't work.
this is what my Dockerfile looks like:

```<code>FROM ubuntu:16.04
MAINTAINER SaveMe SaveMe@Desperate.com

ADD . /app
WORKDIR /app

RUN apt-get update

RUN DEBIAN_FRONTEND=noninteractive apt-get install -y locales

# Set the locale
RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/'
/etc/locale.gen && \
    locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
ENV PYTHONPATH ./app

#Install dependencies
RUN echo "===> Installing sudo to emulate normal OS behavior..."
RUN apt-get install -y software-properties-common
RUN apt-add-repository universe
RUN add-apt-repository ppa:jonathonf/python-3.6
RUN (apt-get update && apt-get upgrade -y -q && apt-get dist-upgrade -
y -q && apt-get -y -q autoclean && apt-get -y -q autoremove)
RUN apt-get install -y libxml2-dev libxslt-dev
RUN apt-get install -y python3.6 python3.6-dev python3.6-venv openssl
ca-certificates python3-pip
RUN apt-get install -y  python3-dev python-dev libffi-dev gfortran
RUN apt-get install -y swig
RUN apt-get install -y sshpass openssh-client rsync python-pip python-
dev libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev
zlib1g-dev libpulse-dev
RUN pip install --upgrade pip
RUN pip install bugsnag

#Install python package + requirements.txt
RUN  pip3 install  -r requirements.txt

CMD ["python3.6", "import_emails.py"]
</code>```

when i'm trying to run: sudo docker run <my_container> i got this Traceback:

```<code>Traceback (most recent call last):
  File "import_emails.py", line 9, in <module>
    import bugsnag
ModuleNotFoundError: No module named 'bugsnag'
</code>```

As you can see i'm using python3.6 for this project. Any lead on how to solve this ?

答: since you're using py3, try using pip3 to install bugsnag instead of pip</p>

Body:
I'm trying to run a python script in a Docker container, and i don't know why, python can't find any of the python's module. I thaught it has something to do with the PYTHONPATH env variable, so i tried to add it in the Dockerfile like this : ENV PYTHONPATH $PYTHONPATH

But it didn't work.
this is what my Dockerfile looks like:

FROM ubuntu:16.04
MAINTAINER SaveMe SaveMe@Desperate.com

ADD . /app
WORKDIR /app

RUN apt-get update

RUN DEBIAN_FRONTEND=noninteractive apt-get install -y locales

# Set the locale
RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/'
/etc/locale.gen && \
    locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
ENV PYTHONPATH ./app

#Install dependencies
RUN echo "===> Installing sudo to emulate normal OS behavior..."
RUN apt-get install -y software-properties-common
RUN apt-add-repository universe
RUN add-apt-repository ppa:jonathonf/python-3.6
RUN (apt-get update && apt-get upgrade -y -q && apt-get dist-upgrade -
y -q && apt-get -y -q autoclean && apt-get -y -q autoremove)
RUN apt-get install -y libxml2-dev libxslt-dev
RUN apt-get install -y python3.6 python3.6-dev python3.6-venv openssl
ca-certificates python3-pip
RUN apt-get install -y  python3-dev python-dev libffi-dev gfortran
RUN apt-get install -y swig
RUN apt-get install -y sshpass openssh-client rsync python-pip python-
dev libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev
zlib1g-dev libpulse-dev
RUN pip install --upgrade pip
RUN pip install bugsnag

#Install python package + requirements.txt
RUN  pip3 install  -r requirements.txt

CMD ["python3.6", "import_emails.py"]

when i'm trying to run: sudo docker run <my_container> i got this Traceback:

Traceback (most recent call last):
  File "import_emails.py", line 9, in <module>
    import bugsnag
ModuleNotFoundError: No module named 'bugsnag'

As you can see i'm using python3.6 for this project. Any lead on how to solve this ?


问:
Sublime Text: Not representable characters
I'm using Sublime Text for Latex, so i need to use a specific encoding. However, in some cases, when I paste text copied from a different program (word/browser in most cases), I'm getting the message:

```<code>"Not all characters are representable in XXX encoding, falling back to UTF-8"
</code>```

My question is: Is there any way to see which parts of the text cannot be encoded, so I can delete them manually?

答:
Just adding to @Draken response: here is the RegEx with spanish characters added.

[^a-zA-Z0-9 -\.;<>/ =“”'{}\[\]\^\?_\\\|:\r\n~@àèêîôâûçäöüÄÖÜßáéíóúñÑ¿€]

In my case I hitted Ctrl+H (for replacement) and as a replacement expression used nothing. So everything got cleared super fast and I was able to save it using ISO-8859-1.

Body:
I'm using Sublime Text for Latex, so i need to use a specific encoding. However, in some cases, when I paste text copied from a different program (word/browser in most cases), I'm getting the message:

"Not all characters are representable in XXX encoding, falling back to UTF-8"

My question is: Is there any way to see which parts of the text cannot be encoded, so I can delete them manually?


问:
Best way to implement form editing and auditing all edits?
I'm starting a new project which will need to allow edits on forms but to keep track of the original and who did what edits and where (p.s. I wouldn't be able to use any extra software other than visual studio 2010 and Microsoft SQL Server Management Studio so no point suggesting any addition software, this is purely a code or table design minded question) .

I'm a perfectionist and I know some possible routes to achieve this will prob change my overall project design but I'm not sure if the ideas I have on how to implement this are best so I like to hear others opinions on below ideas and your own ideas on the quickest most effective way to implement above problem.

Ideas:-

I'd set it up so that when they edit it would display all existing ranges of data from textboxs to radiobuttons and even some drop downs and the value which they had and then on submit it would copy the original record via the Id into a achieve table, create the new record and then delete the original from the main table.

I figure some way to add X amount of comments to any section of the form and each would have a timestamp and username from win auth recorded at the bottom.

Edit - My intention was to get a variety of solutions but I suppose once I'm able to start on the editing section of this project if the single solution given works then I'll mark that correct.

答:
I'm not sure whether this is what you are looking for but I have the need to log all changes to data (for audit reasons) and the way I have implemented this is to create a new 'History' table in SQL Server that will store the record ID, username of person who changed it, whether they added/modified/deleted something and when this happened etc.

In the code to add/edit/delete things in my database I always call ObjectContext.SaveChanges (I use Entity Framework 4) so what I have implemented is an extension to this method that uses various parts of the ObjectStateManager to get the information required about the entity that has changed and inserts the details into the History table. You then just need to query this table in the database to display details of what has changed.


问:
The model item passed into the dictionary is of type .. but this dictionary requires a model item of type
This question and community wiki answer has been added to assist in closing out numerous unanswered questions as discussed in this meta post.

I have some code and when it executes, it throws an exception saying:

The model item passed into the dictionary is of type Bar but this dictionary requires a model item of type Foo

What does this mean, and how do I fix it?

答:
Observe if the view has the model required:

View

```<code>@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....
</code>```

Controller

```<code>[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}
</code>```

In my case I Use a partial view but runs in normal views

Body:
Observe if the view has the model required:

View

@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....

Controller

[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}

In my case I Use a partial view but runs in normal views


问:
Need help in constructing a case statement
I need help in writing a case statement. I've a column in one of my table which has some values and I would like to generate a string out of that values. Below is the column which I've in my table along with the output which I would like to see.

Risk Score

```<code>1.70
2.10
2.60
3.00
3.20
3.60
3.80
4.00
4.10
4.30
4.60
4.90
5.20
5.40
5.50
5.60
5.80
6.10
6.40
6.60
6.80
7.10
7.50
</code>```

So my requirement is I want a case statement where if the risk score is >0 and <=3 it has to got to Low bucket, if the risk score is >3 and <=6 it has to got to Medium bucket, if the risk score is >6 it has to got to High bucket

Regards,

Vikas

答:
You can take advantage of short-circuit evaluation of clauses in a CASE expression:

```<code>...
    case when risk_score > 6 then 'high'
         when risk_score > 3 then 'medium'
         when risk_score > 0 then 'low'
         else                     'some_description_here'
    end
        as bucket
</code>```

The ELSE part is for risk score other than > 0. (Risk score of 0, or negative if possible, or - more likely - NULL, if that is possible in your table.) If you don't need an ELSE branch, it is not required.

Body:
I need help in writing a case statement. I've a column in one of my table which has some values and I would like to generate a string out of that values. Below is the column which I've in my table along with the output which I would like to see.

Risk Score

1.70
2.10
2.60
3.00
3.20
3.60
3.80
4.00
4.10
4.30
4.60
4.90
5.20
5.40
5.50
5.60
5.80
6.10
6.40
6.60
6.80
7.10
7.50

So my requirement is I want a case statement where if the risk score is >0 and <=3 it has to got to Low bucket, if the risk score is >3 and <=6 it has to got to Medium bucket, if the risk score is >6 it has to got to High bucket

Regards,

Vikas

Body:
You can take advantage of short-circuit evaluation of clauses in a CASE expression:

...
    case when risk_score > 6 then 'high'
         when risk_score > 3 then 'medium'
         when risk_score > 0 then 'low'
         else                     'some_description_here'
    end
        as bucket

The ELSE part is for risk score other than > 0. (Risk score of 0, or negative if possible, or - more likely - NULL, if that is possible in your table.) If you don't need an ELSE branch, it is not required.


问:
R Matrix Sum Floating Point Sum Margin Error
I have this data:

```<code>   SEX LS  GPA
1    M DO 2.56
2    M DO 2.70
3    M DO 3.04
4    M DO 1.42
5    M FS 3.02
6    M FS 2.67
7    M FS 2.35
8    M FS 1.80
9    M CO 3.41
10   M CO 2.97
11   M CO 2.23
12   M CO 2.31
13   M AP 2.28
14   M AP 3.73
15   M AP 2.05
16   M AP 2.61
17   M HO 2.57
18   M HO 2.81
19   M HO 3.01
20   M HO 3.40
21   F DO 3.33
22   F DO 1.80
23   F DO 2.50
24   F DO 3.04
25   F FS 3.87
26   F FS 3.00
27   F FS 3.25
28   F FS 2.76
29   F CO 3.14
30   F CO 4.00
31   F CO 2.66
32   F CO 2.91
33   F AP 3.69
34   F AP 2.55
35   F AP 3.21
36   F AP 2.86
37   F HO 3.09
38   F HO 1.99
39   F HO 3.46
40   F HO 3.61
</code>```

I am running an ANOVA on the data, and to find the parameters I'm doing the following:

calculate the means:

```<code>mu_grand <- mean(data$GPA)
mu_alpha <- aggregate(data$GPA,list(data$SEX),mean)$x
mu_beta <- aggregate(data$GPA,list(data$LS),mean)$x
mu_alpha_beta <- matrix(aggregate(data$GPA,list(data$SEX,data$LS),mean)$x,nrow=2)
</code>```

calculate the additive effects

```<code>alpha <- mu_alpha - mu_grand
beta <- mu_beta - mu_grand
</code>```

calculate the interactive effects

```<code>a1 <- rep(alpha[1],length(beta))
a2 <- rep(alpha[2],length(beta))

ab1 <- a1 + beta
ab2 <- a2 + beta

ab <- rbind(ab1,ab2)

alpha_beta <- mu_alpha_beta - (mu_grand + ab)
</code>```

Here is alpha_beta:

```<code>ab1  0.0105  0.02925 -0.07575  0.1855 -0.1495
ab2 -0.0105 -0.02925  0.07575 -0.1855  0.1495
</code>```

If I want to find the sum of alpha_beta I get

```<code>sum(alpha_beta)
[1] -4.440892e-16
</code>```

While this is definitely within floating point accuracy, I'm wondering why there is any error at all when if you just add up all the numbers manually you get 0?  Thanks!

答:
Look at that number it is extremely small. R only calculates to around 15 digits so this is just rounding error. Using the package gmp we can see the laws of physics aren't broken.

Load required package

```<code>require("gmp") #Required package
</code>```

Read in data

```<code>data<- read.table(text="SEX LS  GPA
1    M DO 2.56
                  2    M DO 2.70
                  3    M DO 3.04
                  4    M DO 1.42
                  5    M FS 3.02
                  6    M FS 2.67
                  7    M FS 2.35
                  8    M FS 1.80
                  9    M CO 3.41
                  10   M CO 2.97
                  11   M CO 2.23
                  12   M CO 2.31
                  13   M AP 2.28
                  14   M AP 3.73
                  15   M AP 2.05
                  16   M AP 2.61
                  17   M HO 2.57
                  18   M HO 2.81
                  19   M HO 3.01
                  20   M HO 3.40
                  21   F DO 3.33
                  22   F DO 1.80
                  23   F DO 2.50
                  24   F DO 3.04
                  25   F FS 3.87
                  26   F FS 3.00
                  27   F FS 3.25
                  28   F FS 2.76
                  29   F CO 3.14
                  30   F CO 4.00
                  31   F CO 2.66
                  32   F CO 2.91
                  33   F AP 3.69
                  34   F AP 2.55
                  35   F AP 3.21
                  36   F AP 2.86
                  37   F HO 3.09
                  38   F HO 1.99
                  39   F HO 3.46
                  40   F HO 3.61", header=T,row.names=1)
</code>```

Code

```<code>data$GPA<-as.bigq(data$GPA) #Converts to class `bigq`

#Special function because sapply was converting data to raw format
meanL<-function(L){
  x<-rep(0,length(L))
  x<-as.bigq(x)

  for(i in 1:length(L)){
    x[i]<-mean(L[[i]])
  }
  return(x)
}

#This section is changed to handle the new class `bigq`
mu_grand <- mean(data$GPA)
mu_alpha <- meanL(split(data$GPA,data$SEX))
mu_beta <- meanL(split(data$GPA,data$LS))
mu_alpha_beta <- matrix(meanL(split(data$GPA,as.factor(paste(data$SEX,data$LS,sep="-")))),nrow=2)

alpha <- mu_alpha - mu_grand
beta <- mu_beta - mu_grand

a1 <- rep(alpha[1],length(beta))
a2 <- rep(alpha[2],length(beta))

ab1 <- a1 + beta
ab2 <- a2 + beta

ab<-matrix(c(ab1,ab2),ncol=5,byrow=T) #The same as rbind but needed to work with objects of class 'bigq'.
alpha_beta <- mu_alpha_beta - (mu_grand + ab)
sum(alpha_beta)

Big Rational ('bigq') :
[1] 0
</code>```

This is a nice thought experiment but its a pain in the **s to work this gmp because as you can see functions like aggregate and sapply don't play well with it. Moral of the story when you see incredibly small number i.e. 1e-16 and you are expecting 0 you can just assume they are 0.

Body:
I have this data:

   SEX LS  GPA
1    M DO 2.56
2    M DO 2.70
3    M DO 3.04
4    M DO 1.42
5    M FS 3.02
6    M FS 2.67
7    M FS 2.35
8    M FS 1.80
9    M CO 3.41
10   M CO 2.97
11   M CO 2.23
12   M CO 2.31
13   M AP 2.28
14   M AP 3.73
15   M AP 2.05
16   M AP 2.61
17   M HO 2.57
18   M HO 2.81
19   M HO 3.01
20   M HO 3.40
21   F DO 3.33
22   F DO 1.80
23   F DO 2.50
24   F DO 3.04
25   F FS 3.87
26   F FS 3.00
27   F FS 3.25
28   F FS 2.76
29   F CO 3.14
30   F CO 4.00
31   F CO 2.66
32   F CO 2.91
33   F AP 3.69
34   F AP 2.55
35   F AP 3.21
36   F AP 2.86
37   F HO 3.09
38   F HO 1.99
39   F HO 3.46
40   F HO 3.61

I am running an ANOVA on the data, and to find the parameters I'm doing the following:

calculate the means:

mu_grand <- mean(data$GPA)
mu_alpha <- aggregate(data$GPA,list(data$SEX),mean)$x
mu_beta <- aggregate(data$GPA,list(data$LS),mean)$x
mu_alpha_beta <- matrix(aggregate(data$GPA,list(data$SEX,data$LS),mean)$x,nrow=2)

calculate the additive effects

alpha <- mu_alpha - mu_grand
beta <- mu_beta - mu_grand

calculate the interactive effects

a1 <- rep(alpha[1],length(beta))
a2 <- rep(alpha[2],length(beta))

ab1 <- a1 + beta
ab2 <- a2 + beta

ab <- rbind(ab1,ab2)

alpha_beta <- mu_alpha_beta - (mu_grand + ab)

Here is alpha_beta:

ab1  0.0105  0.02925 -0.07575  0.1855 -0.1495
ab2 -0.0105 -0.02925  0.07575 -0.1855  0.1495

If I want to find the sum of alpha_beta I get

sum(alpha_beta)
[1] -4.440892e-16

While this is definitely within floating point accuracy, I'm wondering why there is any error at all when if you just add up all the numbers manually you get 0?  Thanks!

Body:
Look at that number it is extremely small. R only calculates to around 15 digits so this is just rounding error. Using the package gmp we can see the laws of physics aren't broken.

Load required package

require("gmp") #Required package

Read in data

data<- read.table(text="SEX LS  GPA
1    M DO 2.56
                  2    M DO 2.70
                  3    M DO 3.04
                  4    M DO 1.42
                  5    M FS 3.02
                  6    M FS 2.67
                  7    M FS 2.35
                  8    M FS 1.80
                  9    M CO 3.41
                  10   M CO 2.97
                  11   M CO 2.23
                  12   M CO 2.31
                  13   M AP 2.28
                  14   M AP 3.73
                  15   M AP 2.05
                  16   M AP 2.61
                  17   M HO 2.57
                  18   M HO 2.81
                  19   M HO 3.01
                  20   M HO 3.40
                  21   F DO 3.33
                  22   F DO 1.80
                  23   F DO 2.50
                  24   F DO 3.04
                  25   F FS 3.87
                  26   F FS 3.00
                  27   F FS 3.25
                  28   F FS 2.76
                  29   F CO 3.14
                  30   F CO 4.00
                  31   F CO 2.66
                  32   F CO 2.91
                  33   F AP 3.69
                  34   F AP 2.55
                  35   F AP 3.21
                  36   F AP 2.86
                  37   F HO 3.09
                  38   F HO 1.99
                  39   F HO 3.46
                  40   F HO 3.61", header=T,row.names=1)

Code

data$GPA<-as.bigq(data$GPA) #Converts to class `bigq`

#Special function because sapply was converting data to raw format
meanL<-function(L){
  x<-rep(0,length(L))
  x<-as.bigq(x)

  for(i in 1:length(L)){
    x[i]<-mean(L[[i]])
  }
  return(x)
}

#This section is changed to handle the new class `bigq`
mu_grand <- mean(data$GPA)
mu_alpha <- meanL(split(data$GPA,data$SEX))
mu_beta <- meanL(split(data$GPA,data$LS))
mu_alpha_beta <- matrix(meanL(split(data$GPA,as.factor(paste(data$SEX,data$LS,sep="-")))),nrow=2)

alpha <- mu_alpha - mu_grand
beta <- mu_beta - mu_grand

a1 <- rep(alpha[1],length(beta))
a2 <- rep(alpha[2],length(beta))

ab1 <- a1 + beta
ab2 <- a2 + beta

ab<-matrix(c(ab1,ab2),ncol=5,byrow=T) #The same as rbind but needed to work with objects of class 'bigq'.
alpha_beta <- mu_alpha_beta - (mu_grand + ab)
sum(alpha_beta)

Big Rational ('bigq') :
[1] 0

This is a nice thought experiment but its a pain in the **s to work this gmp because as you can see functions like aggregate and sapply don't play well with it. Moral of the story when you see incredibly small number i.e. 1e-16 and you are expecting 0 you can just assume they are 0.


问:
Array multiple JSON Data output
I'm relatively new and am currently learning php. I'm trying to work with JSON data right now. I'd like to echo all NODES, but I can't find a solution. Maybe somebody can help me.

API: https://flightplandatabase.com/dev/api#route

API XML: https://api.flightplandatabase.com/plan/62478

What I want: route.nodes[].ident <-- All nodes idents. Not only the first one

Currently I only get the first "NODE". Is it possible that I can get every NODE out at the same time without much effort?

```<code>    <?php

            $ch = curl_init();

            curl_setopt($ch,CURLOPT_URL, 'https://api.flightplandatabase.com/plan/62478');
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

            $output = curl_exec($ch);

            curl_close($ch);

            $finalarray = json_decode($output);

            $finalstring = json_encode($output);

    ?>
    <div>
        <p><?php echo $finalarray->route->nodes[0]->ident; ?></p>
    </div>
</code>```

Hope you understand what I mean. :)

答:
That is because you set it to print only this first [0].
Try use a for:

```<code>$nodes = $finalarray->route->nodes
for ($i=0; $i<count($nodes); $i++) {
 echo nodes[$i]->ident;
}
</code>```

Plus, it is better to do:

```<code>json_decode($yourarray, true);
</code>```

And

```<code>json_encode($yourarray, JSON_UNESCAPED_UNICODE);
</code>```

Title: Array multiple JSON Data output

Body:
I'm relatively new and am currently learning php. I'm trying to work with JSON data right now. I'd like to echo all NODES, but I can't find a solution. Maybe somebody can help me.

API: https://flightplandatabase.com/dev/api#route

API XML: https://api.flightplandatabase.com/plan/62478

What I want: route.nodes[].ident <-- All nodes idents. Not only the first one

Currently I only get the first "NODE". Is it possible that I can get every NODE out at the same time without much effort?

    <?php

            $ch = curl_init();

            curl_setopt($ch,CURLOPT_URL, 'https://api.flightplandatabase.com/plan/62478');
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

            $output = curl_exec($ch);

            curl_close($ch);

            $finalarray = json_decode($output);

            $finalstring = json_encode($output);

    ?>

<?php echo $finalarray->route->nodes[0]->ident; ?>

Hope you understand what I mean. :)

Body:
That is because you set it to print only this first [0].
Try use a for:

$nodes = $finalarray->route->nodes
for ($i=0; $i<count($nodes); $i++) {
 echo nodes[$i]->ident;
}

Plus, it is better to do:

json_decode($yourarray, true);

And

json_encode($yourarray, JSON_UNESCAPED_UNICODE);


问:
How to Programmatically trigger focus() on Material UI Select field?
My app forms utilize the enter button to tab to specified fields for speed on a ten-key keyboard. When enter is hit, we do a DOM lookup and trigger focus() on the next element. This works great on text fields but I cannot understand how to accomplish this on a Select box in Material UI Beta@1.0.0-beta.21. I can get each of the DOM elements that make up the Select structure, but triggering focus() at any level does nothing.
Note: I am able to grab the ref of the item via inputRef on the select to prevent us from traversing the DOM but it still yields no results.

Question on GitHub: https://github.com/callemall/material-ui/issues/9182#issuecomment-345148074

Code Sandbox example: https://codesandbox.io/s/m43qqyo2zy

答:
The node passed to Select.props.inputRef() references a hidden input. You would need to focus() on the div that is rendered as its sibling. Also, you need to handle the Select element case first in handleKeyPressInternal() because getElementsByName() will return the input.

This doesn't feel right, though, because you are relying on Select to render the focusable div as its immediate sibling. Could be grounds to extend inputRef() on Select to return the node that can visually receive focus.

https://codesandbox.io/s/zooz41oo3


问:
Windows Mobile - Capture Application/Process Termination Event
I need to create Watchgog application that will keep track of main application. If my main application is crashed/closed/ended by any means, this watchdog application will activate it again.

I can do this by scanning running process at regular intervals, but this is resource intensive process. Can I get any notification when process is terminated (not Form Closing event, it does not work when application crashes)?

答:
Process class does give you such functions.

WaitForExit() (method)    Instructs the Process
  component to wait indefinitely for the
  associated process to exit.
  Exited (event)    Occurs when a process exits.

So you need to find your process only once and than in your watchdog use provided method or event.