问:
WORDPRESS How to add custom fields from taxonomy into a loop
I have a 3 custom post types created (Movies, Videos and Reviews) and 1 taxonomy (Artists).

I have a loop inside the single-movies.php and inside it shows some informations about the movie, all gathered from the post. Here's what I'm working on:

```<code><section class="aboutmovie">
             <h1><?php echo get_post_meta( $post->ID, '_titulobr_filme', true ); ?></h1>

                <img src="<?php echo get_post_meta( $post->ID, '_poster_filme', true ); ?>">

                <h3><?php echo get_post_meta( $post->ID, '_titulo_filme', true ); ?></h3>
                <span class="genero"><?php echo get_post_meta( $post->ID, '_genero_filme', true ); ?></span><br>
                <span class="ano"><?php echo get_post_meta( $post->ID, '_pais_filme', true ); ?>, <?php echo get_post_meta( $post->ID, '_ano_filme', true ); ?></span><br>
                <span class="dist"><?php echo get_post_meta( $post->ID, '_distribuidora_filme', true ); ?></span><br>

                <span class="diretor"><b>Diretor:</b> <?php echo get_post_meta( $post->ID, '_diretor_filme', true ); ?></span><br>
                <span class="roteiro"><b>Roteiro:</b> <?php echo get_post_meta( $post->ID, '_roteiro_filme', true ); ?></span>
</section>
</code>```

I need to add the CAST. For that I need the terms from that taxonomy (artists). I was able to show the list using this:

```<code><?php echo get_the_term_list(
    $post->ID,
    'artistas',
    '<ul class="artistas"><li>',
    ',</li><li>',
    '</li></ul>'
);  ?>
</code>```

But I also need some information from the custom fields of those terms (term metas: nome and imagem). Basically I need to show an image (I have a custom field called "imagem" to add a link), the link to the artist page and his name. How can I do that?

答:
Try this </p>

```<code> <ul>
<?php echo get_the_term_list( $post->ID, 'artistas', '<li class="artistas">', ', ', '</li>' ) ?>
</ul>
</code>```

Body:
I have a 3 custom post types created (Movies, Videos and Reviews) and 1 taxonomy (Artists).

I have a loop inside the single-movies.php and inside it shows some informations about the movie, all gathered from the post. Here's what I'm working on:

<?php echo get_post_meta( $post->ID, '_titulobr_filme', true ); ?>

                <img src="<?php echo get_post_meta( $post->ID, '_poster_filme', true ); ?>">

<?php echo get_post_meta( $post->ID, '_titulo_filme', true ); ?>

                <?php echo get_post_meta( $post->ID, '_genero_filme', true ); ?>

                <?php echo get_post_meta( $post->ID, '_pais_filme', true ); ?>, <?php echo get_post_meta( $post->ID, '_ano_filme', true ); ?>

                <?php echo get_post_meta( $post->ID, '_distribuidora_filme', true ); ?>

                Diretor: <?php echo get_post_meta( $post->ID, '_diretor_filme', true ); ?>

                Roteiro: <?php echo get_post_meta( $post->ID, '_roteiro_filme', true ); ?>

I need to add the CAST. For that I need the terms from that taxonomy (artists). I was able to show the list using this:

<?php echo get_the_term_list(
    $post->ID,
    'artistas',
    '

',
    ',

',
    '

'
);  ?>

But I also need some information from the custom fields of those terms (term metas: nome and imagem). Basically I need to show an image (I have a custom field called "imagem" to add a link), the link to the artist page and his name. How can I do that?

Body:
Try this

 <ul>
<?php echo get_the_term_list( $post->ID, 'artistas', '<li class="artistas">', ', ', '</li>' ) ?>
</ul>


来源: stackexchange

问:
Heuristic Function in a maze in C
```<code>int heuristic(Maze* maze, int x0, int y0, int x1, int y1)
{
    return abs(x0 - x1) + abs(y0 - y1);
}
</code>```

I am searching heuristic function for a maze which includes the altitudes. I found a code with two parameters(x and y). Is there a possibility to have heuristic function which includes axe z(for altitudes) ?

答:
```<code>int heuristic(Maze* maze, int x0, int y0, int x1, int y1, int z0, int z1)
{
    return abs(x0 - x1) + abs(y0 - y1)+ abs(z0-z1);
}
</code>```

<p>? – alberto</p>

ContentLicense: CC BY-SA 3.0

Title: Heuristic Function in a maze in C

Body:
int heuristic(Maze* maze, int x0, int y0, int x1, int y1)
{
    return abs(x0 - x1) + abs(y0 - y1);
}

I am searching heuristic function for a maze which includes the altitudes. I found a code with two parameters(x and y). Is there a possibility to have heuristic function which includes axe z(for altitudes) ?

Body:
int heuristic(Maze* maze, int x0, int y0, int x1, int y1, int z0, int z1)
{
    return abs(x0 - x1) + abs(y0 - y1)+ abs(z0-z1);
}

? – alberto


问:
WPF - Two Columns align right column
I have the following XAML, which I have tried to simplify and removed irrelevant code such as name, content, bindings etc.

The problem is that the textbox on the right is not very nicely aligned. I expect the textboxes to be aligned so they are of equal width.

XAML code:

```<code><StackPanel Grid.Row="1" Grid.RowSpan="2" Grid.Column="1" MinWidth="200" HorizontalAlignment="Right">
<GroupBox >
    <GroupBox.HeaderTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>

                <TextBlock Grid.Row="0" Grid.Column="1" Margin="5"/>
            </Grid>
        </DataTemplate>
    </GroupBox.HeaderTemplate>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="69"/>
            <ColumnDefinition Width="6"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label Grid.Column="0" Grid.Row="0" Margin="5" VerticalAlignment="Center" Grid.ColumnSpan="2"/>
        <TextBox Grid.Column="2" Grid.Row="0" Margin="5,7" VerticalAlignment="Center"/>

        <Label Grid.Column="0" Grid.Row="1" Margin="5" VerticalAlignment="Center" Grid.ColumnSpan="2"/>
        <TextBox Grid.Column="2" Grid.Row="1" Margin="5,7" VerticalAlignment="Center"/>

        <ItemsControl Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>

                        <Label Grid.Column="0" Grid.Row="0" Margin="5" VerticalAlignment="Center"/>
                        <TextBox Grid.Column="1" Grid.Row="0" Margin="5" VerticalAlignment="Center"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</GroupBox>
</StackPanel>
</code>```

I have tried a lot of different combinations but can't get it to as I want for my end goal.

答:
You can specify on the Grid above the Itemscontrol: Grid.IsSharedSizeScope='True'.
Then, in the DataTemplate for item, specify on the first ColumnDefinition:
SharedSizeGroup='LabelsColumn(or any name you like)'.
That will recalculate automatically the width of the first column, to be as long as the longest text/Label(in this scenario).
Example:</p>

```<code><StackPanel Grid.Row="1"
                Grid.RowSpan="2"
                Grid.Column="1"
                MinWidth="200"
                HorizontalAlignment="Right">
        <GroupBox>
            <GroupBox.HeaderTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>

                        <TextBlock Grid.Row="0"
                                   Grid.Column="1"
                                   Margin="5" />
                    </Grid>
                </DataTemplate>
            </GroupBox.HeaderTemplate>
            <Grid Grid.IsSharedSizeScope="True">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"
                                      SharedSizeGroup="Labels"/>
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0"
                       Grid.Row="0"
                       Margin="5"
                       VerticalAlignment="Center"
                       Grid.ColumnSpan="2" />
                <TextBox Grid.Column="1"
                         Grid.Row="0"
                         Margin="5,7"
                         VerticalAlignment="Center" />

                <Label Grid.Column="0"
                       Grid.Row="1"
                       Margin="5"
                       VerticalAlignment="Center"
                       Grid.ColumnSpan="2" />
                <TextBox Grid.Column="1"
                         Grid.Row="1"
                         Margin="5,7"
                         VerticalAlignment="Center" />

                <ItemsControl Grid.Row="2"
                              Grid.Column="0"
                              Grid.ColumnSpan="3">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto"
                                                      SharedSizeGroup="Labels"/>
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>

                                <Label Grid.Column="0"
                                       Grid.Row="0"
                                       Margin="5"
                                       VerticalAlignment="Center" />
                                <TextBox Grid.Column="1"
                                         Grid.Row="0"
                                         Margin="5"
                                         VerticalAlignment="Center" />
                            </Grid>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </Grid>
        </GroupBox>
    </StackPanel>
</code>```

Title: WPF - Two Columns align right column

Body:
I have the following XAML, which I have tried to simplify and removed irrelevant code such as name, content, bindings etc.

The problem is that the textbox on the right is not very nicely aligned. I expect the textboxes to be aligned so they are of equal width.

XAML code:

<StackPanel Grid.Row="1" Grid.RowSpan="2" Grid.Column="1" MinWidth="200" HorizontalAlignment="Right">
<GroupBox >
    <GroupBox.HeaderTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>

                <TextBlock Grid.Row="0" Grid.Column="1" Margin="5"/>
            </Grid>
        </DataTemplate>
    </GroupBox.HeaderTemplate>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="69"/>
            <ColumnDefinition Width="6"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <TextBox Grid.Column="2" Grid.Row="0" Margin="5,7" VerticalAlignment="Center"/>

        <TextBox Grid.Column="2" Grid.Row="1" Margin="5,7" VerticalAlignment="Center"/>

        <ItemsControl Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>

                        <TextBox Grid.Column="1" Grid.Row="0" Margin="5" VerticalAlignment="Center"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</GroupBox>
