问:
ListView And Adapters In Android, Does Falls Under Adapter Design Pattern?
I'm just a beginner in Android application development. And I came to this creating ListView and manipulating content for the ListView. We all know we usually use Adapter as a data and View provider for the ListView. Have one doubt is this really falls under the normal Adapter Design Pattern. One more doubt I'm fetching the content for my list from a third party API. In this I'm using two types of Views one is to show the loading view while the content is getting loaded from the API and the other is the normal View(ListRow). Is it good way of doing it ? Any help or explanation would be largely appreciated.

Thank You

答:
Android adapters are in fact the same Adapter design pattern as per the GoF. Adapters are used to give a known interface to unknown objects. eg: if we are using any 3rd party libraries, it is recommended to have adapters implemented so that the 3rd party interface is converted to a known interface. Then it becomes easy to replace the 3rp party libraries with just adding a new adapter.

Now, look at the ListView Adapter concept in Android as a whole. 3rd party developers are free to add any data backend and make the list view work if they implement the known interface which is the Android defined adapter kind. I hope that clarifies the design pattern.


来源: stackexchange

问:
Telerik Grid - Export to CSV more columns than displayed on screen
Problem:  How to display more columns in a Telerik grid than are displayed in the rendered grid?

eg I'd like to only display on the screen the Surname, but on dump to csv would like firstname too.

I've tried visible = false, and display = false on the GridBoundColumns, but then they don't come out on the csv.

```<code><telerik:RadGrid ID="grdAuctions" runat="server" AllowAutomaticDeletes="True" AllowAutomaticUpdates="True"
        AllowPaging="False" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="odsAuctionSales"
        GridLines="None" EnableEmbeddedSkins="False" OnItemDataBound="grdAuctionSales_ItemDataBound">
        <ExportSettings HideStructureColumns="true" />
        <MasterTableView Width="100%" CommandItemDisplay="Top">
            <PagerStyle Mode="NextPrevNumericAndAdvanced" />
            <CommandItemSettings ShowAddNewRecordButton="false" ShowRefreshButton="false" ShowExportToCsvButton="true"
                ExportToCsvImageUrl="~/Images/excel.jpg" ExportToCsvText="Export to csv" />
        </MasterTableView>
        <MasterTableView DataKeyNames="Id" DataSourceID="odsAuctionSales" CssClass="listItems"
            Width="98%">
            <SortExpressions>
                <telerik:GridSortExpression FieldName="Name"></telerik:GridSortExpression>
            </SortExpressions>
            <RowIndicatorColumn>
                <HeaderStyle Width="20px"></HeaderStyle>
            </RowIndicatorColumn>
            <ExpandCollapseColumn>
                <HeaderStyle Width="20px"></HeaderStyle>
            </ExpandCollapseColumn>
            <Columns>
                <telerik:GridTemplateColumn UniqueName="Edit">
                    <ItemTemplate>
                        <asp:HyperLink ID="edit" runat="server" Text="Edit"></asp:HyperLink>
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridBoundColumn DataField="NameOnTable" HeaderText="Name On Table" SortExpression="NameOnTable"
                    UniqueName="NameOnTable">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Surname" HeaderText="Surname" SortExpression="Surname"
                    UniqueName="Surname">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Firstname" HeaderText="Firstname" SortExpression="Firstname"
                    UniqueName="Firstname">
                </telerik:GridBoundColumn>
</code>```

Edit Here is how I got it working

```<code>protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.ExportToCsvCommandName)
        {
            grdAuctions.MasterTableView.GetColumn("Edit").Visible = false;
            grdAuctions.MasterTableView.GetColumn("DPSAuthCode").Visible = true;
    grdAuctions.MasterTableView.ExportToCSV();
        }

    }
</code>```

and in the aspx

```<code>OnItemCommand="RadGrid1_ItemCommand"
</code>```

and

```<code> <telerik:GridBoundColumn DataField="DPSAuthCode" HeaderText="DPSAuthCode" Visible="false"
                    SortExpression="DPSAuthCode" UniqueName="DPSAuthCode">
                </telerik:GridBoundColumn>
</code>```

答:
The best idea i can give you is to have the control display it, and then use jquery to set the display on those columns off.

Another option might be to overload the export to csv function, but I am not familiar enough with this Telerik control to give you any pointers on that.

ContentLicense: CC BY-SA 2.5

Body:
Problem:  How to display more columns in a Telerik grid than are displayed in the rendered grid?

eg I'd like to only display on the screen the Surname, but on dump to csv would like firstname too.

I've tried visible = false, and display = false on the GridBoundColumns, but then they don't come out on the csv.

<telerik:RadGrid ID="grdAuctions" runat="server" AllowAutomaticDeletes="True" AllowAutomaticUpdates="True"
        AllowPaging="False" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="odsAuctionSales"
        GridLines="None" EnableEmbeddedSkins="False" OnItemDataBound="grdAuctionSales_ItemDataBound">
        <ExportSettings HideStructureColumns="true" />
        <MasterTableView Width="100%" CommandItemDisplay="Top">
            <PagerStyle Mode="NextPrevNumericAndAdvanced" />
            <CommandItemSettings ShowAddNewRecordButton="false" ShowRefreshButton="false" ShowExportToCsvButton="true"
                ExportToCsvImageUrl="~/Images/excel.jpg" ExportToCsvText="Export to csv" />
        </MasterTableView>
        <MasterTableView DataKeyNames="Id" DataSourceID="odsAuctionSales" CssClass="listItems"
            Width="98%">
            <SortExpressions>
                <telerik:GridSortExpression FieldName="Name"></telerik:GridSortExpression>
            </SortExpressions>
            <RowIndicatorColumn>
                <HeaderStyle Width="20px"></HeaderStyle>
            </RowIndicatorColumn>
            <ExpandCollapseColumn>
                <HeaderStyle Width="20px"></HeaderStyle>
            </ExpandCollapseColumn>
            <Columns>
                <telerik:GridTemplateColumn UniqueName="Edit">
                    <ItemTemplate>
                        <asp:HyperLink ID="edit" runat="server" Text="Edit"></asp:HyperLink>
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridBoundColumn DataField="NameOnTable" HeaderText="Name On Table" SortExpression="NameOnTable"
                    UniqueName="NameOnTable">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Surname" HeaderText="Surname" SortExpression="Surname"
                    UniqueName="Surname">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Firstname" HeaderText="Firstname" SortExpression="Firstname"
                    UniqueName="Firstname">
                </telerik:GridBoundColumn>

Edit Here is how I got it working

protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.ExportToCsvCommandName)
        {
            grdAuctions.MasterTableView.GetColumn("Edit").Visible = false;
            grdAuctions.MasterTableView.GetColumn("DPSAuthCode").Visible = true;
    grdAuctions.MasterTableView.ExportToCSV();
        }

    }

and in the aspx

OnItemCommand="RadGrid1_ItemCommand"

and

 <telerik:GridBoundColumn DataField="DPSAuthCode" HeaderText="DPSAuthCode" Visible="false"
                    SortExpression="DPSAuthCode" UniqueName="DPSAuthCode">
                </telerik:GridBoundColumn>


问:
Invalid Subscription key when using Face API
I've just created a Face API key and went to Microsoft's test console  to test it out but I get invalid key error as response. I could not figure out how to change westus to westcentralus so I put together a small PHP code to send the request. The same error. Here is the code:

```<code>$postData = array(
    'url' => '...url to image..',
);

// Setup cURL
$ch = curl_init('https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Ocp-Apim-Subscription-Key' => '9******************************6',
        'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));

// Send the request
$response = curl_exec($ch);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've just created a Face API key and went to Microsoft's test console  to test it out but I get invalid key error as response. I could not figure out how to change westus to westcentralus so I put together a small PHP code to send the request. The same error. Here is the code:

$postData = array(
    'url' => '...url to image..',
);

// Setup cURL
$ch = curl_init('https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Ocp-Apim-Subscription-Key' => '9******************************6',
        'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));

// Send the request
$response = curl_exec($ch);

Body:
You should change the following line of code:

'Ocp-Apim-Subscription-Key' => '9******************************6',

to:

'Ocp-Apim-Subscription-Key: 9******************************6',


问:
How to hide views for always
Can somebody tell me how to hide views for always?

I'm hiding a view with view.setVisibility(view.GONE); but when reopen the app I have to re-hide the view. I want a view hide for always when button is clicked until clearing app data or uninstalling. Thanks!

答:
You have to use SharedPreferences, when you hide the View then store a value in SharedPreferences, and when you come back to the app get value from SharedPreferences and according to that value hide your View by the same method that you are using.

```<code>SharedPreferences sp = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor et = sp.edit();
et.putBoolean("isViewHide", true);
et.commit();
</code>```

Getting value from SharedPreferences

```<code>SharedPreferences sp = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
boolean cb1 = sp.getBoolean("isViewHide", false);
</code>```

reference from SharedPreferences example

Title: How to hide views for always

Body:
You have to use SharedPreferences, when you hide the View then store a value in SharedPreferences, and when you come back to the app get value from SharedPreferences and according to that value hide your View by the same method that you are using.

SharedPreferences sp = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor et = sp.edit();
et.putBoolean("isViewHide", true);
et.commit();

Getting value from SharedPreferences

SharedPreferences sp = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
boolean cb1 = sp.getBoolean("isViewHide", false);

reference from SharedPreferences example


问:
Display complete dependency tree with Leiningen
I understand that lein deps :tree displays a dependency tree of all the project dependencies (implicit and explicit). However, "each dependency is only shown once within a tree." I'd really like to see a tree where this wasn't the case, and that if libraries A and B require library X, library X shows up under both A and B.

Does anyone know how to do this with lein or some other tool?

答: This can now be done using leiningen by lein deps :tree. Note the space between deps and :tree.


问:
How to reload in the Android emulator window when developing React Native Apps?
When developing React Native Apps, I'm following the Getting Started steps at https://facebook.github.io/react-native/docs/getting-started.html#content and have reached the point of modifying the source file and reloading.

"Double tap R on your keyboard to reload, Shake or press menu button for dev menu".

Double tap R - where? The only reasonable place seems to be in the Android emulator window. When I do it there, nothing at all happens. I also tried it in the cmd window which is running the packager - nothing happened.

I see no way to "shake" the emulator.

Press menu button for dev menu - the only thing which looks like a menu button, on a toolbox looking sidebar beside the emulator (three dots), opens an Extended Controls window, which has no Reload button.

Feeling really stupid since I can't make it through Getting Started without getting stuck.

Host is Windows 7.

How to reload in the default Android emulator for react native app says ctrl-R, but that didn't work for me either.

答:
You can add keyboard for the emulator by doing these steps:

```<code> * On Windows
 - Go to "C:\Users\<your name>\.android\avd\<your emulator name>.avd" folder
 - Edit file config.ini
 - Change hw.keyboard=yes (default is no)
 * On Ubuntu
 - ${HOME}/.android/avd/<avd name>/config.ini