</StackPanel>

I have tried a lot of different combinations but can't get it to as I want for my end goal.

Body:
You can specify on the Grid above the Itemscontrol: Grid.IsSharedSizeScope='True'.
Then, in the DataTemplate for item, specify on the first ColumnDefinition:
SharedSizeGroup='LabelsColumn(or any name you like)'.
That will recalculate automatically the width of the first column, to be as long as the longest text/Label(in this scenario).
Example:

<StackPanel Grid.Row="1"
                Grid.RowSpan="2"
                Grid.Column="1"
                MinWidth="200"
                HorizontalAlignment="Right">
        <GroupBox>
            <GroupBox.HeaderTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>

                        <TextBlock Grid.Row="0"
                                   Grid.Column="1"
                                   Margin="5" />
                    </Grid>
                </DataTemplate>
            </GroupBox.HeaderTemplate>
            <Grid Grid.IsSharedSizeScope="True">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"
                                      SharedSizeGroup="Labels"/>
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0"
                       Grid.Row="0"
                       Margin="5"
                       VerticalAlignment="Center"
                       Grid.ColumnSpan="2" />
                <TextBox Grid.Column="1"
                         Grid.Row="0"
                         Margin="5,7"
                         VerticalAlignment="Center" />

                <Label Grid.Column="0"
                       Grid.Row="1"
                       Margin="5"
                       VerticalAlignment="Center"
                       Grid.ColumnSpan="2" />
                <TextBox Grid.Column="1"
                         Grid.Row="1"
                         Margin="5,7"
                         VerticalAlignment="Center" />

                <ItemsControl Grid.Row="2"
                              Grid.Column="0"
                              Grid.ColumnSpan="3">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto"
                                                      SharedSizeGroup="Labels"/>
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>

                                <Label Grid.Column="0"
                                       Grid.Row="0"
                                       Margin="5"
                                       VerticalAlignment="Center" />
                                <TextBox Grid.Column="1"
                                         Grid.Row="0"
                                         Margin="5"
                                         VerticalAlignment="Center" />
                            </Grid>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </Grid>
        </GroupBox>
    </StackPanel>


问:
swagger-codegen header parameter for Java REST Client
I am using swagger-codegen for generating a Java REST client for one of my REST APIs. The REST APIs take an optional header parameter. The generated methods in the client have an additional parameter that takes the header. I would like the methods to be generated without the header parameter in the method signature.
I have read the documentation, but couldn't find any reference.

For example, for a GET all API with option X-CUSTOM-HEADER parameter, swagger-codegen generates a method like below:

```<code>public List<SomeType> findAllUsingGET1(String optionalHeader)
</code>```

where as I would like it to be:

```<code>public List<SomeType> findAllUsingGET1()
</code>```

Looking for pointers for the workaround rather than customizing the client-code generation.

EDIT 1: Adding the JSON spec

```<code>  "get": {
    "summary": "findAll",
    "operationId": "findAllUsingGET1",
    "consumes": [
      "application/json"
    ],
    "produces": [
      "application/json"
    ],
    "parameters": [
      {
        "name": "X-CUSTOM-HEADER",
        "in": "header",
        "description": "Custom Header",
        "required": false,
        "type": "string"
      }
    ],
    "responses": {
      "200": {
        "description": "OK",
        "schema": {
          "type": "string"
        }
      },
      "401": {
        "description": "Unauthorized"
      },
      "403": {
        "description": "Forbidden"
      },
      "404": {
        "description": "Not Found"
      }
    }
  }
</code>```

答:
If you want to remove a parameter (optional) from the method signature in the Java API client, the only way is to remove the parameter from the Swagger/OpenAPI specification.

To add default headers, you can use the addDefaultHeader method in ApiClient: https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java#L528

UPDATE: Header parameters, similar to form, query parameters, are generated as method arguments. From the developer perspective, it's just another parameter (and they do not need to know whether the parameter is a header, form or query parameter)

UPDATE: On May 2018, about 50 top contributors and template creators of Swagger Codegen decided to fork Swagger Codegen to maintain a community-driven version called OpenAPI Generator. Please refer to the Q&A for more information.

Body:
I am using swagger-codegen for generating a Java REST client for one of my REST APIs. The REST APIs take an optional header parameter. The generated methods in the client have an additional parameter that takes the header. I would like the methods to be generated without the header parameter in the method signature.
I have read the documentation, but couldn't find any reference.

For example, for a GET all API with option X-CUSTOM-HEADER parameter, swagger-codegen generates a method like below:

public List<SomeType> findAllUsingGET1(String optionalHeader)

where as I would like it to be:

public List<SomeType> findAllUsingGET1()

Looking for pointers for the workaround rather than customizing the client-code generation.

EDIT 1: Adding the JSON spec

  "get": {
    "summary": "findAll",
    "operationId": "findAllUsingGET1",
    "consumes": [
      "application/json"
    ],
    "produces": [
      "application/json"
    ],
    "parameters": [
      {
        "name": "X-CUSTOM-HEADER",
        "in": "header",
        "description": "Custom Header",
        "required": false,
        "type": "string"
      }
    ],
    "responses": {
      "200": {
        "description": "OK",
        "schema": {
          "type": "string"
        }
      },
      "401": {
        "description": "Unauthorized"
      },
      "403": {
        "description": "Forbidden"
      },
      "404": {
        "description": "Not Found"
      }
    }
  }

ContentLicense: CC BY-SA 4.0


问:
how to add yyyy/MM date in drop down list in webforms c#
I'm new in c# webforms. I'm experimenting drop down list. I want to load the current year and  month, and it's two months ago months. I want to display YEAR and MONTH only.
example: date now - 2017 / 03. two months ago are - 2017 / 02 and 2017 / 01.

default.aspx:

```<code> <asp:DropDownList ID="ddlStartPeriod" runat="server"></asp:DropDownList>
</code>```

on my page_load in default.aspx.cs:

ddlStartPeriod.Items.Add(DateTime.Now.ToString("yyyy / MM"));

I don't know what's the next move and I don't how to subtract 2 months from DateTime.Now.ToString("yyyy / MM").

Thank you in advance!

答:
Simple just add dataTextFormatString attribute.

```<code><asp:DropDownList ID="ddlStartPeriod" runat="server" dataTextFormatString="{0:yyyy/MM}"></asp:DropDownList>
</code>```

OR

ddlStartPeriod.DataTextFormatString = "{0:yyyy/MM}";

more detail for date format so refer this.

Body:
I'm new in c# webforms. I'm experimenting drop down list. I want to load the current year and  month, and it's two months ago months. I want to display YEAR and MONTH only.
example: date now - 2017 / 03. two months ago are - 2017 / 02 and 2017 / 01.

default.aspx:

 <asp:DropDownList ID="ddlStartPeriod" runat="server"></asp:DropDownList>

on my page_load in default.aspx.cs:

ddlStartPeriod.Items.Add(DateTime.Now.ToString("yyyy / MM"));

I don't know what's the next move and I don't how to subtract 2 months from DateTime.Now.ToString("yyyy / MM").

Thank you in advance!

Body:
Simple just add dataTextFormatString attribute.

<asp:DropDownList ID="ddlStartPeriod" runat="server" dataTextFormatString="{0:yyyy/MM}"></asp:DropDownList>

OR

ddlStartPeriod.DataTextFormatString = "{0:yyyy/MM}";

more detail for date format so refer this.


问:
Xcode / Swift default files at installation - iOS
I need to add some "default" file during the installation or the first launch of my app in the "Document" directory to let user access to "demo" files or presets. Is there a way to do it properly ?
It's mostly for iOS Apps.</p>

答:
It's very straightforward to get to the app's Documents directory:

```<code>func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}
</code>```

Using the above function, you would be able to easily refer to the Documents folder to install files (or a folder containing your demo files) into the Documents directory and then read them out of there.

To copy a default file from your iOS application bundle, you could do something like:

```<code>let sourceURL = Bundle.main.url(forResource: "defaultfile", withExtension: ".png") // whatever kind of file it is
let destinationFolderURL = self.getDocumentsDirectory()
let fullDestURL = destinationFolderURL.appendingPathComponent("defaultfile.png")
let fileManager = FileManager.default

do{
    try fileManager.copyItem(at: sourceURL, to: destURL)
} catch {
    print(error)
}
</code>```

Hopefully I didn't make any typos in the above example.  :-)

Body:
It's very straightforward to get to the app's Documents directory:

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

Using the above function, you would be able to easily refer to the Documents folder to install files (or a folder containing your demo files) into the Documents directory and then read them out of there.

To copy a default file from your iOS application bundle, you could do something like:

let sourceURL = Bundle.main.url(forResource: "defaultfile", withExtension: ".png") // whatever kind of file it is
let destinationFolderURL = self.getDocumentsDirectory()
let fullDestURL = destinationFolderURL.appendingPathComponent("defaultfile.png")
let fileManager = FileManager.default

do{
    try fileManager.copyItem(at: sourceURL, to: destURL)
} catch {
    print(error)
}

Hopefully I didn't make any typos in the above example.  :-)


问:
How to use template variable in a template tag in Django?
I have a custom template tag called cg

```<code>{% cg %}
</code>```

and I hava a varialbe {{ status }}

I need to wrap the result of {{ status }} inside a <special></special> HTML tag, and then pass into {%cg  %}, how to write this code in django template?

答: "Passing template variables to the tag"</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a custom template tag called cg

{% cg %}

and I hava a varialbe {{ status }}

I need to wrap the result of {{ status }} inside a <special></special> HTML tag, and then pass into {%cg  %}, how to write this code in django template?

Body: "Passing template variables to the tag"


问:
how does selenium web driver work in javascript?
I am trying to scrap a website so I use selenium-webdriver.
I've chosen javascript and nodejs as language to teach myself.
The following is a very basic code to understand the behaviour of the tool.

I launch it with the following command line :
    node  --debug-brk=5858 src/app.js

```<code> var chromedriver = require('chromedriver');

 var webdriver = require('selenium-webdriver'),
        By = webdriver.By,
        until = webdriver.until;

    var driver = new webdriver.Builder()
        .forBrowser('chrome')
        .build();

    driver.get('http://www.google.com/ncr');
    debugger;
    driver.findElement(By.name('q')).sendKeys('webdriver');
    driver.findElement(By.name('btnG')).click();
    driver.wait(until.titleIs('webdriver - Google Search'), 1000);
    driver.quit();
</code>```

I am using vscode as IDE.
When I press F5, after setting a breakpoint in the code, the breakpoint is hit BUT no browser is opened yet. I click on resume (in VScode), the script finishes, and only then the browser is launched and corresponding commands are executed, my breakpoint being now ignored since it has already been hit.

This has the following consequence : I cannot step by step the selenium webdriver and thus am unable to evaluate the content of a find elements with xpath command.

I am missing Something but fail to see what.
Do I have to add Sleep statements ?

I've seen most people use java but I'd rather stick to javascript if possible.

答:
There are a couple of issues that I can see in your program.

When using javascript to program webdriver, an important concept is that all function calls are asynchronous and return a Thenable or Promise. So you cannot write line by line like in sequential programming.

You need to work this way:

```<code>driver.findElement(By.name('q')).sendKeys('webdriver')
    .then( function(){
        driver.findElement(By.name('btnG')).click();
        ...
    });
</code>```

See WebDriver's javascript API Documentation here:
https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index.html

In terms of debugging, if you pause in the browser's developer tool and trace there, what you trace is the website program that you are trying to scrape, but not your webdriver program. I use WebStorm to trace my webdriver program.

Body:
I am trying to scrap a website so I use selenium-webdriver.
I've chosen javascript and nodejs as language to teach myself.
The following is a very basic code to understand the behaviour of the tool.

I launch it with the following command line :
    node  --debug-brk=5858 src/app.js

 var chromedriver = require('chromedriver');

 var webdriver = require('selenium-webdriver'),
        By = webdriver.By,
        until = webdriver.until;

    var driver = new webdriver.Builder()
        .forBrowser('chrome')
        .build();

    driver.get('http://www.google.com/ncr');
    debugger;
    driver.findElement(By.name('q')).sendKeys('webdriver');
    driver.findElement(By.name('btnG')).click();
    driver.wait(until.titleIs('webdriver - Google Search'), 1000);
    driver.quit();

I am using vscode as IDE.
When I press F5, after setting a breakpoint in the code, the breakpoint is hit BUT no browser is opened yet. I click on resume (in VScode), the script finishes, and only then the browser is launched and corresponding commands are executed, my breakpoint being now ignored since it has already been hit.

This has the following consequence : I cannot step by step the selenium webdriver and thus am unable to evaluate the content of a find elements with xpath command.

I am missing Something but fail to see what.
Do I have to add Sleep statements ?

I've seen most people use java but I'd rather stick to javascript if possible.

Body:
There are a couple of issues that I can see in your program.

When using javascript to program webdriver, an important concept is that all function calls are asynchronous and return a Thenable or Promise. So you cannot write line by line like in sequential programming.

You need to work this way:

driver.findElement(By.name('q')).sendKeys('webdriver')
    .then( function(){
        driver.findElement(By.name('btnG')).click();
        ...
    });

See WebDriver's javascript API Documentation here:
https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index.html

In terms of debugging, if you pause in the browser's developer tool and trace there, what you trace is the website program that you are trying to scrape, but not your webdriver program. I use WebStorm to trace my webdriver program.


问:
Android studio: how to properly use the support library AppCompat?
I know there are many versions such as v4, v7, v8, v13, v14, v17, etc and they aren't in order of upgrades. What I don't understand is the meaning of this checkbox in Android Studio when you create a new project and choose an empty activity

Backwards compatibility (AppCompat)

The description says

if false, this activity will be Activity instead of AppCompatActivity

It's a bit foggy to me, then I checked the library and I found out that it was  android.support.v7.app.AppCompatActivity

The descriptions says that

v7 Support Libraries
  There are several libraries designed to be used with Android 2.3 (API level 9) and higher.

Again I don't understand whether I have to use it or not, depending on different cases. If I set the maximum target API, what is the necessary minSdk to not use it?

答:
Please note that, when you opt out support libraries, you can not get benefit of the powerful RecyeclerView, CardView, DesignSupportLib etc. Because these libs are dependent on appCompat

what version should we use in order to avoid the support library?

You can use any version as min sdk version. It does not matter. Support lib is included in every project by default by android studio, you have to remove it manually.

How to create new project without support library?

While creating a new project,set min sdk version as 14 (just for example), don't add
any activities during the wizard dialog. Just create a project with
no activities. Then after you can add code as you wish

You can remove the support library , removing the dependency from your build.gradle

```<code> dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    //compile 'com.android.support:appcompat-v7:25.2.0'
}
</code>```

Replace your theme parent in styles.xml into a non AppCompat version like Holo.Light

Body:
Please note that, when you opt out support libraries, you can not get benefit of the powerful RecyeclerView, CardView, DesignSupportLib etc. Because these libs are dependent on appCompat

what version should we use in order to avoid the support library?

You can use any version as min sdk version. It does not matter. Support lib is included in every project by default by android studio, you have to remove it manually.

How to create new project without support library?

While creating a new project,set min sdk version as 14 (just for example), don't add
any activities during the wizard dialog. Just create a project with
no activities. Then after you can add code as you wish

You can remove the support library , removing the dependency from your build.gradle

 dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    //compile 'com.android.support:appcompat-v7:25.2.0'
}

Replace your theme parent in styles.xml into a non AppCompat version like Holo.Light


问:
Failed to load ressource (Node js)
I'm working on a project with Node js (Express...). I'll try to explain my problem as clear as I can

I work on localhost, and the home page of my index.html allows us to click on buttons which redirect us to other pages.
I found a little game which I would like to put in my project. So I created a button which is supposed to redirect us to the game's html file. (pong.html). And in pong.html, i have a HTML tag  :

```<code><script type="text/javascript" src="pong.js"></script>
</code>```

which is supposed to load the script pong.js and execute it on my page. But I have an error :

"Failed to load resource: the server responded with a status of 404 (Not Found)"

pong.html is in a "public" folder ; and pong.js is at the root of my project. I don't know if the error comes from a bad redirection in the script tag or in the use of one Nodejs function...
If it can help : the first thing my "pong.js" does after variable declarations is :

```<code>app.use(express.static(path.join(__dirname,"public")));
</code>```

Thanks by advance!

答:
```<code>app.use(express.static(path.join(__dirname,"public")));
</code>```

make public folder static which means localhost:3000/:filenaame can be accessed if file is in that static folder

so for accessing pong.js localhost:3000/pong.js should be address and it should be in static folder

For Eg :
create pong folder with html and js in public

open localhsot:3000/pong/pong.html it will work then

Title: Failed to load ressource (Node js)

Body:
I'm working on a project with Node js (Express...). I'll try to explain my problem as clear as I can

I work on localhost, and the home page of my index.html allows us to click on buttons which redirect us to other pages.
I found a little game which I would like to put in my project. So I created a button which is supposed to redirect us to the game's html file. (pong.html). And in pong.html, i have a HTML tag  :

which is supposed to load the script pong.js and execute it on my page. But I have an error :

"Failed to load resource: the server responded with a status of 404 (Not Found)"

pong.html is in a "public" folder ; and pong.js is at the root of my project. I don't know if the error comes from a bad redirection in the script tag or in the use of one Nodejs function...
If it can help : the first thing my "pong.js" does after variable declarations is :

app.use(express.static(path.join(__dirname,"public")));

Thanks by advance!

Body:
app.use(express.static(path.join(__dirname,"public")));

make public folder static which means localhost:3000/:filenaame can be accessed if file is in that static folder

so for accessing pong.js localhost:3000/pong.js should be address and it should be in static folder

For Eg :
create pong folder with html and js in public

open localhsot:3000/pong/pong.html it will work then


问:
How to add Firebase into android
I want added Firebase into my application. I write below codes, but when running application I can't see TOKEN in log!

My dependencies :

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

Manifest :

```<code><application>
...
        <!--Firebase service-->
        <service android:name=".CloudMSG.MyFirebaseInctanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

    </application>
</code>```

MyFirebaseInctanceIdService :

```<code>public class MyFirebaseInctanceIdService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseInctance";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d("MyFirebaseInctance", "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        //sendRegistrationToServer(refreshedToken);
    }
}
</code>```