</code>```

Regards,
LCD

ContentLicense: CC BY-SA 4.0

Body:
You can add keyboard for the emulator by doing these steps:

 * On Windows
 - Go to "C:\Users\<your name>\.android\avd\<your emulator name>.avd" folder
 - Edit file config.ini
 - Change hw.keyboard=yes (default is no)
 * On Ubuntu
 - ${HOME}/.android/avd/<avd name>/config.ini

Regards,
LCD


问:
Async load multiple images to single cell
I have a problem with loading of 5 images to each cell of TableView. I use AFNetworking for download and setImageWithUrl method for imageView:

```<code>for (int i = 0; i < urls.count; i++) {
    [self.photoImageView[i] setImageWithURL:urls[i]];
}
</code>```

TableView very brakes when I scroll it. But when i try to load 1 or 2  no brakes when scrolling.

How to correct download images without brakes?

答:
You can use SDWebImage as discussed by @Ravi. You can use use the above code in your for loop to display all 5 images asynchronously , without blocking main thread.

```<code>for (int i = 0; i < urls.count; i++) {
[self.photoImageView[i] sd_setImageWithURL:[NSURL URLWithString:urls[i]]
         placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
}
</code>```

If you dont want to use any third party libraries, you can also use GCD for the same. Check this ans.

Hope it helps. Happy Coding!!

Body:
I have a problem with loading of 5 images to each cell of TableView. I use AFNetworking for download and setImageWithUrl method for imageView:

for (int i = 0; i < urls.count; i++) {
    [self.photoImageView[i] setImageWithURL:urls[i]];
}

TableView very brakes when I scroll it. But when i try to load 1 or 2  no brakes when scrolling.

How to correct download images without brakes?

Body:
You can use SDWebImage as discussed by @Ravi. You can use use the above code in your for loop to display all 5 images asynchronously , without blocking main thread.

for (int i = 0; i < urls.count; i++) {
[self.photoImageView[i] sd_setImageWithURL:[NSURL URLWithString:urls[i]]
         placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
}

If you dont want to use any third party libraries, you can also use GCD for the same. Check this ans.

Hope it helps. Happy Coding!!


问:
Verilog Syntax Error with endmodule
I've been stuck here for a day. I use edaplayground for running this code but I don't khow what's wrong with my it. It says syntax error in the last line where I wrote endmodule, please help.

```<code>module lifo #(parameter n=4,w=4) ( input insert ,clk,output isEmpety,isfull,error,inout [w-1:0]data);

         logic h=$clog2(n);

  reg [n-1:0]mem[w-1:0];
  reg [h:0]sp;
  reg [w-1:0]datar;
  wire [w-1:0] #(0) data=datar;
 always@* begin
if(reset==1)
begin
  assign datar={n{z}};
  assign sp={h{1'b0}};
assign isfull=0;
assign isEmpety=0;
assign error=0;
end
if(insert==1)
begin
if(isEmpety==1)
begin
assign mem[sp]=data;
assign isEmpety=0;
if(error==1)
assign error=0;
end
else
if(isfull==1)
begin
assign mem[sp]=data;
assign error=1;
end
else
begin
assign sp=sp+1;
assign stack[sp]=data;
  if(sp=={h{1}})
assign isfull=1;
end
end
if(insert==0)
begin
  if(sp=={h{0}}&&(isEmpety!=1))
begin
assign datar=mem[sp];
assign isEmpety=1;
end
else
if(isEmpety==1)
begin
assign datar=mem[sp];
assign error=1;
end
else
begin
assign datar=mem[sp];
  if(sp!={h{0}})
assign sp=sp-1;
if(error==1)
assign error=0;
if(isfull==1)
assign isfull=0;
end
end
endmodule
</code>```

Thank you for your help.

答:
Before endmodule include a end your missing the end for always block. and remove the assign keyword in always block. this style of coding is not recommended. i have edited code for you check it out

```<code>module lifo #(parameter n=4,w=4) ( input insert ,clk,output isEmpety,isfull,error,inout [w-1:0]data);
    logic h=$clog2(n);
    reg [n-1:0]mem[w-1:0];
    reg [h:0]sp;
    reg [w-1:0]datar;
    wire [w-1:0] #(0) data=datar;
    always@* begin
        if(reset==1)
        begin
             datar={n{z}};
             sp={h{1'b0}};
             isfull=0;
             isEmpety=0;
             error=0;
        end
        if(insert==1)
        begin
            if(isEmpety==1)
            begin
                 mem[sp]=data;
                 isEmpety=0;
                if(error==1)
                    error=0;
            end
            else if(isfull==1)
            begin
                mem[sp]=data;
                error=1;
            end
            else begin
                sp=sp+1;
                stack[sp]=data;
                if(sp=={h{1}})
                    isfull=1;
            end
    end
    if(insert==0)
    begin
        if(sp=={h{0}}&&(isEmpety!=1))
        begin
            datar=mem[sp];
            isEmpety=1;
        end
        else if(isEmpety==1)
        begin
            datar=mem[sp];
            error=1;
        end
        else
        begin
            datar=mem[sp];
            if(sp!={h{0}})
                sp=sp-1;
            if(error==1)
            error=0;
            if(isfull==1)
            isfull=0;
        end
    end
end
endmodule
</code>```

My advice is write code in a proper order and you will able to fine the errors easily.

Title: Verilog Syntax Error with endmodule

Body:
I've been stuck here for a day. I use edaplayground for running this code but I don't khow what's wrong with my it. It says syntax error in the last line where I wrote endmodule, please help.

module lifo #(parameter n=4,w=4) ( input insert ,clk,output isEmpety,isfull,error,inout [w-1:0]data);

         logic h=$clog2(n);

  reg [n-1:0]mem[w-1:0];
  reg [h:0]sp;
  reg [w-1:0]datar;
  wire [w-1:0] #(0) data=datar;
 always@* begin
if(reset==1)
begin
  assign datar={n{z}};
  assign sp={h{1'b0}};
assign isfull=0;
assign isEmpety=0;
assign error=0;
end
if(insert==1)
begin
if(isEmpety==1)
begin
assign mem[sp]=data;
assign isEmpety=0;
if(error==1)
assign error=0;
end
else
if(isfull==1)
begin
assign mem[sp]=data;
assign error=1;
end
else
begin
assign sp=sp+1;
assign stack[sp]=data;
  if(sp=={h{1}})
assign isfull=1;
end
end
if(insert==0)
begin
  if(sp=={h{0}}&&(isEmpety!=1))
begin
assign datar=mem[sp];
assign isEmpety=1;
end
else
if(isEmpety==1)
begin
assign datar=mem[sp];
assign error=1;
end
else
begin
assign datar=mem[sp];
  if(sp!={h{0}})
assign sp=sp-1;
if(error==1)
assign error=0;
if(isfull==1)
assign isfull=0;
end
end
endmodule

Thank you for your help.

Body:
Before endmodule include a end your missing the end for always block. and remove the assign keyword in always block. this style of coding is not recommended. i have edited code for you check it out

module lifo #(parameter n=4,w=4) ( input insert ,clk,output isEmpety,isfull,error,inout [w-1:0]data);
    logic h=$clog2(n);
    reg [n-1:0]mem[w-1:0];
    reg [h:0]sp;
    reg [w-1:0]datar;
    wire [w-1:0] #(0) data=datar;
    always@* begin
        if(reset==1)
        begin
             datar={n{z}};
             sp={h{1'b0}};
             isfull=0;
             isEmpety=0;
             error=0;
        end
        if(insert==1)
        begin
            if(isEmpety==1)
            begin
                 mem[sp]=data;
                 isEmpety=0;
                if(error==1)
                    error=0;
            end
            else if(isfull==1)
            begin
                mem[sp]=data;
                error=1;
            end
            else begin
                sp=sp+1;
                stack[sp]=data;
                if(sp=={h{1}})
                    isfull=1;
            end
    end
    if(insert==0)
    begin
        if(sp=={h{0}}&&(isEmpety!=1))
        begin
            datar=mem[sp];
            isEmpety=1;
        end
        else if(isEmpety==1)
        begin
            datar=mem[sp];
            error=1;
        end
        else
        begin
            datar=mem[sp];
            if(sp!={h{0}})
                sp=sp-1;
            if(error==1)
            error=0;
            if(isfull==1)
            isfull=0;
        end
    end
end
endmodule

My advice is write code in a proper order and you will able to fine the errors easily.


问:
developing R package with templete .Rmd files findable to package function
I'm developing an R package, one of my package function is generate_report() which generate an html report with rmarkdown using a templete Rmd file and function arguments:

```<code>#' generate report based on templete file
#' @import rmarkdown
#' @export
generate_report <- function(x, y){
  rmarkdown::render('templete.Rmd', envir = list(x = x, y = y))
}
</code>```

and here is the inst/templete.Rmd file: (when the package is compiled, it will be moved to top-level folder of package:

```<code>---
title: "templete"
output: html_document
---

## Head 1

```{r}
print(x)
```

```{r}
print(y)
```
</code>```

my question is, when the package is devtools::install()ed, function generate_report() can not find file templete.Rmd, how to make the function find this templete.Rmd file in right way ?

答: Your rmarkdown::render() call needs to use system.file as per http://r-pkgs.had.co.nz/inst.html

Body:
I'm developing an R package, one of my package function is generate_report() which generate an html report with rmarkdown using a templete Rmd file and function arguments:

#' generate report based on templete file
#' @import rmarkdown
#' @export
generate_report <- function(x, y){
  rmarkdown::render('templete.Rmd', envir = list(x = x, y = y))
}

and here is the inst/templete.Rmd file: (when the package is compiled, it will be moved to top-level folder of package:

---
title: "templete"
output: html_document
---

## Head 1

```{r}
print(x)
```

```{r}
print(y)
```

my question is, when the package is devtools::install()ed, function generate_report() can not find file templete.Rmd, how to make the function find this templete.Rmd file in right way ?


问:
Supply custom attribute to every ChoiceType option's label
In Symfony2, using a form with a ChoiceType field will render something like this:

```<code><span>
  <input type="radio"><label>Option 1</label></span>
<span>
<span>
  <input type="radio"><label>Option 2</label></span>
<span>
<span>
  <input type="radio"><label>Option 3</label></span>
<span>
</code>```

Using the label_attr function I can change the attributes of the overarching label, but I want to change the attributes of every label for every options like this:

```<code><span>
  <input type="radio"><label attr="custom">Option 1</label></span>
<span>
<span>
  <input type="radio"><label attr="custom">Option 2</label></span>
<span>
<span>
  <input type="radio"><label attr="custom">Option 3</label></span>
<span>
</code>```

Is this possible in Symfony2?

答:
Using the label_attr function should give you exactly what you're looking for.  For example, your form type:

```<code>class YourFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('someRadio', 'choice', [
                'label_attr' => ['class' => 'extra_class']
                // ... other things here
            ])
        ;
    }
}
</code>```

Body:
In Symfony2, using a form with a ChoiceType field will render something like this:

  <input type="radio">Option 1

  <input type="radio">Option 2

  <input type="radio">Option 3

Using the label_attr function I can change the attributes of the overarching label, but I want to change the attributes of every label for every options like this:

  <input type="radio">Option 1

  <input type="radio">Option 2

  <input type="radio">Option 3

Is this possible in Symfony2?

Body:
Using the label_attr function should give you exactly what you're looking for.  For example, your form type:

class YourFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('someRadio', 'choice', [
                'label_attr' => ['class' => 'extra_class']
                // ... other things here
            ])
        ;
    }
}


问:
How to rollback unit test while service layer is @Transactional
I am using Spring Boot 1.5.2.RELEASE and my service classes is annotated with

```<code>@Service
@Transactional(rollbackFor = Exception.class)
</code>```

My unit test class is annotated with:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
</code>```

I wish to roll back changes made in the database by unit test methods after test is finished.

One of the proposed solutions is to add @Transactional annotation over the test class, I tried it but this solution produces some issues, is that sometimes the test transaction is rolled back (even without no exceptions thrown!) before the service transaction is completed.

Is there another good solution to rollback test?

答:
all changes will be rollbacked if didn't change default behaviour. And you don't have classes / methods with transaction propagation level = REQUIRES_NEW  as it start independent transaction and can commit or rollback independently with the outer transaction

Transaction rollback and commit behavior

By default, test transactions will be automatically rolled back after
  completion of the test; however, transactional commit and rollback
  behavior can be configured declaratively via the @Commit and @Rollback
  annotations.

@Rollback

@Rollback indicates whether the transaction for a transactional test
  method should be rolled back after the test method has completed. If
  true, the transaction is rolled back; otherwise, the transaction is
  committed (see also @Commit). Rollback semantics for integration tests
  in the Spring TestContext Framework default to true even if @Rollback
  is not explicitly declared.

When declared as a class-level annotation, @Rollback defines the
  default rollback semantics for all test methods within the test class
  hierarchy. When declared as a method-level annotation, @Rollback
  defines rollback semantics for the specific test method, potentially
  overriding class-level @Rollback or @Commit semantics.

Body:
I am using Spring Boot 1.5.2.RELEASE and my service classes is annotated with

@Service
@Transactional(rollbackFor = Exception.class)

My unit test class is annotated with:

@RunWith(SpringRunner.class)
@SpringBootTest

I wish to roll back changes made in the database by unit test methods after test is finished.

One of the proposed solutions is to add @Transactional annotation over the test class, I tried it but this solution produces some issues, is that sometimes the test transaction is rolled back (even without no exceptions thrown!) before the service transaction is completed.

Is there another good solution to rollback test?


问:
I have one text file and in that text file I stored words in 2 columns. I want to store first column in one array and second column in another array
I separate two columns by tab. I have done following code for that but with that code I got one column in one array as a whole. I want to access each element individually and I want to store two columns in two arrays using java.

In splitting[0], I have first array and in splitting[1] I stored second column elements. Now I want to access each element individually using Java.

```<code>for(int i=0;i<lines.size();i++){
    String[] splitting = lines.get(i).split("\t");
}
</code>```

答:
Create two more arrays.

Put this after your split.

```<code>array1[i] = splitting[0];
array2[i] = splitting[1];`
</code>```

You need to set the size of the two new arrays to lines.size(). I would use List instead of Array.

Body:
I separate two columns by tab. I have done following code for that but with that code I got one column in one array as a whole. I want to access each element individually and I want to store two columns in two arrays using java.

In splitting[0], I have first array and in splitting[1] I stored second column elements. Now I want to access each element individually using Java.

for(int i=0;i<lines.size();i++){
    String[] splitting = lines.get(i).split("\t");
}

Body:
Create two more arrays.

Put this after your split.

array1[i] = splitting[0];
array2[i] = splitting[1];`

You need to set the size of the two new arrays to lines.size(). I would use List instead of Array.


问:
Convert string to Title Case with JavaScript
Is there a simple way to convert a string to Title Case? E.g. john smith becomes John Smith. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner.

答:
I think the simplest is using css. </p>

```<code>function format_str(str) {
    str = str.toLowerCase();
    return '<span style="text-transform: capitalize">'+ str +'</span>';
}
</code>```

OwnerDisplayName: MDCore

Body:
I think the simplest is using css.

function format_str(str) {
    str = str.toLowerCase();
    return '<span style="text-transform: capitalize">'+ str +'</span>';
}


问:
PHP Magic faster than simply setting the class attribute?
Well, not exactly that, but here is an example. Can anyone explain the difference between B and C? How can it be faster to use a magic function to dynamically set a value instead of simply setting the value in the attribute definition?

Here is some code:

```<code>[root@vm-202-167-238-17 ~]# cat test.php; for d in A B C; do echo "------"; ./test.php $d; done;
#!/usr/bin/php
<?php

$className = $argv[1];

class A
{
    public function __get($a)
    {
        return 5;
    }
}

class B
{
    public $a = 5;
}

class C
{
    public function __get($a)
    {
        $this->a = 5;

        return 5;
    }
}

$a = new $className;

$start = microtime(true);

for ($i=0; $i < 1000000; $i++)
    $b = $a->a;

$end = microtime(true);

echo (($end - $start) * 1000) ." msec\n";

------
598.90794754028 msec
------
205.48391342163 msec
------
189.7759437561 msec
</code>```

答:
In the last case (class C), you create a property called "a" the first time the magic method is called; thereafter the magic method won't be called, it will just access the property; this is why it isn't as slow as the first case, class A.

The next question is why is case B slower than case C.  I'm guessing that it's happening at the OS level; I reversed the test order so that it tests C B A rather than A B C and suddenly test case C is slower than B, so I'm reasonably certain that the performance win there is outside of PHP; from my reasoning in the first paragraph, it stands to reason that all other things being equal test case C should be fractionally slower than test case B (as there will be one call to the magic method, then all the rest are equal).  Note also that (for me anyway) in this example A is always faster than B on 5.2.10 and on 5.3.3.

EDIT

I think that the question title is distracting from interesting issue here; the performance differences (whatever they are) are unrelated to the magic __get method.  The following example illustrates this more simply, without bothering about the __get confusing things.  Instead we create the dynamic property in the constructor; then the only difference is whether the property is declared first (e.g. public $a) or created dynamically when the value is assigned.

```<code>$className = $argv[1];

class A
{
    public function __construct() {
        $this->a = 5;
    }
}

class B extends A
{
    public $a;
}

$a = new $className;

$start = microtime(true);

for ($i=0; $i < 1000000; $i++)
    $b = $a->a;

$end = microtime(true);

echo (($end - $start) * 1000) ." msec\n";
</code>```

Body:
Well, not exactly that, but here is an example. Can anyone explain the difference between B and C? How can it be faster to use a magic function to dynamically set a value instead of simply setting the value in the attribute definition?

Here is some code:

[root@vm-202-167-238-17 ~]# cat test.php; for d in A B C; do echo "------"; ./test.php $d; done;
#!/usr/bin/php
<?php

$className = $argv[1];

class A
{
    public function __get($a)
    {
        return 5;
    }
}

class B
{
    public $a = 5;
}

class C
{
    public function __get($a)
    {
        $this->a = 5;

        return 5;
    }
}

$a = new $className;

$start = microtime(true);

for ($i=0; $i < 1000000; $i++)
    $b = $a->a;

$end = microtime(true);

echo (($end - $start) * 1000) ." msec\n";

------
598.90794754028 msec
------
205.48391342163 msec
------
189.7759437561 msec

Body:
In the last case (class C), you create a property called "a" the first time the magic method is called; thereafter the magic method won't be called, it will just access the property; this is why it isn't as slow as the first case, class A.

The next question is why is case B slower than case C.  I'm guessing that it's happening at the OS level; I reversed the test order so that it tests C B A rather than A B C and suddenly test case C is slower than B, so I'm reasonably certain that the performance win there is outside of PHP; from my reasoning in the first paragraph, it stands to reason that all other things being equal test case C should be fractionally slower than test case B (as there will be one call to the magic method, then all the rest are equal).  Note also that (for me anyway) in this example A is always faster than B on 5.2.10 and on 5.3.3.

EDIT

I think that the question title is distracting from interesting issue here; the performance differences (whatever they are) are unrelated to the magic __get method.  The following example illustrates this more simply, without bothering about the __get confusing things.  Instead we create the dynamic property in the constructor; then the only difference is whether the property is declared first (e.g. public $a) or created dynamically when the value is assigned.

$className = $argv[1];

class A
{
    public function __construct() {
        $this->a = 5;
    }
}

class B extends A
{
    public $a;
}

$a = new $className;

$start = microtime(true);

for ($i=0; $i < 1000000; $i++)
    $b = $a->a;

$end = microtime(true);

echo (($end - $start) * 1000) ." msec\n";


问:
Selenium: Opening a Downloaded File in Java
I need to open and read a downloaded file using selenium and I'm not quite sure how to do it. I see answers that suggests to download the file in a selected location. Does my code really need to start from downloading the file to selected location or can it start directly after downloading?

After opening the file I must also read it. Can anyone give me an idea on how to do this? Thank you!

答:
You can read file using following code :

```<code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample1 {

    private static final String FILENAME = "E:\\test\\filename.txt";

    public static void main(String[] args) {

        BufferedReader br = null;
        FileReader fr = null;

        try {

            fr = new FileReader(FILENAME);
            br = new BufferedReader(fr);

            String sCurrentLine;

            br = new BufferedReader(new FileReader(FILENAME));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (br != null)
                    br.close();

                if (fr != null)
                    fr.close();

            } catch (IOException ex) {

                ex.printStackTrace();

            }

        }

    }

}
</code>```

Hope it will help you.

Body:
You can read file using following code :

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample1 {

    private static final String FILENAME = "E:\\test\\filename.txt";

    public static void main(String[] args) {

        BufferedReader br = null;
        FileReader fr = null;

        try {

            fr = new FileReader(FILENAME);
            br = new BufferedReader(fr);

            String sCurrentLine;

            br = new BufferedReader(new FileReader(FILENAME));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (br != null)
                    br.close();

                if (fr != null)
                    fr.close();

            } catch (IOException ex) {

                ex.printStackTrace();

            }

        }

    }

}

Hope it will help you.


问:
Volume mapped filebeat.yml permissions from Docker on a Windows host
I'm trying to run the official 5.4.3 Filebeat docker container via VirtualBox on a Windows host. Rather than creating a custom image, I'm using a volume mapping to pass the filebeat.yml file to the container using the automatically created VirtualBox mount /c/Users which points to C:\Users on my host.

Unfortunately I'm stuck on this error:

Exiting: error loading config file: config file ("filebeat.yml") can only be writable by the owner but the permissions are "-rwxrwxrwx" (to fix the permissions use: 'chmod go-w /usr/share/filebeat/filebeat.yml')

My docker-compose config is:

filebeat:
  image: "docker.elastic.co/beats/filebeat:5.4.3"
  volumes:
   - "/c/Users/Nathan/filebeat.yml:/usr/share/filebeat/filebeat.yml:ro"
   - "/c/Users/Nathan/log:/mnt/log:ro"
```

I've tried SSH-ing into the machine and running the chmod go-w command but no change. Is this some kind of permission limitation when working with VirtualBox shared folders on a Windows host?

答:
It looks like this is a side effect of the Windows DACL permissions system. Fortunately I only need this for a development environment so I've simply disabled the permission check by overriding the container entry point and passing the strict.perms argument.

filebeat:
  image: "docker.elastic.co/beats/filebeat:5.4.3"
  entrypoint: "filebeat -e -strict.perms=false"
  volumes:
   - "/c/Users/Nathan/filebeat.yml:/usr/share/filebeat/filebeat.yml:ro"
   - "/c/Users/Nathan/log:/mnt/log:ro"
```

Body:
I'm trying to run the official 5.4.3 Filebeat docker container via VirtualBox on a Windows host. Rather than creating a custom image, I'm using a volume mapping to pass the filebeat.yml file to the container using the automatically created VirtualBox mount /c/Users which points to C:\Users on my host.

Unfortunately I'm stuck on this error:

Exiting: error loading config file: config file ("filebeat.yml") can only be writable by the owner but the permissions are "-rwxrwxrwx" (to fix the permissions use: 'chmod go-w /usr/share/filebeat/filebeat.yml')

My docker-compose config is:

filebeat:
  image: "docker.elastic.co/beats/filebeat:5.4.3"
  volumes:
   - "/c/Users/Nathan/filebeat.yml:/usr/share/filebeat/filebeat.yml:ro"
   - "/c/Users/Nathan/log:/mnt/log:ro"

I've tried SSH-ing into the machine and running the chmod go-w command but no change. Is this some kind of permission limitation when working with VirtualBox shared folders on a Windows host?


问:
VBScript return value in string
I am working with a product that uses VBScript extensively and I need to parse a string to extract specific data.  I know how to do this with other languages, but need to be pointed in the right direction with VBScript please.

Here's the string I am reading from a text file.

```<code><PGConfiguration GPOName="Production Policy" GPODisplayName="Production Policy" GPOVersion="0" />
</code>```

The value between GPOName="I_NEED_THIS_DATA" needs to be pulled. It is not expected to be the same between instances.

I have a script that uses InStr() to make sure GPOName= exists and gives me the character position.  I've been able to use that with Mid() to start after the GPOName=".  I don't know how to find the count or position to the closing quote.

Am I going down the right path with InStr() and Mid(), or is there a better way to approach this (regex maybe??)

This code will open the file, read in the contents and pop up a box with the first 10 characters of what I am trying to get to.  Where do I go from here?

Thanks!

```<code>Dim objFSO, objTextFile, Stream, strSearchFor, strFileName, strLine, strPosition
' the file to check
strFileName = "C:\checkme.txt"
' what are we looking for
strSearchFor = "GPOName="

' create the object and open the file
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Stream = objFSO.OpenTextFile(strFileName, 1, False)
Set objTextFile = objFSO.OpenTextFile(strFileName, 1, 0)

' read the first line with my data on it
strLine = objTextFile.ReadLine()
' do an InStr to get the position of the data
strPosition = InStr(strLine, strSearchFor)
' set the offset to 9 to get to the end of the ="
strPosition = strPosition + 9
' print of the first 10 characters after the GPOName=" match
wscript.Echo Mid(strLine,strPosition,10)
</code>```

答:
Depends on if you need to achieve this using string or XML, you can use either of them

```<code>Set objTextFile = objFSO.OpenTextFile(strFileName, 1, 0)

' read the first line with your data on it
strLine = objTextFile.ReadLine()

arr = split(strLine , "GPOName",2)

arr2 = Split(arr(1),"""")
msgbox arr2(1)
</code>```

Need to try if you can load your file as an XML or just load the line as XML as seen below. This is a cleaner solution.

```<code>Set objXML = CreateObject("msxml2.DOMDOCUMENT")
objXML.loadXML strLine
msgbox objXML.selectSingleNode("PGConfiguration/@GPOName").text 'Or nodevalue, whichever suites you
Set objXML = Nothing
</code>```

Title: VBScript return value in string

Body:
I am working with a product that uses VBScript extensively and I need to parse a string to extract specific data.  I know how to do this with other languages, but need to be pointed in the right direction with VBScript please.

Here's the string I am reading from a text file.

<PGConfiguration GPOName="Production Policy" GPODisplayName="Production Policy" GPOVersion="0" />

The value between GPOName="I_NEED_THIS_DATA" needs to be pulled. It is not expected to be the same between instances.

I have a script that uses InStr() to make sure GPOName= exists and gives me the character position.  I've been able to use that with Mid() to start after the GPOName=".  I don't know how to find the count or position to the closing quote.

Am I going down the right path with InStr() and Mid(), or is there a better way to approach this (regex maybe??)

This code will open the file, read in the contents and pop up a box with the first 10 characters of what I am trying to get to.  Where do I go from here?

Thanks!

Dim objFSO, objTextFile, Stream, strSearchFor, strFileName, strLine, strPosition
' the file to check
strFileName = "C:\checkme.txt"
' what are we looking for
strSearchFor = "GPOName="

' create the object and open the file
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Stream = objFSO.OpenTextFile(strFileName, 1, False)
Set objTextFile = objFSO.OpenTextFile(strFileName, 1, 0)

' read the first line with my data on it
strLine = objTextFile.ReadLine()
' do an InStr to get the position of the data
strPosition = InStr(strLine, strSearchFor)
' set the offset to 9 to get to the end of the ="
strPosition = strPosition + 9
' print of the first 10 characters after the GPOName=" match
wscript.Echo Mid(strLine,strPosition,10)

Body:
Depends on if you need to achieve this using string or XML, you can use either of them

Set objTextFile = objFSO.OpenTextFile(strFileName, 1, 0)

' read the first line with your data on it
strLine = objTextFile.ReadLine()

arr = split(strLine , "GPOName",2)

arr2 = Split(arr(1),"""")
msgbox arr2(1)

Need to try if you can load your file as an XML or just load the line as XML as seen below. This is a cleaner solution.

Set objXML = CreateObject("msxml2.DOMDOCUMENT")
objXML.loadXML strLine
msgbox objXML.selectSingleNode("PGConfiguration/@GPOName").text 'Or nodevalue, whichever suites you
Set objXML = Nothing


问:
Simulating click event inside JavaScript OnClick results in error
I am building a context menu with some options using
 tags as shown below. I need to simulate click event on another ID (image), When i choose and click on this option from context menu.. I can only have the function instantaneous execution inside onclick as shown in below code-

Edited the code to give more clarity

```<code>var functionMain = function ContextMenu$functionMain(items, targetId) {
    $(menu).html(buildItems(items, targetId));
};

var buildItems = function ContextMenu$buildItems(items, targetId) {
    var i, result;
    result = '';
    for (i = 0; i < items.length; ++i) {
        var reportId = targetId.substring(targetId.indexOf(':') + 1);
        var reportIdFormed = $('#' + reportId + 'run' + runReportLinkName);
        result += '<li><a href="javascript:void(0);" style="text-decoration:none" onclick="(function(){'+ reportIdFormed+'.trigger(\'click\'); })();"> Run HTML </a></li>';
    }
    return result;
};
</code>```

Above code is resulting in Uncaught SyntaxError: Unexpected identifier

Resultant HTML --> Run HTML

How to get rid of this issue?

答:
The problem with your code is that you are trying to pass and object referent instead and ID string, so you are printing that, so JS cannot print and JS object, so it will print the reference [object Object] so you should do it like so:

```<code>var reportId = targetId.substring(targetId.indexOf(':') + 1); //e.g. rpt1234
var reportIdFormed = '#' + reportId + 'run' + runReportLinkName; //e.g. rpt1234runHTML
result += '<li><a href="javascript:void(0);" style="text-decoration:none" onclick="handleTrigger(reportIdFormed)"> Run HTML </a></li>';
</code>```

Your code JS

```<code>function handleTrigger(id) {
 var target = $(id);
 if (target.length) {
   target.trigger("click")
 }
}
</code>```

Body:
I am building a context menu with some options using
 tags as shown below. I need to simulate click event on another ID (image), When i choose and click on this option from context menu.. I can only have the function instantaneous execution inside onclick as shown in below code-

Edited the code to give more clarity

var functionMain = function ContextMenu$functionMain(items, targetId) {
    $(menu).html(buildItems(items, targetId));
};

var buildItems = function ContextMenu$buildItems(items, targetId) {
    var i, result;
    result = '';
    for (i = 0; i < items.length; ++i) {
        var reportId = targetId.substring(targetId.indexOf(':') + 1);
        var reportIdFormed = $('#' + reportId + 'run' + runReportLinkName);
        result += '
 Run HTML
';
    }
    return result;
};

Above code is resulting in Uncaught SyntaxError: Unexpected identifier

Resultant HTML --> Run HTML

How to get rid of this issue?

Body:
The problem with your code is that you are trying to pass and object referent instead and ID string, so you are printing that, so JS cannot print and JS object, so it will print the reference [object Object] so you should do it like so:

var reportId = targetId.substring(targetId.indexOf(':') + 1); //e.g. rpt1234
var reportIdFormed = '#' + reportId + 'run' + runReportLinkName; //e.g. rpt1234runHTML
result += '<li><a href="javascript:void(0);" style="text-decoration:none" onclick="handleTrigger(reportIdFormed)"> Run HTML </a></li>';

Your code JS

function handleTrigger(id) {
 var target = $(id);
 if (target.length) {
   target.trigger("click")
 }
}


问:
git not honoring git info exclude
I am working on a shared repository and I want to exclude all the files under certain directory just for myself.
So I made an entry in $GIT_ROOT/.git/info/exclude

```<code>/path/to/folder/
</code>```

After this I removed the indexes using

```<code>git rm -r --cached /path/to/folder/*
</code>```

A git status after this show a long list of deleted file staged for commit.
I commit the changes and till here all is good as any changes  made by me are not tracked by git. But I can not push the same to remote as this will mess up other developers working repo.
After this If I pull from remote it shows me a merge conflict modified by them/deleted by us. And with git reset --hard origin/<branch_name> It starts tracking the folder again.

Can this not be achieved because I can not push to remote ?

答:
A more robust solution is to:

move that folder outside of your repo

add a symlink

ignore that symlink with a git update-index --skip-worktree -- mysymlink

add a .gitignore inside that moved folder (with a '*' pattern)

put a sparce checkout in place in order to not fetch/download that specific folder.

.git/info/sparse-checkout content:

```<code>*
!/path/to/mysymlink
</code>```

(with mysymlink being the name of the folder I want to ignore)

See more at "git assume unchanged vs skip worktree - ignoring a symbolic link"

The OP shshnk mentions in the comments the simpler approach:

I was able to implement it using just sparse-checkout.

  Basically I mentioned the name of the folders in the format mentioned by you in .git/info/sparse-checkout file. Now git ignores the files in these folders.

Title: git not honoring git info exclude

Body:
I am working on a shared repository and I want to exclude all the files under certain directory just for myself.
So I made an entry in $GIT_ROOT/.git/info/exclude

/path/to/folder/

After this I removed the indexes using

git rm -r --cached /path/to/folder/*

A git status after this show a long list of deleted file staged for commit.
I commit the changes and till here all is good as any changes  made by me are not tracked by git. But I can not push the same to remote as this will mess up other developers working repo.
After this If I pull from remote it shows me a merge conflict modified by them/deleted by us. And with git reset --hard origin/<branch_name> It starts tracking the folder again.

Can this not be achieved because I can not push to remote ?

Body:
A more robust solution is to:

move that folder outside of your repo

add a symlink

ignore that symlink with a git update-index --skip-worktree -- mysymlink

add a .gitignore inside that moved folder (with a '*' pattern)

put a sparce checkout in place in order to not fetch/download that specific folder.

.git/info/sparse-checkout content:

*
!/path/to/mysymlink

(with mysymlink being the name of the folder I want to ignore)

See more at "git assume unchanged vs skip worktree - ignoring a symbolic link"

The OP shshnk mentions in the comments the simpler approach:

I was able to implement it using just sparse-checkout.

  Basically I mentioned the name of the folders in the format mentioned by you in .git/info/sparse-checkout file. Now git ignores the files in these folders.


问:
Check all $_POST Variable at once
instead of checking all my post variables from a form one at a time is there any way to run one check to atleast verify that they are not empty something like</p>

```<code>if(!isset(ALL $_POST)){
echo "one of your fields is not completed.";
}
</code>```

答:
No because how would your program know which should exist?

However, if you have a list of fields that are expected, you can easily write a function to check.  I called it array_keys_exist because it does the exact same thing as array_key_exists except with multiple keys:

```<code>function array_keys_exist($keys, $array) {
    foreach ($keys as $key) {
        if (!array_key_exists($key, $array)) return false;
    }
    return true;
}

$expectedFields = array('name', 'email');

$success = array_keys_exist($expectedFields, $_POST);
</code>```

Title: Check all $_POST Variable at once

Body:
instead of checking all my post variables from a form one at a time is there any way to run one check to atleast verify that they are not empty something like

if(!isset(ALL $_POST)){
echo "one of your fields is not completed.";
}

Body:
No because how would your program know which should exist?

However, if you have a list of fields that are expected, you can easily write a function to check.  I called it array_keys_exist because it does the exact same thing as array_key_exists except with multiple keys:

function array_keys_exist($keys, $array) {
    foreach ($keys as $key) {
        if (!array_key_exists($key, $array)) return false;
    }
    return true;
}

$expectedFields = array('name', 'email');

$success = array_keys_exist($expectedFields, $_POST);


答:
Use a delegated event

```<code>var reportId = targetId.substring(targetId.indexOf(':') + 1);
var reportIdFormed = $('#' + reportId + 'run' + runReportLinkName);

result += '<li><a href="javascript:void(0);" style="text-decoration:none" class="delegated-event"> Run HTML </a></li>';//add a class

$('body').on('click','.delegated-event',function(){ //delegate the event based on that class
   reportIdFormed.trigger('click');
})
</code>```

if the selector changes for each element then you need a attribute to store the selector:

```<code>var reportIdFormed = '#' + reportId + 'run' + runReportLinkName;//make it a string

    result += '<li><a href="javascript:void(0);" style="text-decoration:none" class="delegated-event" data-selector="'+reportIdFormed+'"> Run HTML </a></li>';//add a class

$('body').on('click','.delegated-event',function(){ //delegate the event based on that class
       reportIdFormed = $($(this).attr('data-selector'));//get the selector
       reportIdFormed.trigger('click');
    })
</code>```

Title: Simulating click event inside JavaScript OnClick results in error

Body:
Use a delegated event

var reportId = targetId.substring(targetId.indexOf(':') + 1);
var reportIdFormed = $('#' + reportId + 'run' + runReportLinkName);

result += '<li><a href="javascript:void(0);" style="text-decoration:none" class="delegated-event"> Run HTML </a></li>';//add a class

$('body').on('click','.delegated-event',function(){ //delegate the event based on that class
   reportIdFormed.trigger('click');
})

if the selector changes for each element then you need a attribute to store the selector:

var reportIdFormed = '#' + reportId + 'run' + runReportLinkName;//make it a string

    result += '<li><a href="javascript:void(0);" style="text-decoration:none" class="delegated-event" data-selector="'+reportIdFormed+'"> Run HTML </a></li>';//add a class

$('body').on('click','.delegated-event',function(){ //delegate the event based on that class
       reportIdFormed = $($(this).attr('data-selector'));//get the selector
       reportIdFormed.trigger('click');
    })


答:
If you see UIImage + AFNetworking class,It internally loads image using Async NSOperations.Try loading image with specific dimensions.It will download image of that size & could improve scrolling performance.</p>

```<code>NSMutableString *newURLPath = [NSMutableString stringWithString[exercise.imageURL absoluteString]];
 [newURLPath appendFormat:@"?width=200&"];
 [newURLPath appendFormat:@"height=200"];
</code>```

Title: Async load multiple images to single cell

Body:
I have a problem with loading of 5 images to each cell of TableView. I use AFNetworking for download and setImageWithUrl method for imageView:

for (int i = 0; i < urls.count; i++) {
    [self.photoImageView[i] setImageWithURL:urls[i]];
}

TableView very brakes when I scroll it. But when i try to load 1 or 2  no brakes when scrolling.

How to correct download images without brakes?

Body:
If you see UIImage + AFNetworking class,It internally loads image using Async NSOperations.Try loading image with specific dimensions.It will download image of that size & could improve scrolling performance.

NSMutableString *newURLPath = [NSMutableString stringWithString[exercise.imageURL absoluteString]];
 [newURLPath appendFormat:@"?width=200&"];
 [newURLPath appendFormat:@"height=200"];


问:
Ionic ng-if generates error - ionic 3
I am trying to implement product categories in ionic application as received from the api. but while implementing the same i get the following error

```<code>Error: Template parse errors:
Can't bind to 'ng-if' since it isn't a known property of 'div'."
</code>```

Here is the code:

```<code>  <div class="width50" *ngFor="let object of dataList">
    <div *ng-if= "{{object?.categories[0]?.slug}} == single">
    <img src="{{object.images[0].src}}" width="150"  (click)="navigateToPage(object.id)" />
    </div>
  </div>
</code>```

When i printed the value for {{object?.categories[0]?.slug}} the code worked fine and returned single.

using *ngif over *ng-if also does not seem to work it shows the following error.

```<code>`Template parse errors:
TypeError: key[0] is undefined ("
<ion-content padding>
  <div class="width50" *ngFor="let object of dataList">
    <div [ERROR ->]*ngIf= "{{object?.categories[0]?.slug}} == single">
    <img src="{{object.images[0].src}}" width="15"): ng:///AppModule/SinglePage.html@21:9
Can't bind to '*ngIf' since it isn't a known property of 'div'. "`
</code>```

I believe that this might happen because maybe not all objects have values is the category array. So is there a way to ensure that the *ng-if= "{{object?.categories[0]?.slug}} == single" condition is checked only after ensuring that the category array is non-empty? also can we have both the conditions and loop on the same div ?

答:
You made a type mistake it should be "*ngIf" not "ng-if",

replace this line,

```<code><div *ng-if= "{{object?.categories[0]?.slug}} == single">
</code>```

with

```<code><div *ngIf= "object?.categories[0]?.slug == single">
</code>```

problem is that you are trying to interpolate object?.categories[0]?.slug as a string inside your *ngIf condition. Remove the curly braces {{}} and your code will run fine

Title: Ionic ng-if generates error - ionic 3

Body:
I am trying to implement product categories in ionic application as received from the api. but while implementing the same i get the following error

Error: Template parse errors:
Can't bind to 'ng-if' since it isn't a known property of 'div'."

Here is the code:

When i printed the value for {{object?.categories[0]?.slug}} the code worked fine and returned single.

using *ngif over *ng-if also does not seem to work it shows the following error.

`Template parse errors:
TypeError: key[0] is undefined ("
<ion-content padding>

]*ngIf= "{{object?.categories[0]?.slug}} == single">
    <img src="{{object.images[0].src}}" width="15"): ng:///AppModule/SinglePage.html@21:9
Can't bind to '*ngIf' since it isn't a known property of 'div'. "`

I believe that this might happen because maybe not all objects have values is the category array. So is there a way to ensure that the *ng-if= "{{object?.categories[0]?.slug}} == single" condition is checked only after ensuring that the category array is non-empty? also can we have both the conditions and loop on the same div ?

Body:
You made a type mistake it should be "*ngIf" not "ng-if",

replace this line,

<div *ng-if= "{{object?.categories[0]?.slug}} == single">

with

<div *ngIf= "object?.categories[0]?.slug == single">

problem is that you are trying to interpolate object?.categories[0]?.slug as a string inside your *ngIf condition. Remove the curly braces {{}} and your code will run fine


问:
How to Remove Root Element in C#/
I'm new to XML & C#.
I want to remove root element without deleting child element.
XML file is strudctured as below.

```<code>   <?xml version="1.0" encoding="UTF-8"?>
   <dataroot generated="2013-07-06T20:26:48" xmlns:od="urn:schemas-microsoft-com:officedata">
     <MetaDataSection>
       <Name>KR04</Name>
       <XMLCreationDate>02.05.2013 9:52:41 </XMLCreationDate>
       <Address>AUTOMATIC</Address>
       <Age>22</Age>
     </MetaDataSection>
   </dataroot>
</code>```

I want to root element "dataroot", so it should look like below.

```<code>    <?xml version="1.0" encoding="UTF-8"?>
     <MetaDataSection>
       <Name>KR04</Name>
       <XMLCreationDate>02.05.2013 9:52:41 </XMLCreationDate>
       <Address>AUTOMATIC</Address>
       <Age>22</Age>
     </MetaDataSection>
</code>```

Deleting child elements look like easy, but I don't know how to delete root element only.
Below is the code I've tried so far.

```<code>        XmlDocument xmlFile = new XmlDocument();
        xmlFile.Load("path to xml");

        XmlNodeList nodes = xmlFile.SelectNodes("//dataroot");

        foreach (XmlElement element in nodes)
        {
            element.RemoveAll();
        }
</code>```

Is there a way to remove root element only? without deleting child elements?
Thank you in advnace.

答:
if you need to do in c# coding means

Solution

```<code> foreach (XElement item in Element.Descendants("dataroot").ToList())
        {
            item.ReplaceWith(item.Nodes());
        }
</code>```

Title: How to Remove Root Element in C#/

Body:
I'm new to XML & C#.
I want to remove root element without deleting child element.
XML file is strudctured as below.

   <?xml version="1.0" encoding="UTF-8"?>
   <dataroot generated="2013-07-06T20:26:48" xmlns:od="urn:schemas-microsoft-com:officedata">
     <MetaDataSection>
       <Name>KR04</Name>
       <XMLCreationDate>02.05.2013 9:52:41 </XMLCreationDate>
       <Address>AUTOMATIC</Address>
       <Age>22</Age>
     </MetaDataSection>
   </dataroot>

I want to root element "dataroot", so it should look like below.

    <?xml version="1.0" encoding="UTF-8"?>
     <MetaDataSection>
       <Name>KR04</Name>
       <XMLCreationDate>02.05.2013 9:52:41 </XMLCreationDate>
       <Address>AUTOMATIC</Address>
       <Age>22</Age>
     </MetaDataSection>

Deleting child elements look like easy, but I don't know how to delete root element only.
Below is the code I've tried so far.

        XmlDocument xmlFile = new XmlDocument();
        xmlFile.Load("path to xml");

        XmlNodeList nodes = xmlFile.SelectNodes("//dataroot");

        foreach (XmlElement element in nodes)
        {
            element.RemoveAll();
        }

Is there a way to remove root element only? without deleting child elements?
Thank you in advnace.

Body:
if you need to do in c# coding means

Solution

 foreach (XElement item in Element.Descendants("dataroot").ToList())
        {
            item.ReplaceWith(item.Nodes());
        }


问:
How to use WordPress register_script parameters?
// Docs

https://developer.wordpress.org/reference/functions/wp_register_script/

// Usage

wp_register_script( $handle, $src, $deps, $ver, $in_footer )

// Docs

$ver
    (string|bool|null) (Optional) String specifying script version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added.
    Default value: false

Q:
What happens if I pass an empty string '' to $ver?

Q:
If I use a date-time as the value for $ver woll the cache be busted and will the script reload each time the page is refreshed?

How about using dynamic date-time values that change each time the page is loaded? Is this a sound practice?

```<code><?php

$ver = filemtime( get_stylesheet_directory() . '/js/example.js');

// Bust the cache each time page is loaded
add_action( 'wp_enqueue_scripts', 'cache-buster', 15 );
function cache-buster() {
    wp_register_script( 'cache-buster', get_stylesheet_directory_uri() . '/js/example.js', array(), $ver, true );
    wp_enqueue_script( 'cache-buster' );
}
</code>```

Q:
If $ver is false because the version of WordPress remains a static value until WordPress is updated will the script remain cached because it has the same value?

Q:
If $ver is null is the script cached or not?

What are the best practices and optimal values for registering scripts in WordPress?

答:
Here are the answers to your questions -

If you pass '' to $var it will consider as false and the default WordPress version number will be added as a $var to query string.

If you use date-time value then yes, the script will be loaded each time on page refresh. So it will solve versioning issue. But it can cause page load time issue because we are not caching the script files and every time they are loading as a new.So, I think it should not be the good practice.

Yes the script remains cached because it has same value.

Yes, the script will get cached.

Body:
// Docs

https://developer.wordpress.org/reference/functions/wp_register_script/

// Usage

wp_register_script( $handle, $src, $deps, $ver, $in_footer )

// Docs

$ver
    (string|bool|null) (Optional) String specifying script version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added.
    Default value: false

Q:
What happens if I pass an empty string '' to $ver?

Q:
If I use a date-time as the value for $ver woll the cache be busted and will the script reload each time the page is refreshed?

How about using dynamic date-time values that change each time the page is loaded? Is this a sound practice?

<?php

$ver = filemtime( get_stylesheet_directory() . '/js/example.js');

// Bust the cache each time page is loaded
add_action( 'wp_enqueue_scripts', 'cache-buster', 15 );
function cache-buster() {
    wp_register_script( 'cache-buster', get_stylesheet_directory_uri() . '/js/example.js', array(), $ver, true );
    wp_enqueue_script( 'cache-buster' );
}

Q:
If $ver is false because the version of WordPress remains a static value until WordPress is updated will the script remain cached because it has the same value?

Q:
If $ver is null is the script cached or not?

What are the best practices and optimal values for registering scripts in WordPress?


问:
iPhone/iPad HTTP streaming library or server
Is there any available open-source (preferred) or commercial library for on-fly segmenting and streaming of video to iPhone / iPad?

Also, is there any open-source/commercial server (alternative to Wowza) which supports this?

答:
Apple offers mediastreamsegmenter:

https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StreamingMediaGuide/UsingHTTPLiveStreaming/UsingHTTPLiveStreaming.html

You might also want to peek at Best Practices for Creating and Deploying HTTP Live Streaming Media for the iPhone and iPad:

https://developer.apple.com/library/content/technotes/tn2224/_index.html

There's also Darwin Streaming Server, but you may not need it.


问:
How to test constructor that sets protected properties?
Well, I'm new to unit-testing (with phpUnit) and just started to test one class of mine.

Actual constructor looks like this:

```<code>/**
 * Loads configuration.
 */
function __construct() {

    $config =
        Kohana::$config->load('koffee');

    $this->_table_name = $config->table_name;
    $this->_table_columns = $config->table_columns;

}
</code>```

It basically gets configuration from another file and sets it as protected properties to that object.

Here is how unit-test looks (it's not finished and that's where I need help):

```<code>/**
 * Tests that config is loaded and correct.
 */
function testConfigIsLoadedAndCorrect() {

    $object = new Model_Article();

    $config = Kohana::$config->load('koffee');

    // Compare object's **protected** properties to local `$config`. How?!

}
</code>```

The problem is that properties are protected and I cannot access them so easy...

Possible solutions I see at the moment:

Change visibility of properties (I don't like this),

Add, so called, "getters" to class I test - not unit-test (I don't like this neither);

Probably this is funny to you, but, as I said, I'm new to unit-tests. Any help much appreciated.

答:
You can try to use ReflectionClass::newInstanceWithoutConstructor</p>

```<code>$reflector = new ReflectionClass('Model_Article');
$object = $reflector->newInstanceWithoutConstructor();
</code>```

Body:
Well, I'm new to unit-testing (with phpUnit) and just started to test one class of mine.

Actual constructor looks like this:

/**
 * Loads configuration.
 */
function __construct() {

    $config =
        Kohana::$config->load('koffee');

    $this->_table_name = $config->table_name;
    $this->_table_columns = $config->table_columns;

}

It basically gets configuration from another file and sets it as protected properties to that object.

Here is how unit-test looks (it's not finished and that's where I need help):

/**
 * Tests that config is loaded and correct.
 */
function testConfigIsLoadedAndCorrect() {

    $object = new Model_Article();

    $config = Kohana::$config->load('koffee');

    // Compare object's **protected** properties to local `$config`. How?!

}

The problem is that properties are protected and I cannot access them so easy...

Possible solutions I see at the moment:

Change visibility of properties (I don't like this),

Add, so called, "getters" to class I test - not unit-test (I don't like this neither);

Probably this is funny to you, but, as I said, I'm new to unit-tests. Any help much appreciated.

Body:
You can try to use ReflectionClass::newInstanceWithoutConstructor

$reflector = new ReflectionClass('Model_Article');
$object = $reflector->newInstanceWithoutConstructor();


问:
Tuple and List to formatted string in python
In Python3.4 I have a tuple

```<code>t = ('A', 'B', 'C')
</code>```

and a list

```<code>l = ['P', 'Q', 'R']
</code>```

and I need to convert the tuple to a string formatted as "(#A;#B;#C)" and the list to a string formatted as "(@P; @Q; @R)". The obvious way is to traverse using a for loop and string manipulation.

Is there a way to do it without running the loop?

Thanks!

答:
i dont know why you dont want to use the for loop, but you can do it using list comprehension, you will use the for loop, but in a prettier way

```<code>l = ['P', 'Q', 'R']

new = '('+'; '.join(['@'+i for i in l])+')'

print(new)
(@P; @Q; @R)
</code>```

you could do the same for the tuple.

Body:
In Python3.4 I have a tuple

t = ('A', 'B', 'C')

and a list

l = ['P', 'Q', 'R']

and I need to convert the tuple to a string formatted as "(#A;#B;#C)" and the list to a string formatted as "(@P; @Q; @R)". The obvious way is to traverse using a for loop and string manipulation.

Is there a way to do it without running the loop?

Thanks!

Body:
i dont know why you dont want to use the for loop, but you can do it using list comprehension, you will use the for loop, but in a prettier way

l = ['P', 'Q', 'R']

new = '('+'; '.join(['@'+i for i in l])+')'

print(new)
(@P; @Q; @R)

you could do the same for the tuple.


问:
AndroidStudio: Failed to sync Install build tools
Going crazy with this error from about a couple of hours.

The error is:

```<code>failed to find Build Tools revision 23.0.0 rc1
</code>```

But I think to have all update (also the release candidate!)

This is the image: thank you.

答:
One of the answers ask you to use buildToolsVersion 23.0.0, but you would get buildToolsVersion 23.0.0 has serious bugs use buildToolsVersion 23.0.3. I did that then I started getting message buildToolsVersion 23.0.3 is too low from project app update to buildToolsVersion 25.0.0 and sync again. So I did that and it worked , So here are the final changes.

Inside app's build.gradle change this

```<code>android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0 rc2"
}
</code>```

with this one

```<code>android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0"
}
</code>```

Body:
Going crazy with this error from about a couple of hours.

The error is:

failed to find Build Tools revision 23.0.0 rc1

But I think to have all update (also the release candidate!)

This is the image: thank you.

Body:
One of the answers ask you to use buildToolsVersion 23.0.0, but you would get buildToolsVersion 23.0.0 has serious bugs use buildToolsVersion 23.0.3. I did that then I started getting message buildToolsVersion 23.0.3 is too low from project app update to buildToolsVersion 25.0.0 and sync again. So I did that and it worked , So here are the final changes.

Inside app's build.gradle change this

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0 rc2"
}

with this one

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0"
}


问:
Check if user accepted a push notification permission in iOS in codenameone
How can I check if the user denied or accepted the push notification permission message in ios in codenameone or native?</p>

答:
Both Android and iOS have API's to detect if push is enabled:
Push Notification ON or OFF Checking in iOS

Android 4.1: How to check notifications are disabled for the application?

Since those were added relatively recently and we didn't get enough demand for that we don't support them at this time. You can probably invoke them with a native interface or submit a pull request with integration. Normally you would get a push registered callback when push works and an error or nothing if it doesn't.


问:
Set raw asset as wallpaper from selected drawable
I have a gridview that contains an array of images in my drawable folder. I have it worked out right now to send the drawable to another activity where the user will view the image before setting a picture from the raw folder as the wallpaper. I can't use the drawable asset because of compression and a suitable image cause a crash from a lack of memory.

My MainActivity file with the gridview:

```<code>GridView androidGridView;

private Integer asset1 = R.drawable.asset1;
private Integer asset2 = R.drawable.asset2;
private Integer asset3 = R.drawable.asset1;
private Integer asset4 = R.drawable.asset2;
private Integer asset5 = R.drawable.asset1;
private Integer asset6 = R.drawable.asset2;
private Integer[] images = {
        asset1, asset2, asset3,
        asset4, asset5, asset6
};

Integer[] imagesIDs = {
        R.raw.asset1, R.raw.asset2, R.drawable.asset1,
        R.drawable.asset1, R.drawable.asset1, R.drawable.asset1,
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    androidGridView = findViewById(R.id.gridview_android_example);
    androidGridView.setAdapter(new ImageAdapterGridView(this));

    androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent,
                                View v, int position, long id) {
            int imageRes = images[position];

            Intent intent = new Intent(MainActivity.this, ViewActivity.class);
            intent.putExtra("IMAGE_RES", imageRes);
            startActivity(intent);
        }
    });

}

public class ImageAdapterGridView extends BaseAdapter {
    private Context mContext;

    public ImageAdapterGridView(Context c) {
        mContext = c;
    }

    public int getCount() {
        return images.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView mImageView;

        if (convertView == null) {
            mImageView = new ImageView(mContext);
            mImageView.setLayoutParams(new GridView.LayoutParams(525, 350));
            mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            mImageView.setPadding(16, 16, 16, 16);
        } else {
            mImageView = (ImageView) convertView;
        }
        mImageView.setImageResource(images[position]);
        return mImageView;
    }
</code>```

My ViewActivity file where the user will preview the image before setting it as the wallpaper:

```<code>private Integer asset1 = R.raw.asset1;
private Integer asset2 = R.raw.asset2;
private Integer asset3 = R.raw.asset1;
private Integer asset4 = R.raw.asset2;
private Integer asset5 = R.raw.asset1;
private Integer asset6 = R.raw.asset2;
private Integer[] images = {
        asset1, asset2, asset3,
        asset4, asset5, asset6
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view);

    Bundle extras = getIntent().getExtras();
    int imageRes = extras.getInt("IMAGE_RES");

    ImageView preview = findViewById(R.id.preview);
    preview.setImageResource(imageRes);
    preview.setScaleType(ImageView.ScaleType.CENTER_CROP);

    Button set = findViewById(R.id.setButton);
    set.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
}
</code>```

I'm not sure whether or not I'm on the right track, but if anyone can point me in the right direction that would be great!

答:
A lot has been written on SO about Out of Memory errors when working with bitmaps and images in android apps: here, here and here, for example.

For the special purpose of setting the wallpaper on a device, you might try this sort of approach. I don't guarantee that you'll always avoid OOM errors doing it this way, but it should prevent most of them.

It does that by trying to stay within the app's current free memory when it decodes the resource into a bitmap. It also recycles the bitmap at the end.

One advantage is that you don't have to come up with the required width and height of the output bitmap. It does that for you, based on free memory. (That's also a disadvantage -- you're not free to choose whatever bitmap dimensions you want. They might be too large and cause a crash.)

It can take some time to do the decoding, which is why it's done on a background thread.

Anyway, this works for me:

Add an ExecutorService and the method decodeBitmapWithinFreeMemory to your ViewActivity:

```<code>private ExecutorService executor = Executors.newSingleThreadExecutor();

...

// adapted from https://developer.android.com/topic/performance/graphics/load-bitmap.html
private Bitmap decodeResourceWithinFreeMemory(Resources resources, int resourceId, float requiredAspectRatio) {

    // get just the size of the resource image
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(resources, resourceId, options);

    // estimate number of pixels we can work with in current free memory
    long freeMem = Runtime.getRuntime().freeMemory();
    long spaceForARGV8888Px = freeMem / 4; // est. number of ARGV_8888 pixels that can be stored

    // calculate the sides of a rectangle with approximately that number of pixels
    long squareRootLowerBound = (long) Math.floor(Math.pow(spaceForARGV8888Px, 0.5));
    int requestedWidth = (int) Math.floor(squareRootLowerBound * requiredAspectRatio);
    int requestedHeight = (int) Math.floor(squareRootLowerBound / requiredAspectRatio);

    // find the right sample size by aggressively increasing sampleSize var: require only that
    // _one_ of the output dimensions be greater than the corresponding requested dimension
    int sampleSize = 1;
    while ((options.outHeight / (2 * sampleSize) ) >= requestedHeight
            || (options.outWidth / (2 * sampleSize) ) >= requestedWidth) {
        sampleSize *= 2;
    }

    // output the bitmap by sampling the input resource at the calculated sampleSize
    options.inSampleSize = sampleSize;
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(resources, resourceId, options);
}
</code>```

Invoke decodeBitmapWithinFreeMemory inside the button's onClick method, feeding it the device's screen aspect ratio:

```<code>DisplayMetrics metrics = getResources().getDisplayMetrics();
final float screenAspectRatio = (float)metrics.widthPixels/(float)metrics.heightPixels;
executor.submit(new Runnable() {
    @Override
    public void run() {
        try {
            Bitmap drawableAsBitmap = decodeResourceWithinFreeMemory(getResources(),
                    R.raw.asset1, screenAspectRatio);
            WallpaperManager.getInstance(MainActivity.this).setBitmap(drawableAsBitmap);
            drawableAsBitmap.recycle();
        } catch (IOException ioe) {
            Log.e(TAG, "Could not set wallpaper to bitmap", ioe);
        }
    }
});
</code>```

Also note that you can optionally add a BroadcastReceiver to your Activities to be notified that the wallpaper has been set. (See the documentation for setBitmap.)

Body:
I have a gridview that contains an array of images in my drawable folder. I have it worked out right now to send the drawable to another activity where the user will view the image before setting a picture from the raw folder as the wallpaper. I can't use the drawable asset because of compression and a suitable image cause a crash from a lack of memory.

My MainActivity file with the gridview:

GridView androidGridView;

private Integer asset1 = R.drawable.asset1;
private Integer asset2 = R.drawable.asset2;
private Integer asset3 = R.drawable.asset1;
private Integer asset4 = R.drawable.asset2;
private Integer asset5 = R.drawable.asset1;
private Integer asset6 = R.drawable.asset2;
private Integer[] images = {
        asset1, asset2, asset3,
        asset4, asset5, asset6
};

Integer[] imagesIDs = {
        R.raw.asset1, R.raw.asset2, R.drawable.asset1,
        R.drawable.asset1, R.drawable.asset1, R.drawable.asset1,
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    androidGridView = findViewById(R.id.gridview_android_example);
    androidGridView.setAdapter(new ImageAdapterGridView(this));

    androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent,
                                View v, int position, long id) {
            int imageRes = images[position];

            Intent intent = new Intent(MainActivity.this, ViewActivity.class);
            intent.putExtra("IMAGE_RES", imageRes);
            startActivity(intent);
        }
    });

}

public class ImageAdapterGridView extends BaseAdapter {
    private Context mContext;

    public ImageAdapterGridView(Context c) {
        mContext = c;
    }

    public int getCount() {
        return images.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView mImageView;

        if (convertView == null) {
            mImageView = new ImageView(mContext);
            mImageView.setLayoutParams(new GridView.LayoutParams(525, 350));
            mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            mImageView.setPadding(16, 16, 16, 16);
        } else {
            mImageView = (ImageView) convertView;
        }
        mImageView.setImageResource(images[position]);
        return mImageView;
    }

My ViewActivity file where the user will preview the image before setting it as the wallpaper:

private Integer asset1 = R.raw.asset1;
private Integer asset2 = R.raw.asset2;
private Integer asset3 = R.raw.asset1;
private Integer asset4 = R.raw.asset2;
private Integer asset5 = R.raw.asset1;
private Integer asset6 = R.raw.asset2;
private Integer[] images = {
        asset1, asset2, asset3,
        asset4, asset5, asset6
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view);

    Bundle extras = getIntent().getExtras();
    int imageRes = extras.getInt("IMAGE_RES");

    ImageView preview = findViewById(R.id.preview);
    preview.setImageResource(imageRes);
    preview.setScaleType(ImageView.ScaleType.CENTER_CROP);

    Button set = findViewById(R.id.setButton);
    set.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
}

I'm not sure whether or not I'm on the right track, but if anyone can point me in the right direction that would be great!

Body:
A lot has been written on SO about Out of Memory errors when working with bitmaps and images in android apps: here, here and here, for example.

For the special purpose of setting the wallpaper on a device, you might try this sort of approach. I don't guarantee that you'll always avoid OOM errors doing it this way, but it should prevent most of them.

It does that by trying to stay within the app's current free memory when it decodes the resource into a bitmap. It also recycles the bitmap at the end.

One advantage is that you don't have to come up with the required width and height of the output bitmap. It does that for you, based on free memory. (That's also a disadvantage -- you're not free to choose whatever bitmap dimensions you want. They might be too large and cause a crash.)

It can take some time to do the decoding, which is why it's done on a background thread.

Anyway, this works for me:

Add an ExecutorService and the method decodeBitmapWithinFreeMemory to your ViewActivity:

private ExecutorService executor = Executors.newSingleThreadExecutor();

...

// adapted from https://developer.android.com/topic/performance/graphics/load-bitmap.html
private Bitmap decodeResourceWithinFreeMemory(Resources resources, int resourceId, float requiredAspectRatio) {

    // get just the size of the resource image
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(resources, resourceId, options);

    // estimate number of pixels we can work with in current free memory
    long freeMem = Runtime.getRuntime().freeMemory();
    long spaceForARGV8888Px = freeMem / 4; // est. number of ARGV_8888 pixels that can be stored

    // calculate the sides of a rectangle with approximately that number of pixels
    long squareRootLowerBound = (long) Math.floor(Math.pow(spaceForARGV8888Px, 0.5));
    int requestedWidth = (int) Math.floor(squareRootLowerBound * requiredAspectRatio);
    int requestedHeight = (int) Math.floor(squareRootLowerBound / requiredAspectRatio);

    // find the right sample size by aggressively increasing sampleSize var: require only that
    // _one_ of the output dimensions be greater than the corresponding requested dimension
    int sampleSize = 1;
    while ((options.outHeight / (2 * sampleSize) ) >= requestedHeight
            || (options.outWidth / (2 * sampleSize) ) >= requestedWidth) {
        sampleSize *= 2;
    }

    // output the bitmap by sampling the input resource at the calculated sampleSize
    options.inSampleSize = sampleSize;
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(resources, resourceId, options);
}

Invoke decodeBitmapWithinFreeMemory inside the button's onClick method, feeding it the device's screen aspect ratio:

DisplayMetrics metrics = getResources().getDisplayMetrics();
final float screenAspectRatio = (float)metrics.widthPixels/(float)metrics.heightPixels;
executor.submit(new Runnable() {
    @Override
    public void run() {
        try {
            Bitmap drawableAsBitmap = decodeResourceWithinFreeMemory(getResources(),
                    R.raw.asset1, screenAspectRatio);
            WallpaperManager.getInstance(MainActivity.this).setBitmap(drawableAsBitmap);
            drawableAsBitmap.recycle();
        } catch (IOException ioe) {
            Log.e(TAG, "Could not set wallpaper to bitmap", ioe);
        }
    }
});

Also note that you can optionally add a BroadcastReceiver to your Activities to be notified that the wallpaper has been set. (See the documentation for setBitmap.)


问:
Session store not set on request in Laravel 5.3
My website got an error like this:

I also tried some solution like wrap Route in middleware web it it didn't works

Here is my Kernel.php

```<code><?php

namespace App\Http;

use App\Http\Middleware\Activated;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{

    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \anlutro\LaravelSettings\SaveMiddleware::class,
            \Barryvdh\Cors\HandleCors::class,
            Activated::class
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
(The rest of file)
    }
</code>```

How can i resolve that :((

答:
If adding your routes inside the web middleware doesn't work for any reason then try adding this to $middleware into Kernel.php

```<code>protected $middleware = [
    //...
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
</code>```

Body:
My website got an error like this:

I also tried some solution like wrap Route in middleware web it it didn't works

Here is my Kernel.php

<?php

namespace App\Http;

use App\Http\Middleware\Activated;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{

    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \anlutro\LaravelSettings\SaveMiddleware::class,
            \Barryvdh\Cors\HandleCors::class,
            Activated::class
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
(The rest of file)
    }

How can i resolve that :((

Body:
If adding your routes inside the web middleware doesn't work for any reason then try adding this to $middleware into Kernel.php

protected $middleware = [
    //...
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];


问:
inlining failed in call to always_inline '__m256d _mm256_broadcast_sd(const double*)'
I'm trying to run a Visual Studio cpp project created by a friend of mine. I'm trying to run the file without VS. But I'm getting a list of errors, all in the same format:

```<code>inlining failed in call to always_inline '__m256d _mm256_broadcast_sd(const double*)': target specific option mismatch|
</code>```

It runs correctly in VS with release mode and breaks when run in debug mode.

The includes are as follows:

```<code>#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
# include <omp.h>
#include <chrono>
#include <fstream>
#include <algorithm>

#include <immintrin.h>

using namespace std::chrono;
using namespace std;
</code>```

and the error is called from here:

```<code>double zero = 0;
__m256d acc = _mm256_broadcast_sd(&zero);
</code>```

Update:

I'm using the this command to run it: g++ -std=c++0x multip.cpp -o multip, is there an additional parameter to add -mavx to the compiler invocation?

答:
"Target specific option mismatch" means that you're missing a feature flag from your GCC invocation. You probably need to add -mavx to your compiler invocation.

If you're intending to run this on your computer only, -march=native will turn on all the feature flags that your own machine supports.

Body:
I'm trying to run a Visual Studio cpp project created by a friend of mine. I'm trying to run the file without VS. But I'm getting a list of errors, all in the same format:

inlining failed in call to always_inline '__m256d _mm256_broadcast_sd(const double*)': target specific option mismatch|

It runs correctly in VS with release mode and breaks when run in debug mode.

The includes are as follows:

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
# include <omp.h>
#include <chrono>
#include <fstream>
#include <algorithm>

#include <immintrin.h>

using namespace std::chrono;
using namespace std;

and the error is called from here:

double zero = 0;
__m256d acc = _mm256_broadcast_sd(&zero);

Update:

I'm using the this command to run it: g++ -std=c++0x multip.cpp -o multip, is there an additional parameter to add -mavx to the compiler invocation?


问:
How to use a complex associative array in javascript?
I need this table http://code.google.com/apis/chart/docs/gallery/qr_codes.html#details in my program and I'm not even sure if an associative array is the way to go.

Given the type (numeric/alphanumeric), number of characters and EC (error correction) level, I want a function to return the version (first column).

答:
First, JavaScript has "Arrays" and "Objects". By 'associative array' I assume you mean a JavaScript Object, using keys other than non-negative integers.

You can create JavaScript object literals using syntax such as the following:

```<code>var versions = {
  "1" : {
    rowcols : [21,21],
    charsByECLevel : {
      L : {
        digits:41,
        alpha:25
      },
      M : {
        digits:34,
        alpha:20
      }
    }
  },
  "2" : {
    rowcols : [25,25],
    charsByECLevel : {
      L : {
        digits:77,
        alpha:47
      },
      M : {
        digits:63,
        alpha:48
      }
    }
  }
};
</code>```

You would then access the properties like so:

```<code>console.log( versions[1].charsByECLevel.L.digits );
// 41
</code>```

To loop through the values, you could do this:

```<code>function findVersion( versions, level, digits ){
  for (var versionNumber in versions){
    if (versions.hasOwnProperty(versionNumber)){
      if (versions[versionNumber].charsByECLevel[level].digits == digits){
        return versionNumber;
      }
    }
  }
}

findVersion( versions, "L", 77 );
// returns "2"
</code>```

Edit: Having written the above, if you only want to look up versions based on level and digits, you should probably reverse the hash. Instead of looping through and checking the versions, index them directly and look it up in constant time:

```<code>var versionByLevelAndDigits = {
  L : {
     41 : 1,
     77 : 2,
    127 : 3
  },
  M : {
     34 : 1,
     63 : 2,
    101 : 3
  }
};

var version = versionByLevelAndDigits["L"][77];
// 2
</code>```

Body:
First, JavaScript has "Arrays" and "Objects". By 'associative array' I assume you mean a JavaScript Object, using keys other than non-negative integers.

You can create JavaScript object literals using syntax such as the following:

var versions = {
  "1" : {
    rowcols : [21,21],
    charsByECLevel : {
      L : {
        digits:41,
        alpha:25
      },
      M : {
        digits:34,
        alpha:20
      }
    }
  },
  "2" : {
    rowcols : [25,25],
    charsByECLevel : {
      L : {
        digits:77,
        alpha:47
      },
      M : {
        digits:63,
        alpha:48
      }
    }
  }
};

You would then access the properties like so:

console.log( versions[1].charsByECLevel.L.digits );
// 41

To loop through the values, you could do this:

function findVersion( versions, level, digits ){
  for (var versionNumber in versions){
    if (versions.hasOwnProperty(versionNumber)){
      if (versions[versionNumber].charsByECLevel[level].digits == digits){
        return versionNumber;
      }
    }
  }
}

findVersion( versions, "L", 77 );
// returns "2"

Edit: Having written the above, if you only want to look up versions based on level and digits, you should probably reverse the hash. Instead of looping through and checking the versions, index them directly and look it up in constant time:

var versionByLevelAndDigits = {
  L : {
     41 : 1,
     77 : 2,
    127 : 3
  },
  M : {
     34 : 1,
     63 : 2,
    101 : 3
  }
};

var version = versionByLevelAndDigits["L"][77];
// 2


问:
SQLite add Primary Key
I created a table in Sqlite by using the CREATE TABLE AS syntax to create a table based on a SELECT statement.  Now this table has no primary key but I would like to add one.

Executing ALTER TABLE table_name ADD PRIMARY KEY(col1, col2,...) gives a syntax error "near PRIMARY"

Is there a way to add a primary key either during table creation or afterwards in Sqlite?

By "during creation" I mean during creation with CREATE TABLE AS.

答:
```<code>sqlite>  create table t(id integer, col2 varchar(32), col3 varchar(8));
sqlite>  insert into t values(1, 'he', 'ha');
sqlite>
sqlite>  create table t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite>  insert into t2 select * from t;
sqlite> .schema
CREATE TABLE t(id integer, col2 varchar(32), col3 varchar(8));
CREATE TABLE t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite> drop table t;
sqlite> alter table t2 rename to t;
sqlite> .schema
CREATE TABLE IF NOT EXISTS "t"(id integer primary key, col2 varchar(32), col3 varchar(8));
</code>```

Title: SQLite add Primary Key