Logs:

```<code>03-30 13:36:42.943 9487-9487/? I/art: Late-enabling -Xcheck:jni
03-30 13:36:43.218 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
03-30 13:36:43.269 9487-9487/com.example.mohammad.a1_firebase W/InstanceID/Rpc: Found 10004
03-30 13:36:43.298 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: App measurement is starting up, version: 10084
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: Debug-level message logging enabled
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: AppMeasurement singleton hash: 720240273
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: Collection enabled
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: App package, google app id: com.example.mohammad.a1_firebase, 1:685652680518:android:0280a3bc1c6da8cb
03-30 13:36:43.405 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable faster debug mode event logging run:
                                                                      adb shell setprop debug.firebase.analytics.app com.example.mohammad.a1_firebase
03-30 13:36:43.463 9487-9487/com.example.mohammad.a1_firebase V/FA: Registered activity lifecycle callback
03-30 13:36:43.465 9487-9487/com.example.mohammad.a1_firebase I/FirebaseInitProvider: FirebaseApp initialization successful
03-30 13:36:43.467 9487-9487/com.example.mohammad.a1_firebase I/InstantRun: Starting Instant Run Server for com.example.mohammad.a1_firebase
03-30 13:36:43.471 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.489 9487-9587/com.example.mohammad.a1_firebase V/FA: Connecting to remote service
03-30 13:36:43.528 9487-9587/com.example.mohammad.a1_firebase W/GooglePlayServicesUtil: Google Play services out of date.  Requires 10084000 but found 6599430
03-30 13:36:43.612 9487-9487/com.example.mohammad.a1_firebase D/ContextHelper: convertTheme. context->name=com.example.mohammad.a1_firebase themeResourceId=2131230883
03-30 13:36:43.656 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
03-30 13:36:43.690 9487-9487/com.example.mohammad.a1_firebase V/FA: onActivityCreated
03-30 13:36:43.696 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [generateLayout] setColorNavigationBar => color=0x ff000001
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase D/PhoneWindowEx: [PWEx][generateLayout] setNavigationBarColor2 : colors=0xfff5f5f5
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [setNavigationBarColor2] color=0x fff5f5f5
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Connection attempt already in progress
03-30 13:36:43.864 9487-9587/com.example.mohammad.a1_firebase V/FA: Activity resumed, time: 1436094125
03-30 13:36:43.879 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Render dirty regions requested: true
03-30 13:36:43.881 9487-9612/com.example.mohammad.a1_firebase I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013_msm8974_LA.BF.1.1.1_RB1__release_AU ()
                                                                            OpenGL ES Shader Compiler Version: E031.25.03.00
                                                                            Build Date: 01/21/15 Wed
                                                                            Local Branch: mybranch7061829
                                                                            Remote Branch: quic/LA.BF.1.1.1_rb1.7
                                                                            Local Patches: NONE
                                                                            Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013 +  NOTHING
03-30 13:36:43.882 9487-9612/com.example.mohammad.a1_firebase I/OpenGLRenderer: Initialized EGL, version 1.4
03-30 13:36:43.910 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Enabling debug mode 0
03-30 13:36:43.916 9487-9487/com.example.mohammad.a1_firebase D/Atlas: Validating map...
03-30 13:36:43.927 9487-9487/com.example.mohammad.a1_firebase W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
03-30 13:36:43.936 9487-9592/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 30s
03-30 13:36:44.008 9487-9502/com.example.mohammad.a1_firebase W/art: Suspending all threads took: 5.068ms
03-30 13:36:44.047 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-30 13:36:44.183 9487-9487/com.example.mohammad.a1_firebase I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@755dbad time:128236912
03-30 13:37:14.017 9487-10051/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 60s
</code>```

How can I fix this issue and show Firebase token in logs?

答:
Firebase onTokenRefresh() will only be called if your token changes. Before that you should invoke

```<code>FirebaseInstanceId.getInstance().getToken()
</code>```

in your initial activity (like MainActivity) maybe.

Title: How to add Firebase into android

Body:
I want added Firebase into my application. I write below codes, but when running application I can't see TOKEN in log!

My dependencies :

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

Manifest :

<application>
...

        <service android:name=".CloudMSG.MyFirebaseInctanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

    </application>

MyFirebaseInctanceIdService :

public class MyFirebaseInctanceIdService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseInctance";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d("MyFirebaseInctance", "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        //sendRegistrationToServer(refreshedToken);
    }
}

Logs:

03-30 13:36:42.943 9487-9487/? I/art: Late-enabling -Xcheck:jni
03-30 13:36:43.218 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
03-30 13:36:43.269 9487-9487/com.example.mohammad.a1_firebase W/InstanceID/Rpc: Found 10004
03-30 13:36:43.298 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: App measurement is starting up, version: 10084
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: Debug-level message logging enabled
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: AppMeasurement singleton hash: 720240273
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: Collection enabled
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: App package, google app id: com.example.mohammad.a1_firebase, 1:685652680518:android:0280a3bc1c6da8cb
03-30 13:36:43.405 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable faster debug mode event logging run:
                                                                      adb shell setprop debug.firebase.analytics.app com.example.mohammad.a1_firebase
03-30 13:36:43.463 9487-9487/com.example.mohammad.a1_firebase V/FA: Registered activity lifecycle callback
03-30 13:36:43.465 9487-9487/com.example.mohammad.a1_firebase I/FirebaseInitProvider: FirebaseApp initialization successful
03-30 13:36:43.467 9487-9487/com.example.mohammad.a1_firebase I/InstantRun: Starting Instant Run Server for com.example.mohammad.a1_firebase
03-30 13:36:43.471 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.489 9487-9587/com.example.mohammad.a1_firebase V/FA: Connecting to remote service
03-30 13:36:43.528 9487-9587/com.example.mohammad.a1_firebase W/GooglePlayServicesUtil: Google Play services out of date.  Requires 10084000 but found 6599430
03-30 13:36:43.612 9487-9487/com.example.mohammad.a1_firebase D/ContextHelper: convertTheme. context->name=com.example.mohammad.a1_firebase themeResourceId=2131230883
03-30 13:36:43.656 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
03-30 13:36:43.690 9487-9487/com.example.mohammad.a1_firebase V/FA: onActivityCreated
03-30 13:36:43.696 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [generateLayout] setColorNavigationBar => color=0x ff000001
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase D/PhoneWindowEx: [PWEx][generateLayout] setNavigationBarColor2 : colors=0xfff5f5f5
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [setNavigationBarColor2] color=0x fff5f5f5
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Connection attempt already in progress
03-30 13:36:43.864 9487-9587/com.example.mohammad.a1_firebase V/FA: Activity resumed, time: 1436094125
03-30 13:36:43.879 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Render dirty regions requested: true
03-30 13:36:43.881 9487-9612/com.example.mohammad.a1_firebase I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013_msm8974_LA.BF.1.1.1_RB1__release_AU ()
                                                                            OpenGL ES Shader Compiler Version: E031.25.03.00
                                                                            Build Date: 01/21/15 Wed
                                                                            Local Branch: mybranch7061829
                                                                            Remote Branch: quic/LA.BF.1.1.1_rb1.7
                                                                            Local Patches: NONE
                                                                            Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013 +  NOTHING
03-30 13:36:43.882 9487-9612/com.example.mohammad.a1_firebase I/OpenGLRenderer: Initialized EGL, version 1.4
03-30 13:36:43.910 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Enabling debug mode 0
03-30 13:36:43.916 9487-9487/com.example.mohammad.a1_firebase D/Atlas: Validating map...
03-30 13:36:43.927 9487-9487/com.example.mohammad.a1_firebase W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
03-30 13:36:43.936 9487-9592/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 30s
03-30 13:36:44.008 9487-9502/com.example.mohammad.a1_firebase W/art: Suspending all threads took: 5.068ms
03-30 13:36:44.047 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-30 13:36:44.183 9487-9487/com.example.mohammad.a1_firebase I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@755dbad time:128236912
03-30 13:37:14.017 9487-10051/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 60s

How can I fix this issue and show Firebase token in logs?

Body:
Firebase onTokenRefresh() will only be called if your token changes. Before that you should invoke

FirebaseInstanceId.getInstance().getToken()

in your initial activity (like MainActivity) maybe.


问:
Ruby on Rails database is not configured
We have 2 Ruby on Rails websites. Live and Beta. Recently we made a database move, so I was asked to try and update the database connections for the websites. I did that using the database.yml files for both.

Afterwards, the Live website works as expected, but the Beta throws up an error:

```<code> 'staging' database is not configured. Available: ["defaults", "production", "writeable"] (ActiveRecord::AdapterNotSpecified)
</code>```

My database.yml file:

```<code>defaults: &defaults
  adapter: mysql2
  host: eu-west-1.rds.amazonaws.com
  pool: 10
  reconnect: true
  encoding: utf8
  database: Project_database

production:
  <<: *defaults
  username: Username
  password: Password
  port: 3306

writeable:
  <<: *defaults
  username: Username
  password: Passowrd
  port: 3306
</code>```

How do I solve this, without effecting the Live website?

Ruby 2.3.0
Gems 4.2.6

答:
Just add this with appropriate username and password to database.yml file.
Might be helpful

```<code>staging:
  <<: *defaults
  username: Username
  password: Password
  port: 3306
</code>```

Body:
We have 2 Ruby on Rails websites. Live and Beta. Recently we made a database move, so I was asked to try and update the database connections for the websites. I did that using the database.yml files for both.

Afterwards, the Live website works as expected, but the Beta throws up an error:

 'staging' database is not configured. Available: ["defaults", "production", "writeable"] (ActiveRecord::AdapterNotSpecified)

My database.yml file:

defaults: &defaults
  adapter: mysql2
  host: eu-west-1.rds.amazonaws.com
  pool: 10
  reconnect: true
  encoding: utf8
  database: Project_database

production:
  <<: *defaults
  username: Username
  password: Password
  port: 3306

writeable:
  <<: *defaults
  username: Username
  password: Passowrd
  port: 3306

How do I solve this, without effecting the Live website?

Ruby 2.3.0
Gems 4.2.6

Body:
Just add this with appropriate username and password to database.yml file.
Might be helpful

staging:
  <<: *defaults
  username: Username
  password: Password
  port: 3306


问:
Load external nav and update links
I have been googling for an hour on this and thought I would see if someone had a quick answer.

I have a site running on a hosted cms and have just created a wordpress blog running on a subdomain on a new server. I do not have access to source code of hosted (business catalyst) CMS.

I would like to load the CMS navigation in to my wordpress theme and was considering using jQuery but ajax seems to have a same domain policy for loading content. From what I have read so far the way around this is with a php proxy loading the external content. Without diving in to this I can see there being a problem with the navigation links having relative urls to the original domain so they will not work on blog.domain.com. I do not want to have to create redirects for all of the possible urls on the new server as the CMS navigation will be updating regularly.

How can I load the navigation contents using php to create the proxy but automatically change the relative url's to absolute urls to the original domain? + there will be one url in the navigation that will need to stay the same and that is the one pointing to the subdomain blog.domain.com

Thanks in advance for your help.

答:
Ok, I'm going to answer my own questions (s) in case someone else runs in to the same scenario.

Simple HTML DOM Library will let you parse the navigation by targeting the div id:

http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-html-dom-library/

You can then parse your navigation directly in to your php template:

```<code><?php
include_once('simple_html_dom.php');

$html = file_get_html('http://www.domain.com/');

foreach($html->find('div#cat_514340_divs') as $e)
    echo $e->innertext;

?>
</code>```

And add absolute urls to each href with jQuery:

```<code>jQuery(document).ready(function($) {
/* Add absolute urls to top navigation */
  $('#nav a').each(function() {
    var href = $(this).attr('href');
    $(this).attr('href', 'http://www.originalsitedomain.com' + href);
  });
});
</code>```

Title: Load external nav and update links

Body:
Ok, I'm going to answer my own questions (s) in case someone else runs in to the same scenario.

Simple HTML DOM Library will let you parse the navigation by targeting the div id:

http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-html-dom-library/

You can then parse your navigation directly in to your php template:

<?php
include_once('simple_html_dom.php');

$html = file_get_html('http://www.domain.com/');

foreach($html->find('div#cat_514340_divs') as $e)
    echo $e->innertext;

?>

And add absolute urls to each href with jQuery:

jQuery(document).ready(function($) {
/* Add absolute urls to top navigation */
  $('#nav a').each(function() {
    var href = $(this).attr('href');
    $(this).attr('href', 'http://www.originalsitedomain.com' + href);
  });
});


问:
How to hide specific fields which are extracted via populate query
My schemas are as follows:

order.js

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var foodtruck = require('./foodtruck.js');
var payment = require('./payment.js');
var Items = require('./items.js');

var order = new Schema({
    order_status:Number,   //0 place 1 accepted 2 cooked 3 cancelled
    foodtruck_id:{type:Schema.Types.ObjectId,ref: 'foodtruck'},
    customer_id:{type: Schema.Types.ObjectId,ref: 'user'},
    items:[{type : Schema.Types.ObjectId, ref : 'items'}],
    user_type:Boolean,
    order_time:Date,
    order_rating:{type:Number,default:5.0},
    order_issue_comments:String,
    order_special_instruction:String,
    order_total:Number,
    order_location:String,
    order_coupon_code:String,
    payment_id:{type:Schema.Types.ObjectId,ref:'payment'}
},{ versionKey: false });

module.exports = mongoose.model('order',order);
</code>```

foodtruck.js

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Items = require('./items.js');

var FoodTruckSchema = new Schema({
    foodtruck_name:String,
    foodtruck_location:String,
    foodtruck_rating:{type:Number,default:5},
    foodtruck_total_votes:{type:Number,default:0},
    foodtruck_tag:String,
    foodtruck_open_status:{type:Number,default:1},   //0 open 1 closed
    foodtruck_starting_timing:String,
    foodtruck_closing_timing:String,
    foodtruck_cusine:String,
    foodtruck_img:String,
    foodtruck_logo:String,
    item_list: [ {type : mongoose.Schema.ObjectId, ref : 'items'}]
},{ versionKey: false });

module.exports = mongoose.model('foodtruck',FoodTruckSchema);
</code>```

items.js

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
    no_of_times_ordered:Number,
    item_name:String,
    item_tag:String,
    item_category:String,
    item_illustrations:[String],
    item_stock:Number,   //0 available 1 last 5 items 2 not available
    item_quantity_ordered:{type:Number,default:0},
    item_discount_price:Number,
    item_price:Number,
    item_img:String,
    no_of_likes:{type:Number,default:0}
},{ versionKey: false });

module.exports = mongoose.model('items',ItemSchema);
</code>```

Now my query is as shown below:

```<code>var getOrderList = function(req, res) {
    var foodtruck_id = req.body.foodtruck_id;
    if ((foodtruck_id) && (foodtruck_id.trim() != '')) {
        order.find({
            'foodtruck_id': foodtruck_id.trim()
        }).populate('foodtruck_id').populate('customer_id').populate('items').exec(function(err, orderList) {
            if (err) res.json({
                status: '500',
                message: 'There was no order found'
            });
            else {
                res.json({
                    status: '200',
                    message: 'Order list',
                    data: orderList
                });
            }
        });
    } else {
        res.json({
            status: '404',
            message: 'Please enter valid id'
        });
    }
};
</code>```

The response is as show below:

Now, what happens is when I put populate query for "foodtruck_id", it also shows item_list attached with it. Is there any way through which I can hide item_list field while populating foodtruck_id query?

答:
1.
You can use '-' to exclude a key after populate.

```<code>.populate({path:foodtruck_id,select:'-item_list')
</code>```

If you want to select any specific key example you only want foodtruck_name .
You can do this way

.populate({path:foodtruck_id,select:'foodtruck_name')

to read more about populate you can visit mongoose doc

Body:
My schemas are as follows:

order.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var foodtruck = require('./foodtruck.js');
var payment = require('./payment.js');
var Items = require('./items.js');

var order = new Schema({
    order_status:Number,   //0 place 1 accepted 2 cooked 3 cancelled
    foodtruck_id:{type:Schema.Types.ObjectId,ref: 'foodtruck'},
    customer_id:{type: Schema.Types.ObjectId,ref: 'user'},
    items:[{type : Schema.Types.ObjectId, ref : 'items'}],
    user_type:Boolean,
    order_time:Date,
    order_rating:{type:Number,default:5.0},
    order_issue_comments:String,
    order_special_instruction:String,
    order_total:Number,
    order_location:String,
    order_coupon_code:String,
    payment_id:{type:Schema.Types.ObjectId,ref:'payment'}
},{ versionKey: false });

module.exports = mongoose.model('order',order);

foodtruck.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Items = require('./items.js');

var FoodTruckSchema = new Schema({
    foodtruck_name:String,
    foodtruck_location:String,
    foodtruck_rating:{type:Number,default:5},
    foodtruck_total_votes:{type:Number,default:0},
    foodtruck_tag:String,
    foodtruck_open_status:{type:Number,default:1},   //0 open 1 closed
    foodtruck_starting_timing:String,
    foodtruck_closing_timing:String,
    foodtruck_cusine:String,
    foodtruck_img:String,
    foodtruck_logo:String,
    item_list: [ {type : mongoose.Schema.ObjectId, ref : 'items'}]
},{ versionKey: false });

module.exports = mongoose.model('foodtruck',FoodTruckSchema);

items.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
    no_of_times_ordered:Number,
    item_name:String,
    item_tag:String,
    item_category:String,
    item_illustrations:[String],
    item_stock:Number,   //0 available 1 last 5 items 2 not available
    item_quantity_ordered:{type:Number,default:0},
    item_discount_price:Number,
    item_price:Number,
    item_img:String,
    no_of_likes:{type:Number,default:0}
},{ versionKey: false });

module.exports = mongoose.model('items',ItemSchema);

Now my query is as shown below:

var getOrderList = function(req, res) {
    var foodtruck_id = req.body.foodtruck_id;
    if ((foodtruck_id) && (foodtruck_id.trim() != '')) {
        order.find({
            'foodtruck_id': foodtruck_id.trim()
        }).populate('foodtruck_id').populate('customer_id').populate('items').exec(function(err, orderList) {
            if (err) res.json({
                status: '500',
                message: 'There was no order found'
            });
            else {
                res.json({
                    status: '200',
                    message: 'Order list',
                    data: orderList
                });
            }
        });
    } else {
        res.json({
            status: '404',
            message: 'Please enter valid id'
        });
    }
};

The response is as show below:

Now, what happens is when I put populate query for "foodtruck_id", it also shows item_list attached with it. Is there any way through which I can hide item_list field while populating foodtruck_id query?

Body:
1.
You can use '-' to exclude a key after populate.

.populate({path:foodtruck_id,select:'-item_list')

If you want to select any specific key example you only want foodtruck_name .
You can do this way

.populate({path:foodtruck_id,select:'foodtruck_name')

to read more about populate you can visit mongoose doc


问:
Typescript : require statement not part of an import statement
Typescript version 2.2.2

I wrote this require in my UserRoutzr.ts

```<code>const users = <IUser[]> require(path.join(process.cwd() + "/data"));
</code>```

TSLint is raising the following warning:

```<code>require statement not part of an import statement
</code>```

if I changed it to :

```<code>import users = <IUser[]> require(path.join(process.cwd() + "/data"));
</code>```

Then it's raising an error :

```<code>TS1003 Identifier expected
</code>```

How should I rewrite this require ?
thanks for feedback

答:
may be you need dynamic module loading, and the code like this:</p>

```<code>import {IUser} from './lib/user';
const users:IUser[] = require(path.join(process.cwd() + "/data"));
</code>```

Body:
Typescript version 2.2.2

I wrote this require in my UserRoutzr.ts

const users = <IUser[]> require(path.join(process.cwd() + "/data"));

TSLint is raising the following warning:

require statement not part of an import statement

if I changed it to :

import users = <IUser[]> require(path.join(process.cwd() + "/data"));

Then it's raising an error :

TS1003 Identifier expected

How should I rewrite this require ?
thanks for feedback

Body:
may be you need dynamic module loading, and the code like this:

import {IUser} from './lib/user';
const users:IUser[] = require(path.join(process.cwd() + "/data"));


问:
How to store critically sensitive information such as secret, key, token, encryptionKey in iOS application
When we talk about securing iOS application we often forget to secure most critically sensitive information such as secret, key, token, encryptionKey.  This information is stored in iOS binary. So none of your server side security protocol will help you.

There are lots of suggestion that we should not store such information in the app but store in the server and get it via SSL secured web service call. But this is not possible for all application. E.g. if my application does not need web service at all.

In iOS app we have following option to store information.

UserDefault: Not appropriate for this case

String Constant: Not appropriate for this case. Can be reverse
engineer to retrieve or just use strings command

Secure Database: Store in Secure and encrypted Database. But again have responsibility to secure database username and password.

KeyChain: Best to store critical info. But we cannot save information before installing the app. To store in the keychain, we first need to open the app, read from some source and store in the keychain. Not appropriate for our case either.

Custom Hash String Constant: Not to directly use secret, token, key from service provider (mixpanel, paypal), instead use hash version of that information from custom key. This is also not perfect solution. But add complexity during hacking.

Kindly send some awsome solution to this problem.

答:
1) Internet Connection Required

1.1) Push Notifications
Great way to have a secure data exchange could be to use (silent) push services from Apple, those use the apns and send data through https - more Details 3.1

1.2)
A more or less similar approach is also used when distributing new user certificates to already deployed applications, if a reinstall of the application is no opportunity AND the application requires a working internet connection anyway.

Downside: working network connection required and basically the information is coming to the application, when it is already being executed => seems not to be appropriate for your case. (see step 4)

2) Static data (as there will be no exchange without network connection / communication partner)

Encryption of data with private key being provided in the bundle itself. Whether it is now a string or a hash, which can be reverse engineered with functions you got emebedded in your application.
Since iOS9 it is pretty hard to decompile iOS applications and basically you will mainly have a look into the provided header-files. So if you had such a function, string, hash value or whatever, make sure you got it in your .m-file!

But again: if the information is not device or user specific, just a secret across your own micro environment, valid across all devices, you would have to provide the encrypted data AND the decryption method in the same bundle, if there is no update process / information exchange or something else, you can think of.

Good for encryption:
iOS System.Security https://developer.apple.com/reference/security
or simply openssl

The difference between your described keychain approach is:
You got a value, which WILL be encrypted and stored securely.
(2) describes the approach to have an encrypted and stored (in bundle) semi secure value, which WILL be decrypted

3) Information exchange

You describe critical data, which was hashed by another instance. Great! - Make sure, relly make sure, the instance you are talking to is really the instance you expect to be (Network Hooking prevention with ssl certificate pinning etc, but even here you might have intruder (men-in-the-middle)). And you will (probably) have a certificate being provided in your application bundle, to ensure the authenticity of the communication server - here you go again, data that is supposed to ensure a secure process between certain instances of your micro environment. Nevertheless, this data is being provided in your application's bundle.

3.1 Secure Information Exchange extended - Silent Push
Make use of Apple's servers to exchange your secrets for this purpose. If you just need to exchange small data chunks. I would recommend to use silent push notifications to the user, those do even work without explicit permission from the user. Huge advantage: In case your secrets or keys change, you can inform users as soon as possible about the change. They will likely only need the change, when they receive new data, which should reliably work in most cases. Exception: Data exchange in local networks or via bluetooth, in this case I would recommend to provide a notification to the user to have the requirement to update a local decryption key. Or exchange the key in this format as well. Once again: I am leaking some detailed information about your environment architecture.
Downside: You don't know, whether a user just used your app for the first time, until the user "tells" you so.
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW1

3.1 Secure Information Exchange extended - In App Purchase
Use a frree In-App Purchase for the user to get the data to your phone. Good point here: you can provide larger data chunks easily, as this should be an active request by the user, the user does expect certain processing time and should also be aware of the fact to require a working internet connection.
Downside: User would have to select this on purpose. Up until then the app would not work accordinly.
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Introduction.html#//apple_ref/doc/uid/TP40008267

So, it just slightly differs from the approach (2) in its basic idea.

In short: Can you provide additional information, what kind of data you need to encrypt/want to store securely and whether you will have a network exchange or not?

Would need some more information here :-)

I would like to emphasize once again that an application on iOS is not that easy to decrypt anymore, even decompiling would not get everything, you expect it to get. For instance decryption tools like dumpdecrypt were only working properly up until iOS 8.4


答:
Obj-C solution for anyone interested

If you want user to just read/view those files, all you need to do is to drag&drop them to your project files in Xcode, and then you can access them programmatically like this:

```<code>[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"relative/path/to/your/files"]
</code>```

Alternatively, if you want your users to modify/re-save those files, you'll need to copy-paste them from your NSBundle to Documents directory on the first launch.

```<code>- (void)copyDemoFilesToDocumentsFolder {
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *demoFilesPath = [DOCUMENTS_DIR stringByAppendingPathComponent:@"path/to/your/demo/files"];

    if (![fileManager fileExistsAtPath:demoFilesPath]) {
        NSString *sourceFolderPath = [[[NSBundle mainBundle] bundlePath]
                                  stringByAppendingPathComponent:@"path/to/your/demo/files"];

    [fileManager copyItemAtPath:sourceFolderPath
                         toPath:demoFilesPath
                          error:&error];
    }
}
</code>```

Title: Xcode / Swift default files at installation - iOS

Body:
I need to add some "default" file during the installation or the first launch of my app in the "Document" directory to let user access to "demo" files or presets. Is there a way to do it properly ?
It's mostly for iOS Apps.

Body:
Obj-C solution for anyone interested

If you want user to just read/view those files, all you need to do is to drag&drop them to your project files in Xcode, and then you can access them programmatically like this:

[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"relative/path/to/your/files"]

Alternatively, if you want your users to modify/re-save those files, you'll need to copy-paste them from your NSBundle to Documents directory on the first launch.

- (void)copyDemoFilesToDocumentsFolder {
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *demoFilesPath = [DOCUMENTS_DIR stringByAppendingPathComponent:@"path/to/your/demo/files"];

    if (![fileManager fileExistsAtPath:demoFilesPath]) {
        NSString *sourceFolderPath = [[[NSBundle mainBundle] bundlePath]
                                  stringByAppendingPathComponent:@"path/to/your/demo/files"];

    [fileManager copyItemAtPath:sourceFolderPath
                         toPath:demoFilesPath
                          error:&error];
    }
}


问:
How do you do an include in applescript?
I have a bunch of code I want to to use in several different applescripts so I would like to put it into it's own applescript that I can reference from other applescripts.  Basically I want to do an include.  How is this done in applescript?</p>

答:
Here is the best way I have found to accomplish this. You can call a function on another script like so:

script a.scpt

```<code>set myScript to load script "b.scpt"
set foo to myScript's theTest()
</code>```

script b.scpt

```<code>on theTest()
       return true
end theTest
</code>```

As you can see you can call functions within b.scpt from a.scpt by calling the function name myScript's theTest().

Body:
Here is the best way I have found to accomplish this. You can call a function on another script like so:

script a.scpt

set myScript to load script "b.scpt"
set foo to myScript's theTest()

script b.scpt

on theTest()
       return true
end theTest

As you can see you can call functions within b.scpt from a.scpt by calling the function name myScript's theTest().


问:
Loading not responding in Android
Can anyone help me to fix the Loading harmful and not responding in Android App? I'm a newbie in Android and I have to do my project and which have bug with Android OS 6.

The app show the group persons on the map and when click on Contact icon, then show the group person lists.

For now, on other OS below OS 6 are working fine and in OS 6 when change to group which have friends or Members, then click on Contact, the loading was stuck and Not responding alert show up. I don't know why.

But on the group which have no members or friends have working fine. I'll show you with the screenshot below.

The Image One is no Members and Friends in the Group (Group Name was Test1).

https://drive.google.com/file/d/0BwG4MW1kR1WMSGNHYXNENzVGVUE/view

The Image Two is Choose the Non Member Group and Click on Contact Icon, the list was only me show up.(Work fine with no member in group).

https://drive.google.com/file/d/0BwG4MW1kR1WMcXc5NDc0c09nRXc/view

The Image Three was chosen the Group which have Members or Friends.(The Group name was tt.) The Location pointer was show up in Map.

https://drive.google.com/file/d/0BwG4MW1kR1WMbEdHZUs2NGZPYW8/view

The Image Four is Choose the group which have Members and Click on the Contact Icon, Then the bug was show up. (The loading icon was stuck and after a few seconds or minutes then no responding alert will show up).

https://drive.google.com/file/d/0BwG4MW1kR1WMbF94cjQySkJhSDA/view

Here is LogCat screenshot (Honestly I don't understand how to fix after seeing LogCat) https://drive.google.com/file/d/0BwG4MW1kR1WMalRrN3psS0h2a28/view

```<code> @Override
protected View onCreateMainView(LayoutInflater inflater) {
    Log.d(TAG, "Start Up");
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        Log.d(TAG, "Start Up Condition");
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            Log.d(TAG, "Start Up SelfCheck");

            final AlertDialog.Builder builder = new AlertDialog.Builder(((MainActivity ) getActivity()));
            builder.setIcon(R.drawable.ico_info_popup_locator);
            builder.setTitle("Already accept location");
            builder.setMessage("Location was already accepted~!");
            builder.setPositiveButton(android.R.string.ok, null);

            builder.show();

        } else {

            final AlertDialog.Builder builder = new AlertDialog.Builder(((MainActivity ) getActivity()));
            builder.setIcon(R.drawable.ico_info_popup_locator);
            builder.setTitle("Location need to accept");
            builder.setMessage("Please Accept to use your location service~!");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
                }

                private void requestPermissions(String[] strings, int permissionRequestCoarseLocation) {
                    // TODO Auto-generated method stub

                }
            });
            builder.show();
        }
    }

    map_layout = inflater.inflate(R.layout.map_fragment, null, false);
    viewContaner = (RelativeLayout) map_layout.findViewById(R.id.viewContaner);
    viewContaner.setVisibility(View.INVISIBLE);

    mapZoomLevel =
            SharePreferencesUtil.getIntValue(ISharePreferencesDefine.KEY_STORE_LEVEL_ZOOM,
                    IConstants.LEVEL_ZOOM_MAP_DEFAULT);
    actionGetUser();
    LocationTracking.getInstance().setOnLocationChangedListener(this);
    initMap();

    return map_layout;
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    if (requestCode == MY_PERMISSIONS_REQUEST_LOCATION) {

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

           Log.d(TAG, "coarse location permission granted");

        } else {

            final AlertDialog.Builder builder = new AlertDialog.Builder(((MainActivity ) getActivity()));
            builder.setIcon(R.drawable.ico_info_popup_locator);
            builder.setTitle("Location need to accept");
            builder.setMessage("Please Accept to use your location service~!");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
                }

                private void requestPermissions(String[] strings, int permissionRequestCoarseLocation) {
                    // TODO Auto-generated method stub

                }
            });
            builder.show();
        }
    }
}
</code>```

答: But maybe you have problems with permissions. I think above android API Level 23 you get the permission for your app with permission requests while the app is running. But maybe you don't think for the older devices and you don't get the permissions for your app at installation with the Mainifest.XML. Maybe this is the thing why you loading stuck. Or you just use a syntax for new devices and old devices cannot resolve it.

Title: Loading not responding in Android

Body:
Can anyone help me to fix the Loading harmful and not responding in Android App? I'm a newbie in Android and I have to do my project and which have bug with Android OS 6.

The app show the group persons on the map and when click on Contact icon, then show the group person lists.

For now, on other OS below OS 6 are working fine and in OS 6 when change to group which have friends or Members, then click on Contact, the loading was stuck and Not responding alert show up. I don't know why.

But on the group which have no members or friends have working fine. I'll show you with the screenshot below.

The Image One is no Members and Friends in the Group (Group Name was Test1).

https://drive.google.com/file/d/0BwG4MW1kR1WMSGNHYXNENzVGVUE/view

The Image Two is Choose the Non Member Group and Click on Contact Icon, the list was only me show up.(Work fine with no member in group).

https://drive.google.com/file/d/0BwG4MW1kR1WMcXc5NDc0c09nRXc/view

The Image Three was chosen the Group which have Members or Friends.(The Group name was tt.) The Location pointer was show up in Map.

https://drive.google.com/file/d/0BwG4MW1kR1WMbEdHZUs2NGZPYW8/view

The Image Four is Choose the group which have Members and Click on the Contact Icon, Then the bug was show up. (The loading icon was stuck and after a few seconds or minutes then no responding alert will show up).

https://drive.google.com/file/d/0BwG4MW1kR1WMbF94cjQySkJhSDA/view

Here is LogCat screenshot (Honestly I don't understand how to fix after seeing LogCat) https://drive.google.com/file/d/0BwG4MW1kR1WMalRrN3psS0h2a28/view

 @Override
protected View onCreateMainView(LayoutInflater inflater) {
    Log.d(TAG, "Start Up");
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        Log.d(TAG, "Start Up Condition");
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            Log.d(TAG, "Start Up SelfCheck");

            final AlertDialog.Builder builder = new AlertDialog.Builder(((MainActivity ) getActivity()));
            builder.setIcon(R.drawable.ico_info_popup_locator);
            builder.setTitle("Already accept location");
            builder.setMessage("Location was already accepted~!");
            builder.setPositiveButton(android.R.string.ok, null);

            builder.show();

        } else {

            final AlertDialog.Builder builder = new AlertDialog.Builder(((MainActivity ) getActivity()));
            builder.setIcon(R.drawable.ico_info_popup_locator);
            builder.setTitle("Location need to accept");
            builder.setMessage("Please Accept to use your location service~!");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
                }

                private void requestPermissions(String[] strings, int permissionRequestCoarseLocation) {
                    // TODO Auto-generated method stub

                }
            });
            builder.show();
        }
    }

    map_layout = inflater.inflate(R.layout.map_fragment, null, false);
    viewContaner = (RelativeLayout) map_layout.findViewById(R.id.viewContaner);
    viewContaner.setVisibility(View.INVISIBLE);

    mapZoomLevel =
            SharePreferencesUtil.getIntValue(ISharePreferencesDefine.KEY_STORE_LEVEL_ZOOM,
                    IConstants.LEVEL_ZOOM_MAP_DEFAULT);
    actionGetUser();
    LocationTracking.getInstance().setOnLocationChangedListener(this);
    initMap();

    return map_layout;
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    if (requestCode == MY_PERMISSIONS_REQUEST_LOCATION) {

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

           Log.d(TAG, "coarse location permission granted");

        } else {

            final AlertDialog.Builder builder = new AlertDialog.Builder(((MainActivity ) getActivity()));
            builder.setIcon(R.drawable.ico_info_popup_locator);
            builder.setTitle("Location need to accept");
            builder.setMessage("Please Accept to use your location service~!");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
                }

                private void requestPermissions(String[] strings, int permissionRequestCoarseLocation) {
                    // TODO Auto-generated method stub

                }
            });
            builder.show();
        }
    }
}


问:
Vim's Omnicompletion with Python just doesn't work
I've searched around for an hour, both on Stack Overflow and elsewhere. Alas! Please help. Vim's omnicompletion just doesn't work.

I have Vim 7.2 compiled with Python support.

filetype plugin on is in my .vimrc.

When a .py file is open, :echo &omnifunc prints pythoncomplete#Complete.

I'm working with a large project and I have a tags file generated with exhuberant-ctags. It's in Vim's ctags path. I can test it by typing ^] on a symbol and I'm then taken to the symbols' definition.

Update 1: All of my project's code is in the python-in-Vim's path. I can :python import myproject successfully.

Now, anywhere I try C-x C-o, all I get is:

```<code>-- Omni completion (^O^N^P) Pattern not found
</code>```

What am I doing wrong?

Update 2: When I type C-x C-o C-n at the module-level, Vim displays a completion popup with a few module-level constants from other modules in my project. But it's only constants (symbols capital letters) and the completion still doesn't work anywhere else.

Update 3: I've found that C-x C-o at the top of the file starts some kind of omnicompletion, and completion for pprint. brings up the menu and quick-reference of everything in the pprint module. However, none of my own module's imports are being completed.

Update 4, one year later: I gave up and learned Emacs. I have been to the dark side, the mystical land of intrigue and spice, and I say to thee that I have found The Way.

Update 5, two years later: I went back to Vim. Emacs is beautiful, but even after 1.5 years of Emacs, I'm still faster at getting work done in Vim. I've stopped writing Python for now, however, and can't test how well these suggestions work.

答:
If you are using python2, make sure you

```<code>sudo apt-get install vim.nox-py2
</code>```

and use vim.nox-py2 instead of vim.

Body:
I've searched around for an hour, both on Stack Overflow and elsewhere. Alas! Please help. Vim's omnicompletion just doesn't work.

I have Vim 7.2 compiled with Python support.

filetype plugin on is in my .vimrc.

When a .py file is open, :echo &omnifunc prints pythoncomplete#Complete.

I'm working with a large project and I have a tags file generated with exhuberant-ctags. It's in Vim's ctags path. I can test it by typing ^] on a symbol and I'm then taken to the symbols' definition.

Update 1: All of my project's code is in the python-in-Vim's path. I can :python import myproject successfully.

Now, anywhere I try C-x C-o, all I get is:

-- Omni completion (^O^N^P) Pattern not found

What am I doing wrong?

Update 2: When I type C-x C-o C-n at the module-level, Vim displays a completion popup with a few module-level constants from other modules in my project. But it's only constants (symbols capital letters) and the completion still doesn't work anywhere else.

Update 3: I've found that C-x C-o at the top of the file starts some kind of omnicompletion, and completion for pprint. brings up the menu and quick-reference of everything in the pprint module. However, none of my own module's imports are being completed.

Update 4, one year later: I gave up and learned Emacs. I have been to the dark side, the mystical land of intrigue and spice, and I say to thee that I have found The Way.

Update 5, two years later: I went back to Vim. Emacs is beautiful, but even after 1.5 years of Emacs, I'm still faster at getting work done in Vim. I've stopped writing Python for now, however, and can't test how well these suggestions work.

Body:
If you are using python2, make sure you

sudo apt-get install vim.nox-py2

and use vim.nox-py2 instead of vim.


问:
Is Java "pass-by-reference" or "pass-by-value"?
I always thought Java uses pass-by-reference. However, I read a blog post which claims that Java uses pass-by-value. I don't think I understand the distinction the author is making.

What is the explanation?

答:
Unlike some other languages, Java does not allow you to choose between pass-by-value and pass-by-reference.

All arguments are passed by value.

A method call can pass two types of valuesto a method

copies of primitive values (e.g., values of type int and double)

copies of references to objects.

Objects themselves cannot be passed to methods. When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.

This is also true for reference-type parameters. If you modify a reference-type parameter so that it refers to another object, only the parameter refers to the new object—the reference stored in the caller’s variable still refers to the original object.

References: Java™ How To Program (Early Objects), Tenth Edition


问:
How to fix a white gap after Bootstrap 4 Cards (CSS3 multi-columns bug)(Chrome IE )?
I have very annoying bug on Chrome and IE (On Fire Fox it looks fine). I am not really sure what element or elements are doing this.

About the bug:  If you scroll down, you can see where the Bootstrap cards end a big white gap between them and the footer.

URL where the bug is: I have to remove my URL (Stackoverflow rules...sorry guys)

I have been using Google Chrome Inspect to try to find where the problem is but I did not have luck. That is the reason why I am asking here because I can see where the problem is.

The only clues I have are:
-   The bug is not in any JS file or in any extern css file, I think there is something in my CSS is doing this.
-   It is not the position:relative or the overflow:hidden form the class dtl24, because I have tried to delete them and updated my CSS without them and the bug was still there.

Also, I would like to apologize to you. I have tried to create a snippet with the code but without the images, the bug not appreciable.

Do you know where is the bug and how I could fix it please?

Thanks

答:
It is happening because of this styling. </p>

```<code>column-gap: 1.25rem;
</code>```

Body:
It is happening because of this styling.

column-gap: 1.25rem;


问:
How to test style for a React component attribute with Enzyme
I am trying to test a style attribute for a React component. What is the best way to get style params in the test?

At this moment, my best option is to test if the HTML includes the string, but I think there is a better option.

Case:

```<code>it('Should render large image when desktop', () => {
    const dummyUrl = 'http://dummyUrl';
    const wrapper = shallow(
      <MockedStore
        initialState={{
          app: fromJS({ browser: { desktop: true } }),
        }}
      >
        <LandingHero bigImage={dummyUrl} />
      </MockedStore>
    );
  });
</code>```

The Component to test is:

```<code>// @flow
import React, { Component } from 'react';
import gc from 'styles/core.scss';
import $ from 'jquery';
import DownloadButton from 'components/DownloadButton';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import DownArrow from 'components/DownArrow';
import { connect } from 'react-redux';
import type { Map } from 'immutable';
import c from './styles.scss';

@withStyles([gc, c])
@connect(({ app }) => ({ app }))
class LandingHero extends Component {
  componentDidMount() {
    if ($(window).height() > 0) { // Necesary for webpack dev server
      $(this.hero).css('height', $(window).height() - 46);
    }
  }

  hero: HTMLElement;

  props: {
    app: Map<string, any>,
    copy: string,
    secondaryText: string,
    thirdText: string,
    bigImage?: string,
    smallImage: string,
  }

  render() {
    const { copy, secondaryText, thirdText } = this.props;
    const browser = this.props.app.has('browser') ? this.props.app.get('browser') : {};
    const backgroundImage = browser.desktop ? this.props.bigImage : this.props.smallImage;

    return (
      <div
        className={`${c.hero} ${gc.textCenter}` +
        ` ${gc.alignMiddle} ${gc.alignCenter} ${gc.row} ${gc.expanded}`}
        ref={(hero) => { this.hero = hero; }}
        style={{
          margin: 0,
          position: 'relative',
          background: `linear-gradient(to bottom, rgba($ixdarkprimary, .3), rgba($ixdarkprimary, .3)), url(${backgroundImage || ''})`,
        }}
      >
        <div className={`${gc.row} ${gc.alignCenter} ${gc.alignMiddle} ${gc.column} ${gc.medium10}`}>
          <div className={`${gc.textCenter}`}>
            <div
              className={`${gc.white} ${c.mainText} ${c.copy}`}
            >
              { copy }
            </div>
            <div className={`${gc.small6} ${gc.smallOffset3} ${gc.medium4} ${gc.mediumOffset4}`} style={{ marginBottom: 45 }}>
              <DownloadButton />
            </div>
            <div className={`${gc.white} ${gc.fontBold} ${gc.font24}`}>{secondaryText}</div>
            <p className={`${gc.white} ${gc.font20}`}>{thirdText}</p>
          </div>
          <DownArrow goTo="#content" />
        </div>
      </div>
    );
  }
}

export default LandingHero;
</code>```

答:
You can use this method. It returns ReactElement.</p>

```<code>let containerStyle = container.get(0).style;
expect(containerStyle).to.have.property('opacity', '1');
</code>```

Body:
I am trying to test a style attribute for a React component. What is the best way to get style params in the test?

At this moment, my best option is to test if the HTML includes the string, but I think there is a better option.

Case:

it('Should render large image when desktop', () => {
    const dummyUrl = 'http://dummyUrl';
    const wrapper = shallow(
      <MockedStore
        initialState={{
          app: fromJS({ browser: { desktop: true } }),
        }}
      >
        <LandingHero bigImage={dummyUrl} />
      </MockedStore>
    );
  });

The Component to test is:

// @flow
import React, { Component } from 'react';
import gc from 'styles/core.scss';
import $ from 'jquery';
import DownloadButton from 'components/DownloadButton';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import DownArrow from 'components/DownArrow';
import { connect } from 'react-redux';
import type { Map } from 'immutable';
import c from './styles.scss';

@withStyles([gc, c])
@connect(({ app }) => ({ app }))
class LandingHero extends Component {
  componentDidMount() {
    if ($(window).height() > 0) { // Necesary for webpack dev server
      $(this.hero).css('height', $(window).height() - 46);
    }
  }

  hero: HTMLElement;

  props: {
    app: Map<string, any>,
    copy: string,
    secondaryText: string,
    thirdText: string,
    bigImage?: string,
    smallImage: string,
  }

  render() {
    const { copy, secondaryText, thirdText } = this.props;
    const browser = this.props.app.has('browser') ? this.props.app.get('browser') : {};
    const backgroundImage = browser.desktop ? this.props.bigImage : this.props.smallImage;

    return (
      <div
        className={`${c.hero} ${gc.textCenter}` +
        ` ${gc.alignMiddle} ${gc.alignCenter} ${gc.row} ${gc.expanded}`}
        ref={(hero) => { this.hero = hero; }}
        style={{
          margin: 0,
          position: 'relative',
          background: `linear-gradient(to bottom, rgba($ixdarkprimary, .3), rgba($ixdarkprimary, .3)), url(${backgroundImage || ''})`,
        }}
      >
        <div className={`${gc.row} ${gc.alignCenter} ${gc.alignMiddle} ${gc.column} ${gc.medium10}`}>
          <div className={`${gc.textCenter}`}>
            <div
              className={`${gc.white} ${c.mainText} ${c.copy}`}
            >
              { copy }

            <div className={`${gc.small6} ${gc.smallOffset3} ${gc.medium4} ${gc.mediumOffset4}`} style={{ marginBottom: 45 }}>
              <DownloadButton />

            <div className={`${gc.white} ${gc.fontBold} ${gc.font24}`}>{secondaryText}

            <p className={`${gc.white} ${gc.font20}`}>{thirdText}

          <DownArrow goTo="#content" />

    );
  }
}

export default LandingHero;

Body:
You can use this method. It returns ReactElement.

let containerStyle = container.get(0).style;
expect(containerStyle).to.have.property('opacity', '1');