问:
Send email from Android App without user's intervention
I would like to send an email to given email address with some default instructions. I know that I can achieve it for sms by using twilio but don't know how to do this via mail..</p>

答:
You can directly use following to send mail with body:</p>

```<code>final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
                          emailIntent.setType("text/plain");
                          intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String\[\]{  "serveroverloadofficial@gmail.com"});
                          intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hello There");
                          intent.putExtra(android.content.Intent.EXTRA_TEXT, "Add Message here");

                            intent.setType("message/rfc822");

                        try {
                            startActivity(Intent.createChooser(intent,
                                    "Send email using..."));
                        } catch (android.content.ActivityNotFoundException ex) {
                            Toast.makeText(getActivity(),
                                    "No email clients installed.",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                });
</code>```

Body:
You can directly use following to send mail with body:

final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
                          emailIntent.setType("text/plain");
                          intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String\[\]{  "serveroverloadofficial@gmail.com"});
                          intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hello There");
                          intent.putExtra(android.content.Intent.EXTRA_TEXT, "Add Message here");

                            intent.setType("message/rfc822");

                        try {
                            startActivity(Intent.createChooser(intent,
                                    "Send email using..."));
                        } catch (android.content.ActivityNotFoundException ex) {
                            Toast.makeText(getActivity(),
                                    "No email clients installed.",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                });


来源: stackexchange

问:
Get url variable from request
One of my URLs looks like this:

```<code>url(r'^(?P<my_id>[0-9]+)/foo/', Foo.as_view()),
</code>```

Given this CBV:

```<code>Class Whatever(View):

    @custom_decorator(my_id)
    def post(self, request, my_id):
        # ...
</code>```

I need to access to my_id in the decorator. What is the best way to accomplish this?
Maybe, overriding initial and take it from request.path?

答:
You should named your parameter in your URL :

```<code>url(r'^(?P<my_id>[0-9]+)/foo/', Foo.as_view()),
</code>```

And then use it in your CBV :

```<code>Class Whatever(View):

@decorator(my_id)
def post(self, request, my_id, *args, **kwargs):
    self.kwargs['my_id']
    ...
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get url variable from request

Body:
One of my URLs looks like this:

url(r'^(?P<my_id>[0-9]+)/foo/', Foo.as_view()),

Given this CBV:

Class Whatever(View):

    @custom_decorator(my_id)
    def post(self, request, my_id):
        # ...

I need to access to my_id in the decorator. What is the best way to accomplish this?
Maybe, overriding initial and take it from request.path?

Body:
You should named your parameter in your URL :

url(r'^(?P<my_id>[0-9]+)/foo/', Foo.as_view()),

And then use it in your CBV :

Class Whatever(View):

@decorator(my_id)
def post(self, request, my_id, *args, **kwargs):
    self.kwargs['my_id']
    ...


问:
Is it possible to redirect all types of error to a common page in codeigniter?
Is it possible redirect all following error page contents to a common page?
normally codeigniter packages include following pages for error handling:

application->views->errors->html (error_exception.php, error_db.php, error_general.php, error_php.php, error_404.php)
Is it possible to redirect these contents to a common page?

答:
Use try...catch and redirect everything to one page using header.</p>

```<code>try {
   //code
} catch( Exception $e ) {
   echo "friendly error message";
   logging_function($e->getMessage());
   throw $e;
}
</code>```

Body:
Use try...catch and redirect everything to one page using header.

try {
   //code
} catch( Exception $e ) {
   echo "friendly error message";
   logging_function($e->getMessage());
   throw $e;
}


问:
Do I have to use a Git software or it's ok to use just the command line?
I always like the Command Line Environment because you feel like you have control on every thing. But is it necessary to use a software for using Git? How do companies handle this? Do they use CLI or do they use softwares?</p>

答:
Yes, it’s not necessary.

Since you are familiar with command line and like to use it, I will recommend you to use it directly.

Other IDE/software just operate based on git commands, and it’s limited for some commands to used in IDE. Such as git filter-branch, git update-index etc are not supported by most IDE (VS, TortoiseGit, sourceTree etc). It’s more free for you to use command line directly if you are used to it.


问:
How to add key with unique random value in HTTP Request defaults in Jmeter
I am trying to apply load  sample request is like

http://54.174.110.64:8080/adserver/html5/inwapads/?adFormat=preappvideo&ak=O4DCX2&version=1.0&adu=5&cb=1494853894218&output=vast&priority=1&size=[vdo_adSize]&pageURL=http://qa.vdopia.com/qa/Ruchi/ssp_preroll1.html?0.7888977&domain=vdopia.com&refURL=&category=[CATEGORY]&siteName=vdopia&displayManager=Vdopia-SPP-Web&di=[COOKIE_ID]&dif=fpcm&sex=[GENDER]&age=[AGE];ipAddress=203.122.9.130;di=abcdefghijklmn

I have single request, what I want is that same request should have unique di (last key in query param). Nothing else I want to change.

My test is based on unique di in request keeping other parameters constant.

答:
You can use Random function.

Hint:

Body:
You can use Random function.

Hint:


问:
Pass *args in django templates
I did use django pagination, but there is a problem with urls, here is my urls.py:

```<code>url(r'^/blog/$', blog_view.main, name='blog'),
url(r'^/blog/page/(?P<page_id>\d{0,9})$', blog.post, name='blog_page'),
</code>```

My views.py:

```<code>def post(request, page_id=None):
    posts = Posts.objects.all()
    pageid = page_id
    return render(request, 'base.html', {'posts': posts, 'pageid': pageid,})
</code>```

My base.html which use bootstrap:

```<code>{% url 'blog_page' as blog_page %} # Blog page need follow patterns
    <ul>
{% for post in posts %}
    <li {% if request.path == htt://myblog.com/blog/page/5 %} class="active" {% endif %}>{{ post.title }}</li> # When I put blog_page django shows error. Help me how to put something to fix this condition.
{% endfor %}
   </ul>
</code>```

答:
As stated in the documenation on HttpRequest objects,
HttpRequest.path is

A string representing the full path to the requested page, not including the scheme or domain.

  Example: "/music/bands/the_beatles/"

(emphasis mine).

So, in your test, leave out the scheme (which you, btw, incorrectly wrote as htt://) and domain parts:

```<code><li {% if request.path == /blog/page/5 %} class="active" {% endif %}>{{ post.title }}</li>
</code>```

Title: Pass *args in django templates

Body:
I did use django pagination, but there is a problem with urls, here is my urls.py:

url(r'^/blog/$', blog_view.main, name='blog'),
url(r'^/blog/page/(?P<page_id>\d{0,9})$', blog.post, name='blog_page'),

My views.py:

def post(request, page_id=None):
    posts = Posts.objects.all()
    pageid = page_id
    return render(request, 'base.html', {'posts': posts, 'pageid': pageid,})

My base.html which use bootstrap:

{% url 'blog_page' as blog_page %} # Blog page need follow patterns

{% for post in posts %}

{{ post.title }}
 # When I put blog_page django shows error. Help me how to put something to fix this condition.
{% endfor %}

Body:
As stated in the documenation on HttpRequest objects,
HttpRequest.path is

A string representing the full path to the requested page, not including the scheme or domain.

  Example: "/music/bands/the_beatles/"

(emphasis mine).

So, in your test, leave out the scheme (which you, btw, incorrectly wrote as htt://) and domain parts:

<li {% if request.path == /blog/page/5 %} class="active" {% endif %}>{{ post.title }}</li>


问:
Angular Material2 md-select dropdown appears at bottom of the page
I'm currently using Angular Material2 in an Angular 2.4.0 application (using @angular/material: 2.0.0-beta.1). For some reason, the md-select dropdown, instead of appearing over the initial value or placeholder or arrow to select the dropdown, as demonstrated in these examples from the material docs, appears all the way at the bottom of the page. To the point that if the md-select dropdown is at the top right of the page (the component I am attempting to place mine in is at the top right of the page) when you click the arrow to view the dropdown options it will scroll you to the bottom of the page where they will be displayed. They will also be the full width of the page rather than the width of the dropdown.

Here is my component (at least the relevant bits - this app is fairly large + I commented out or removed as much code not relating to the dropdown (and removed everything in the view other than the dropdown to both narrow down the issue for myself as well as make it easier for anyone reading this to see the issue)):

```<code>import { Component, EventEmitter, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  moduleId: module.id,
  selector: 'my-component',
  templateUrl: 'my-component.component.html',
  styleUrls: ['my-component.component.css'],
  providers: [FormBuilder]
})

export class MyComponent implements OnInit {
  @Input() page: Page;
  canvasBackgroundColors: string[] = ['White', 'Pink', 'Black'];
  draftModule: FormGroup;

  // --- Component Constructor ---

  constructor(private formBuilder: FormBuilder){}

  // --- Angular LifeCycle Hooks ---

  ngOnInit() {
    this.formBuilderInit();
  }

  // --- UI Delegates ---
  public onSave() {
   debugger;
  }

  // --- Private Helpers ---

  private formBuilderInit() {
    this.draftModule = this.formBuilder.group({
      canvasBackgroundColor: this.page.canvasBackgroundColor,
    });

    this.draftModule.valueChanges.subscribe(draftMod => {
      console.log('Test Module', draftMod);
    })
  }
}
</code>```

The associated NgModule has the MaterialModule imported appropriately.
Here is the entire view (haml):

```<code>%form{'[formGroup]' => 'draftModule', '(ngSubmit)' => 'onSave()'}

  %md-select{'formControlName' => 'canvasBackgroundColor'}
    %md-option{'*ngFor' => 'let color of canvasBackgroundColors', :value => '{{color}}'}
      {{color}}

  %button{:type => 'submit'}
    Save
</code>```

Currently all the CSS for the entire app has been commented out so I know it's not something in there affecting the dropdown. The dropdown works perfectly and updates properly with form builder, its just that when you click the dropdown error the options suddenly show up all the way at the bottom of the page and are as wide as the page. Once you select an option you get scrolled back up to where your dropdown box is. I have searched everywhere and can't seem to find anyone else having this problem or a fix for it. The closest I came was one person mentioning in this github issue that they had this problem but they fixed it by adding theming. I tried this and adding theming did not make a difference in the way the dropdown worked.

For further clarification, when I inspect the dropdown options that appear at the bottom of the page I noticed that they appear not just outside of the component's template that md-select is in, but outside of the angular app entirely. The html shown in the inspector looks something like the following code (simplified of course to remove all the components that are not relevant to this issue). Note: my-app is the selector for the app component and cdk-overlay-container includes the md-select-panel and md-select-content and the dropdown options):

```<code> <html>
   <head></head>
   <body id="body" class>
     <my-app>
       <my-component>
         <md-select></md-select>
       </my-component>
     </my-app>
     <div class="cdk-overlay-container"></div>
   </body>
</html>
</code>```

Any advice would be appreciated!

答:
If you are installing angular material to your angular cli project then your themes would be in node_modules/@angular/material/prebuilt-themes/

so import link would be something like shown below

```<code>@import "~@angular/material/prebuilt-themes/deeppurple-amber.css"
</code>```

We should add the above line to our angular-cli application's styles.css file. Here deeppurple-amber.css is one of the prebuilt theme angular material is offering us.
Most of the built-in components like md-select won't be working as expected if this import has not done properly.

Happy Coding :)

Body:
I'm currently using Angular Material2 in an Angular 2.4.0 application (using @angular/material: 2.0.0-beta.1). For some reason, the md-select dropdown, instead of appearing over the initial value or placeholder or arrow to select the dropdown, as demonstrated in these examples from the material docs, appears all the way at the bottom of the page. To the point that if the md-select dropdown is at the top right of the page (the component I am attempting to place mine in is at the top right of the page) when you click the arrow to view the dropdown options it will scroll you to the bottom of the page where they will be displayed. They will also be the full width of the page rather than the width of the dropdown.

Here is my component (at least the relevant bits - this app is fairly large + I commented out or removed as much code not relating to the dropdown (and removed everything in the view other than the dropdown to both narrow down the issue for myself as well as make it easier for anyone reading this to see the issue)):

import { Component, EventEmitter, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  moduleId: module.id,
  selector: 'my-component',
  templateUrl: 'my-component.component.html',
  styleUrls: ['my-component.component.css'],
  providers: [FormBuilder]
})

export class MyComponent implements OnInit {
  @Input() page: Page;
  canvasBackgroundColors: string[] = ['White', 'Pink', 'Black'];
  draftModule: FormGroup;

  // --- Component Constructor ---

  constructor(private formBuilder: FormBuilder){}

  // --- Angular LifeCycle Hooks ---

  ngOnInit() {
    this.formBuilderInit();
  }

  // --- UI Delegates ---
  public onSave() {
   debugger;
  }

  // --- Private Helpers ---

  private formBuilderInit() {
    this.draftModule = this.formBuilder.group({
      canvasBackgroundColor: this.page.canvasBackgroundColor,
    });

    this.draftModule.valueChanges.subscribe(draftMod => {
      console.log('Test Module', draftMod);
    })
  }
}

The associated NgModule has the MaterialModule imported appropriately.
Here is the entire view (haml):

%form{'[formGroup]' => 'draftModule', '(ngSubmit)' => 'onSave()'}

  %md-select{'formControlName' => 'canvasBackgroundColor'}
    %md-option{'*ngFor' => 'let color of canvasBackgroundColors', :value => '{{color}}'}
      {{color}}

  %button{:type => 'submit'}
    Save

Currently all the CSS for the entire app has been commented out so I know it's not something in there affecting the dropdown. The dropdown works perfectly and updates properly with form builder, its just that when you click the dropdown error the options suddenly show up all the way at the bottom of the page and are as wide as the page. Once you select an option you get scrolled back up to where your dropdown box is. I have searched everywhere and can't seem to find anyone else having this problem or a fix for it. The closest I came was one person mentioning in this github issue that they had this problem but they fixed it by adding theming. I tried this and adding theming did not make a difference in the way the dropdown worked.

For further clarification, when I inspect the dropdown options that appear at the bottom of the page I noticed that they appear not just outside of the component's template that md-select is in, but outside of the angular app entirely. The html shown in the inspector looks something like the following code (simplified of course to remove all the components that are not relevant to this issue). Note: my-app is the selector for the app component and cdk-overlay-container includes the md-select-panel and md-select-content and the dropdown options):

     <my-app>
       <my-component>
         <md-select></md-select>
       </my-component>
     </my-app>

Any advice would be appreciated!

Body:
If you are installing angular material to your angular cli project then your themes would be in node_modules/@angular/material/prebuilt-themes/

so import link would be something like shown below

@import "~@angular/material/prebuilt-themes/deeppurple-amber.css"

We should add the above line to our angular-cli application's styles.css file. Here deeppurple-amber.css is one of the prebuilt theme angular material is offering us.
Most of the built-in components like md-select won't be working as expected if this import has not done properly.

Happy Coding :)


问:
How can I confirm that firebase notification was actually sent (fcm)?
I allow users to send notifications out through my website. The notifications are working, however, I would like a way to actually confirm if the notification was sent out (in code), or if that is not possible at least confirmation that the curl worked, so I can show a message on my website that it either succeeded or failed. In my jquery post request, the status seems to always be "success", even if I provide an invalid API_ACCESS_KEY in my php (so it obviously is not sending the notification yet it is still saying success). How can I know for sure that the notification was sent out? Grateful for any help.

Here is my post request in index.html:

```<code>$("#send-button").click(function(){
    if($("#send").val().length == 0) {
        return;
    } else {
        $.post("php/send-notification.php",
        {
            notification_message: $("#send").val()
        },
        function(data, status) {
            alert("Data: " + data + "\nStatus: " + status);
            // status seems to always be "success" even with an invalid API_ACCESS_KEY
        });
    }
});
</code>```

Here is send-notification.php:

```<code><?php
    define( 'API_ACCESS_KEY', 'AAA....AAA' );

    $msg = array
    (
        'body'  => $_POST['notification_message'],
        'vibrate'   => 1,
        'sound'     => 1,
        'badge'     => 1
    );

    $fields = array
    (
        'to'            => "/topics/global",
        'notification'  => $msg,
        'priority'      => 'high'
    );

    $headers = array
    (
        'Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
    curl_setopt( $ch,CURLOPT_POST, true );
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
    $result = curl_exec( $ch );
    curl_close( $ch );
?>
</code>```

答:
You can use curl_getinfo

to check response information, if yur status code 200 that meet everything ok.

```<code>$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($httpcode == 200) {
    //everything ok
}
</code>```

Body:
I allow users to send notifications out through my website. The notifications are working, however, I would like a way to actually confirm if the notification was sent out (in code), or if that is not possible at least confirmation that the curl worked, so I can show a message on my website that it either succeeded or failed. In my jquery post request, the status seems to always be "success", even if I provide an invalid API_ACCESS_KEY in my php (so it obviously is not sending the notification yet it is still saying success). How can I know for sure that the notification was sent out? Grateful for any help.

Here is my post request in index.html:

$("#send-button").click(function(){
    if($("#send").val().length == 0) {
        return;
    } else {
        $.post("php/send-notification.php",
        {
            notification_message: $("#send").val()
        },
        function(data, status) {
            alert("Data: " + data + "\nStatus: " + status);
            // status seems to always be "success" even with an invalid API_ACCESS_KEY
        });
    }
});

Here is send-notification.php:

<?php
    define( 'API_ACCESS_KEY', 'AAA....AAA' );

    $msg = array
    (
        'body'  => $_POST['notification_message'],
        'vibrate'   => 1,
        'sound'     => 1,
        'badge'     => 1
    );

    $fields = array
    (
        'to'            => "/topics/global",
        'notification'  => $msg,
        'priority'      => 'high'
    );

    $headers = array
    (
        'Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
    curl_setopt( $ch,CURLOPT_POST, true );
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
    $result = curl_exec( $ch );
    curl_close( $ch );
?>

Body:
You can use curl_getinfo

to check response information, if yur status code 200 that meet everything ok.

$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($httpcode == 200) {
    //everything ok
}


问:
Pagination in thumbnail PHP
I am trying to create a page that shows thumbnails from my database. However i want to create a pagination in case i want to update my database. Only the first 3 table should show in page 1 and so on...

Here is my script in thumbnail

```<code><?php
    /* Attempt MySQL server connection. Assuming you are running MySQL
    server with default setting (user 'root' with no password) */
    $link = mysqli_connect("localhost", "root", "", "test");

    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    // Attempt select query execution
    $sql = "SELECT * FROM news limit 3";
    if($result = mysqli_query($link, $sql)){
        if( mysqli_num_rows($result) > 0 ){

            echo "<div class=\"container\">";
            echo "<table>";
            echo "<tr>";
            echo "</tr>";
            while($row=mysqli_fetch_array($result)){

                echo "<div class=\"col-md-4\">";
                echo "<div class=\"thumbnail\">";
                echo "<img alt=\"News\" src=\"images/{$row["image"]}\">";
                echo "<div class=\"caption\">";
                echo "<b><h4>{$row["title"]}</b></h4>";
                echo "<p>{$row["caption"]}</p>";
                echo "<p align=\"right\">";
                echo "<a class=\"btn btn-primary\" href=\"{$row["newsupdate"]}\">Read More</a>";
                echo "</p>";
                echo "</div>";
                echo "</div>";
                echo "</div>";
                echo "</div>";
            }
            echo "</table>";

            // Free result set
            mysqli_free_result($result);
        } else{
            echo "No records matching your query were found.";
        }
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }

    // Close connection
    mysqli_close($link);
?>

<ul class="pagination">
  <li><a href="#">1</a></li>
  <li><a href="#">2</a></li>
  <li><a href="#">3</a></li>
  <li><a href="#">4</a></li>
  <li><a href="#">5</a></li>
</ul>
</code>```

答:
In order to paginate through your recordset, thus limiting the display to a specified number of records at a time, you need to change the sql query to use the offset and total values for the limit clause. Generally pagination uses GET variables to determine the page the user is currently on and this variable is used in the SQL query.

The following is a basic example I just wrote to paginate through a particular recordset - it should be straightforward to utilise the code and alter to suit your particular query.

```<code><?php
    $dbhost =   'localhost';
    $dbuser =   'xxx';
    $dbpwd  =   'xxx';
    $dbname =   'xxx';
    $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
?>
<!doctype html>
<html>
    <head>
        <title>Basic Pagination</title>
        <style>
            #paging{border-top:1px solid black;margin:1rem auto;float:none;clear:both;}
            #paging *{margin:0.5rem 1rem;clear:none!important;display:inline-block;}
            .minimal{margin:0.5rem 0.1rem!important;}
        </style>
    </head>
    <body>
        <div id='results'>
            <?php
                /* Single user supplied parameter - the PAGE */
                $page = isset( $_GET['page'] ) ? filter_input( INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT ) : 0;

                if( is_numeric( $page ) && $page >= 0 ){

                    $rpp = 10;  /* Records Per Page */
                    $offset = $page * $rpp; /* paging offset */

                    /*
                        In order to determine the paging you need to know the total number of records available
                        that are returned by the query with any given WHERE clause. The sub-query therefore uses
                        the same WHERE clause and returns a number to be used later.

                        Edit the sql to suit your needs and edit the data that is rendered in the while loop.
                    */
                    $sql="select
                        ( select count(*) from `maps`  where `location_enabled`=1 ) as 'count',
                        `id`,
                        `location_name` as 'name'
                        from `maps`
                        where `location_enabled`=1
                        limit {$offset},{$rpp}";

                    /*
                        Ignoring the possible SQL injection vulnerability - run the query
                    */
                    $results=$db->query( $sql );

                    if( $results && $results->num_rows > 0 ){

                        /* Process the recordset however is appropriate for your use-case */
                        while( $rs=$results->fetch_object() ){

                            /* From sql query, the total number of records that satisfy the "WHERE" clause */
                            $count=$rs->count;

                            /* output data - thumbnails etc etc */
                            echo "<div>{$rs->id} - {$rs->name}</div>";
                        }

                    } else {
                        echo "Error! Unable to fetch results";
                    }
                } else {
                    echo "Error... Bad foo!";
                }
            ?>
        </div>
        <div id='paging'>
            <?php
                /*
                    Calculate links for basic pagination
                    ( First,Previous,Next,Last )
                */
                if( is_numeric( $page ) ){

                    $total_pages = floor( $count / $rpp );

                    $text='First';
                    if( $page == 0 ){
                        echo "<div>$text</div>";
                    } else {
                        echo "<a href='?page=0'>$text</a>";
                    }

                    $text='Previous';
                    if( $page > 0 ){
                        echo "<a href='?page=".max( 0, $page - 1 )."'>$text</a>";
                    } else {
                        echo "<div>$text</div>";
                    }

                    $text='Next';
                    if( $page >= $total_pages ){
                        echo "<div>$text</div>";
                    } else {
                        echo "<a href='?page=".min( $total_pages, $page + 1 )."'>$text</a>";
                    }

                    $text='Last';
                    if( $page==$total_pages ){
                        echo "<div>$text</div>";
                    } else {
                        echo "<a href='?page={$total_pages}'>$text</a>";
                    }

                    /* Generate basic hyperlink for each possible page */
                    for( $i=0; $i <= $total_pages; $i++ ) {
                        echo "<a class='minimal' href='?page={$i}'>".( $i + 1 )."</a>";
                    }
                }
            ?>
        </div>
    </body>
</html>
<?php

    $db->close();

?>
</code>```

Title: Pagination in thumbnail PHP

Body:
I am trying to create a page that shows thumbnails from my database. However i want to create a pagination in case i want to update my database. Only the first 3 table should show in page 1 and so on...

Here is my script in thumbnail

<?php
    /* Attempt MySQL server connection. Assuming you are running MySQL
    server with default setting (user 'root' with no password) */
    $link = mysqli_connect("localhost", "root", "", "test");

    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    // Attempt select query execution
    $sql = "SELECT * FROM news limit 3";
    if($result = mysqli_query($link, $sql)){
        if( mysqli_num_rows($result) > 0 ){

            echo "
";
            echo "
";
            echo "
";
            echo "
";
            while($row=mysqli_fetch_array($result)){

                echo "
";
                echo "
";
                echo "";
                echo "
";
                echo "
{$row["title"]}
";
                echo "
{$row["caption"]}
";
                echo "
";
                echo "Read More";
                echo "
";
                echo "
";
                echo "
";
                echo "
";
                echo "
";
            }
            echo "
";

            // Free result set
            mysqli_free_result($result);
        } else{
            echo "No records matching your query were found.";
        }
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }

    // Close connection
    mysqli_close($link);
?>

1

2

3

4

5

Body:
In order to paginate through your recordset, thus limiting the display to a specified number of records at a time, you need to change the sql query to use the offset and total values for the limit clause. Generally pagination uses GET variables to determine the page the user is currently on and this variable is used in the SQL query.

The following is a basic example I just wrote to paginate through a particular recordset - it should be straightforward to utilise the code and alter to suit your particular query.

<?php
    $dbhost =   'localhost';
    $dbuser =   'xxx';
    $dbpwd  =   'xxx';
    $dbname =   'xxx';
    $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
?>
<!doctype html>
<html>
    <head>
        <title>Basic Pagination</title>
        <style>
            #paging{border-top:1px solid black;margin:1rem auto;float:none;clear:both;}
            #paging *{margin:0.5rem 1rem;clear:none!important;display:inline-block;}
            .minimal{margin:0.5rem 0.1rem!important;}
        </style>
    </head>
    <body>
        <div id='results'>
            <?php
                /* Single user supplied parameter - the PAGE */
                $page = isset( $_GET['page'] ) ? filter_input( INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT ) : 0;

                if( is_numeric( $page ) && $page >= 0 ){

                    $rpp = 10;  /* Records Per Page */
                    $offset = $page * $rpp; /* paging offset */

                    /*
                        In order to determine the paging you need to know the total number of records available
                        that are returned by the query with any given WHERE clause. The sub-query therefore uses
                        the same WHERE clause and returns a number to be used later.

                        Edit the sql to suit your needs and edit the data that is rendered in the while loop.
                    */
                    $sql="select
                        ( select count(*) from `maps`  where `location_enabled`=1 ) as 'count',
                        `id`,
                        `location_name` as 'name'
                        from `maps`
                        where `location_enabled`=1
                        limit {$offset},{$rpp}";

                    /*
                        Ignoring the possible SQL injection vulnerability - run the query
                    */
                    $results=$db->query( $sql );

                    if( $results && $results->num_rows > 0 ){

                        /* Process the recordset however is appropriate for your use-case */
                        while( $rs=$results->fetch_object() ){

                            /* From sql query, the total number of records that satisfy the "WHERE" clause */
                            $count=$rs->count;

                            /* output data - thumbnails etc etc */
                            echo "<div>{$rs->id} - {$rs->name}</div>";
                        }

                    } else {
                        echo "Error! Unable to fetch results";
                    }
                } else {
                    echo "Error... Bad foo!";
                }
            ?>
        </div>
        <div id='paging'>
            <?php
                /*
                    Calculate links for basic pagination
                    ( First,Previous,Next,Last )
                */
                if( is_numeric( $page ) ){

                    $total_pages = floor( $count / $rpp );

                    $text='First';
                    if( $page == 0 ){
                        echo "<div>$text</div>";
                    } else {
                        echo "<a href='?page=0'>$text</a>";
                    }

                    $text='Previous';
                    if( $page > 0 ){
                        echo "<a href='?page=".max( 0, $page - 1 )."'>$text</a>";
                    } else {
                        echo "<div>$text</div>";
                    }

                    $text='Next';
                    if( $page >= $total_pages ){
                        echo "<div>$text</div>";
                    } else {
                        echo "<a href='?page=".min( $total_pages, $page + 1 )."'>$text</a>";
                    }

                    $text='Last';
                    if( $page==$total_pages ){
                        echo "<div>$text</div>";
                    } else {
                        echo "<a href='?page={$total_pages}'>$text</a>";
                    }

                    /* Generate basic hyperlink for each possible page */
                    for( $i=0; $i <= $total_pages; $i++ ) {
                        echo "<a class='minimal' href='?page={$i}'>".( $i + 1 )."</a>";
                    }
                }
            ?>
        </div>
    </body>
</html>
<?php

    $db->close();

?>


问:
Angular Service is reset on each call of it
In my web Angular project I've created an AuthenticationGuard and an AuthenticationService to handle the security.

These files comes from another branch of my project who works perfectly.

Here is how my scripts should works:

Navigate to 'auth/login'

User inputs his credentials

Authservice call the back-end wepApi to get a Bearer Token

Back-end returns the token.

AuthService set his var 'isLoggedIn' to true;

AuthService use to router to navigate to '/home'

AuthGuard check authentication by checking the 'isLoggedIn' of AuthService.

My problem is when AuthGuard access the AuthService : AuthService always return false.

auth.guard.ts

import { Injectable }       from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';
import { AuthService }      from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (this.authService.getIsLoggedIn()) {
      return true;
    }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Navigate to the login page with extras
    this.router.navigate(['/auth/login']);
    return false;
  }
}```
</div>
</div>
</p>

<p>auth.service.ts
<div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';

import { config } from './../shared/smartadmin.config';

import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthService {
    private isLoggedIn: boolean = false;

    public redirectUrl: string;

    constructor(private router: Router, private http: Http) {
    }

    public getIsLoggedIn(): boolean {
        console.log("getIsLoggedIn() = " + this.isLoggedIn); // Always returns false
        return this.isLoggedIn;
    }

    public login(username: string, password: string) {
        this.ProcessLogin(username, password)
            .subscribe(result => {
                if (result === true) {
                    console.log("before attribution");
                    console.log("this.isLoggedIn = " + this.isLoggedIn); // returns false
                    this.isLoggedIn = true;
                    console.log("after attribution");
                    console.log("this.isLoggedIn = " + this.isLoggedIn); // returns true
                    this.router.navigate(this.redirectUrl ? [this.redirectUrl] : ['/home']);
                } else {
                    this.logout();
                }
            });
    }

    public logout(): void {
        localStorage.removeItem('oAuthToken');
        this.isLoggedIn = false;
    }

    private ProcessLogin(username: string, password: string): Observable<boolean> {

        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers });
        let body = 'grant_type=password&username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password);

        let endpoint = config.API_ENDPOINT + 'token';

        return this.http.post(endpoint, body, options)
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let token = response.json() && response.json().access_token;
                if (token) {
                    localStorage.setItem('oAuthToken', token);

                    // return true to indicate successful login
                    return true;
                } else {
                    localStorage.removeItem('oAuthToken');
                    // return false to indicate failed login
                    return false;
                }
            });
    }
}</code>```

答:
Without having seen your module definitions I suspect that you have not made AuthService a core service (a Singleton) which mean that every module that makes use of it will have its own instance (keeping track of its own isLoggedIn flag).

To make a service a singleton in angular it has to be served by the root module injector. To accomplish this you will need to do this:

```<code>import { NgModulep } from '@angular/core';
import { CommonModule, ModuleWithProviders } from '@angular/common';
import { AuthService, AuthGuard } from './services/index';

@NgModule({
  imports: [
    CommonModule,
    ModuleWithProviders
  ]
})
export class SharedModule {

  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        AuthService,
        AuthGuard
      ]
    };
  }

}
</code>```

And then call the forRoot method when importing the SharedModule into the root AppModule.

```<code>@NgModule({
  imports: [
    ...
    SharedModule.forRoot(),
    ...
  ],
  ...,
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Have a look att "Configure Core Services" here https://angular.io/docs/ts/latest/guide/ngmodule.html#!#core-for-root

Body:
In my web Angular project I've created an AuthenticationGuard and an AuthenticationService to handle the security.

These files comes from another branch of my project who works perfectly.

Here is how my scripts should works:

Navigate to 'auth/login'

User inputs his credentials

Authservice call the back-end wepApi to get a Bearer Token

Back-end returns the token.

AuthService set his var 'isLoggedIn' to true;

AuthService use to router to navigate to '/home'

AuthGuard check authentication by checking the 'isLoggedIn' of AuthService.

My problem is when AuthGuard access the AuthService : AuthService always return false.

auth.guard.ts

import { Injectable }       from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';
import { AuthService }      from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (this.authService.getIsLoggedIn()) {
      return true;
    }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Navigate to the login page with extras
    this.router.navigate(['/auth/login']);
    return false;
  }
}

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';

import { config } from './../shared/smartadmin.config';

import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthService {
    private isLoggedIn: boolean = false;

    public redirectUrl: string;

    constructor(private router: Router, private http: Http) {
    }

    public getIsLoggedIn(): boolean {
        console.log("getIsLoggedIn() = " + this.isLoggedIn); // Always returns false
        return this.isLoggedIn;
    }

    public login(username: string, password: string) {
        this.ProcessLogin(username, password)
            .subscribe(result => {
                if (result === true) {
                    console.log("before attribution");
                    console.log("this.isLoggedIn = " + this.isLoggedIn); // returns false
                    this.isLoggedIn = true;
                    console.log("after attribution");
                    console.log("this.isLoggedIn = " + this.isLoggedIn); // returns true
                    this.router.navigate(this.redirectUrl ? [this.redirectUrl] : ['/home']);
                } else {
                    this.logout();
                }
            });
    }

    public logout(): void {
        localStorage.removeItem('oAuthToken');
        this.isLoggedIn = false;
    }

    private ProcessLogin(username: string, password: string): Observable<boolean> {

        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers });
        let body = 'grant_type=password&username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password);

        let endpoint = config.API_ENDPOINT + 'token';

        return this.http.post(endpoint, body, options)
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let token = response.json() && response.json().access_token;
                if (token) {
                    localStorage.setItem('oAuthToken', token);

                    // return true to indicate successful login
                    return true;
                } else {
                    localStorage.removeItem('oAuthToken');
                    // return false to indicate failed login
                    return false;
                }
            });
    }
}

Body:
Without having seen your module definitions I suspect that you have not made AuthService a core service (a Singleton) which mean that every module that makes use of it will have its own instance (keeping track of its own isLoggedIn flag).

To make a service a singleton in angular it has to be served by the root module injector. To accomplish this you will need to do this:

import { NgModulep } from '@angular/core';
import { CommonModule, ModuleWithProviders } from '@angular/common';
import { AuthService, AuthGuard } from './services/index';

@NgModule({
  imports: [
    CommonModule,
    ModuleWithProviders
  ]
})
export class SharedModule {

  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        AuthService,
        AuthGuard
      ]
    };
  }

}

And then call the forRoot method when importing the SharedModule into the root AppModule.

@NgModule({
  imports: [
    ...
    SharedModule.forRoot(),
    ...
  ],
  ...,
  bootstrap: [AppComponent]
})
export class AppModule { }

Have a look att "Configure Core Services" here https://angular.io/docs/ts/latest/guide/ngmodule.html#!#core-for-root


问:
How to get $http response and assign to local variable using services?
service.js

```<code>     angular.module('app')
        .service('tableService', [
        '$q',
      tableService
  ]);

  function tableService($q){
    var tableData = [
      {
        issue: 'Vinayak N',
        progress: 100,
       // status: 69,
        class: 'md-accent'
      }
    ];
}
</code>```

i want to make a call to $http.get('http://localhost:5000/api/studentsList'); and assign the response.data to a local variable tableData in service.js

答:
Try this:</p>

```<code>angular.module('app')
        .service('tableService', [
        '$q','$http',
      tableService
  ]);

  function tableService($q, $http){
    var tableData = [
      {
        issue: 'Vinayak N',
        progress: 100,
       // status: 69,
        class: 'md-accent'
      }
    ];
    $http.get('http://localhost:5000/api/studentsList').then(function(result){
      tableData.data = result.data;
    });
}
</code>```

Body:
service.js

     angular.module('app')
        .service('tableService', [
        '$q',
      tableService
  ]);

  function tableService($q){
    var tableData = [
      {
        issue: 'Vinayak N',
        progress: 100,
       // status: 69,
        class: 'md-accent'
      }
    ];
}

i want to make a call to $http.get('http://localhost:5000/api/studentsList'); and assign the response.data to a local variable tableData in service.js

Body:
Try this:

angular.module('app')
        .service('tableService', [
        '$q','$http',
      tableService
  ]);

  function tableService($q, $http){
    var tableData = [
      {
        issue: 'Vinayak N',
        progress: 100,
       // status: 69,
        class: 'md-accent'
      }
    ];
    $http.get('http://localhost:5000/api/studentsList').then(function(result){
      tableData.data = result.data;
    });
}


问:
How to edit a bootstrap template
I want to use a bootstrap template for styling. i am using sonic template for styling. I have downloaded the zip file of sonic template.I want to add my text, button and images. How to modify the template.
http://www.templatemo.com/templates/templatemo_394_sonic/

答:
Here's a better idea than downloading from a Zip file.

Here’s a link to the site - https://www.scribd.com/document/332827979/Getting-Started-Bootstrap

```<code>The folks over at MaxCDN provide CDN support for Bootstrap's CSS and JavaScript. Just use these Bootstrap CDN links.

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
To enable screen reader support, press shortcut Ctrl+Alt+Z. To learn about keyboard shortcuts, press shortcut Ctrl+slash.
</code>```

Title: How to edit a bootstrap template

Body:
Here's a better idea than downloading from a Zip file.

Here’s a link to the site - https://www.scribd.com/document/332827979/Getting-Started-Bootstrap

The folks over at MaxCDN provide CDN support for Bootstrap's CSS and JavaScript. Just use these Bootstrap CDN links.

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
To enable screen reader support, press shortcut Ctrl+Alt+Z. To learn about keyboard shortcuts, press shortcut Ctrl+slash.


问:
Trying to get user input and cout a message expect when I enter a valid name it couts all of them
```<code>#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

    string gun = "";
    cout << "Enter The Gun You Would Like To Know The Type Of Ammo For: \n";
    getline(cin, gun);
    if (gun == "b95" || "B95" || "windchester" || "wind chester" || "Windchester" || "Wind Chester" || "longhorn" || "Long Horn" || "fal" || "FAL")
    {
        cout << "The Type Of Ammo For The " << gun << " Is 308 Windchester";
    }
    if (gun == "izh rifle" || "IZH Rifle" || "izhrifle" || "izh rifle" || "sks" || "SKS" || "akm" || "AKM")
    {
        cout << "The Type Of Ammo For The " << gun << " 7.62x39mm";
    }
    if (gun == "Mangnum" || "mangnum" || "Repetor" || "repetor")
    {
        cout << "The Type Of Ammo For The " << gun << ".357";
    }
    return 0;
}
</code>```

When the program is run for example i would enter sks and it would output all of the cout messages for example: The Type Of Ammo For The sks Is 308 WindchesterThe Type Of Ammo For The sks 7.62x39mmThe Type Of Ammo For The sks.357

答:
If conditions does not work this way.
If you want this, you have to write it like:

```<code> if (gun == "izh rifle" || gun ==  "IZH Rifle" || gun == "izhrifle" || gun ==  "izh rifle" ||
   gun ==  "sks" ||gun ==  "SKS" ||gun ==  "akm" ||gun ==  "AKM")
</code>```

Basically proper comparison requires two values to be compared, not just one.

Body:
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

    string gun = "";
    cout << "Enter The Gun You Would Like To Know The Type Of Ammo For: \n";
    getline(cin, gun);
    if (gun == "b95" || "B95" || "windchester" || "wind chester" || "Windchester" || "Wind Chester" || "longhorn" || "Long Horn" || "fal" || "FAL")
    {
        cout << "The Type Of Ammo For The " << gun << " Is 308 Windchester";
    }
    if (gun == "izh rifle" || "IZH Rifle" || "izhrifle" || "izh rifle" || "sks" || "SKS" || "akm" || "AKM")
    {
        cout << "The Type Of Ammo For The " << gun << " 7.62x39mm";
    }
    if (gun == "Mangnum" || "mangnum" || "Repetor" || "repetor")
    {
        cout << "The Type Of Ammo For The " << gun << ".357";
    }
    return 0;
}

When the program is run for example i would enter sks and it would output all of the cout messages for example: The Type Of Ammo For The sks Is 308 WindchesterThe Type Of Ammo For The sks 7.62x39mmThe Type Of Ammo For The sks.357

Body:
If conditions does not work this way.
If you want this, you have to write it like:

 if (gun == "izh rifle" || gun ==  "IZH Rifle" || gun == "izhrifle" || gun ==  "izh rifle" ||
   gun ==  "sks" ||gun ==  "SKS" ||gun ==  "akm" ||gun ==  "AKM")

Basically proper comparison requires two values to be compared, not just one.


问:
Stuck with linking SQL queries together
I'm trying get the MAX value of my subquery denoted as NUM_of_CUST column and to display it alongside with the artist name in tge main query so it would display like this:

ARTIST_NAME | NUM_of_CUST

```<code>Select A.Lastname ||''|| A.FirstName as Artist_Name from dhey.ARTIST A
LEFT JOIN
(SELECT * FROM(
SELECT COUNT(*) As Num_of_Customer From Dhey.CUSTOMER_ARTIST_INT CAI
GROUP BY ARTISTID
ORDER BY COUNT(*) desc) WHERE ROWNUM = 1) B on A.ArtistID = B.ArtistID;
</code>```

However SQL is throwing me B"."ARTISTID": invalid identifier exception.

Can anyone advise on this?

Thank you!

答:
I have solved my answer with this

```<code>SELECT A.lastname ||''||A.firstname as Artist_Name, COUNT(CAI.ARTISTID) AS NumberOfCustomers
FROM dhey.CUSTOMER_ARTIST_INT CAI
LEFT JOIN dhey.CUSTOMER C
ON CAI.CUSTOMERID = C.CUSTOMERID
LEFT JOIN dhey.ARTIST A
ON CAI.ARTISTID = A.ARTISTID
group by  A.lastname,  A.firstname
having count(*) = (select max(count(ArtistID))
                     from dhey.CUSTOMER_ARTIST_INT
                    group by ArtistID);
</code>```

Thank you all that helped!

Title: Stuck with linking SQL queries together

Body:
I'm trying get the MAX value of my subquery denoted as NUM_of_CUST column and to display it alongside with the artist name in tge main query so it would display like this:

ARTIST_NAME | NUM_of_CUST

Select A.Lastname ||''|| A.FirstName as Artist_Name from dhey.ARTIST A
LEFT JOIN
(SELECT * FROM(
SELECT COUNT(*) As Num_of_Customer From Dhey.CUSTOMER_ARTIST_INT CAI
GROUP BY ARTISTID
ORDER BY COUNT(*) desc) WHERE ROWNUM = 1) B on A.ArtistID = B.ArtistID;

However SQL is throwing me B"."ARTISTID": invalid identifier exception.

Can anyone advise on this?

Thank you!

Body:
I have solved my answer with this

SELECT A.lastname ||''||A.firstname as Artist_Name, COUNT(CAI.ARTISTID) AS NumberOfCustomers
FROM dhey.CUSTOMER_ARTIST_INT CAI
LEFT JOIN dhey.CUSTOMER C
ON CAI.CUSTOMERID = C.CUSTOMERID
LEFT JOIN dhey.ARTIST A
ON CAI.ARTISTID = A.ARTISTID
group by  A.lastname,  A.firstname
having count(*) = (select max(count(ArtistID))
                     from dhey.CUSTOMER_ARTIST_INT
                    group by ArtistID);

Thank you all that helped!


问:
name space comprehension in python with if and else
code first:

```<code># case01
def x():
    if False:
        #x2 = 22
        print x1
    else:
        print x2

if __name__ == '__main__':
    if False:
        x1 = 1
    else:
        x2 = 2
    x()
</code>```

case01's output:

```<code>2
</code>```

No problem! but when i uncomment #x2 = 22 in if False: block and rerun, it will got error:

```<code>---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-e36cb32b2c83> in <module>()
     11     else:
     12         x2 = 2
---> 13     x()

<ipython-input-4-e36cb32b2c83> in x()
      4         print x1
      5     else:
----> 6         print x2
      7
      8 if __name__ == '__main__':

UnboundLocalError: local variable 'x2' referenced before assignment
</code>```

As i see, if False: block will not excute, But why x2 = 22 take some effect to the script i worte?

My python version: 2.7.13

答:
Before start your script Python interpreter precompile it in a bytecode and when it sees "x2=22" in the function it puts x2 in __locals__ for that function and consider every ref to x2 as to local x2 not the global one. But when you start your function you don't assign any value to the local x2 but Python still looking only for the local one, so you get the error.

I hope I explained in understandable manner, sorry for my unperfect English )))

Body:
code first:

# case01
def x():
    if False:
        #x2 = 22
        print x1
    else:
        print x2

if __name__ == '__main__':
    if False:
        x1 = 1
    else:
        x2 = 2
    x()

case01's output:

2

No problem! but when i uncomment #x2 = 22 in if False: block and rerun, it will got error:

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-e36cb32b2c83> in <module>()
     11     else:
     12         x2 = 2
---> 13     x()

<ipython-input-4-e36cb32b2c83> in x()
      4         print x1
      5     else:
----> 6         print x2
      7
      8 if __name__ == '__main__':

UnboundLocalError: local variable 'x2' referenced before assignment

As i see, if False: block will not excute, But why x2 = 22 take some effect to the script i worte?

My python version: 2.7.13


问:
How get the current date and the timezone in numbers format
I want to print the current date in this format 2017/06/05 > Year/Month/Day
and next to it, the  current timezone in this format +3

I used this code

```<code>String DateToday  = DateFormat.getDateInstance().format(new Date());
String TZtoday = DateFormat.getTimeInstance().getTimeZone().getDisplayName();
txt.setText(DateToday + " | "+ TZtoday );
</code>```

But, it shows like this:

Jun 5, 2017 | Arabia Standard Time

I want it like this:

2017/06/05 | +3

答:
```<code>SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd | X");
System.out.println(sdf.format(new Date()));
</code>```

gets close, but the time zone is printed with a leading zero:

```<code>2017/06/05 | +03
</code>```

I suppose you could remove leading zeros from the time zone, if you need to:

```<code>SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat zone = new SimpleDateFormat("ZZZZZ"); // = +03:00
String tz = zone.format(new Date()).split(":")[0]
    .replaceAll("^(\\+|-)0", "$1"); // = +3
System.out.println(sdf.format(new Date()) + " | " + tz);
</code>```

which gives:

```<code>2017/06/05 | +3
</code>```

Body:
I want to print the current date in this format 2017/06/05 > Year/Month/Day
and next to it, the  current timezone in this format +3

I used this code

String DateToday  = DateFormat.getDateInstance().format(new Date());
String TZtoday = DateFormat.getTimeInstance().getTimeZone().getDisplayName();
txt.setText(DateToday + " | "+ TZtoday );

But, it shows like this:

Jun 5, 2017 | Arabia Standard Time

I want it like this:

2017/06/05 | +3

Body:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd | X");
System.out.println(sdf.format(new Date()));

gets close, but the time zone is printed with a leading zero:

2017/06/05 | +03

I suppose you could remove leading zeros from the time zone, if you need to:

SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat zone = new SimpleDateFormat("ZZZZZ"); // = +03:00
String tz = zone.format(new Date()).split(":")[0]
    .replaceAll("^(\\+|-)0", "$1"); // = +3
System.out.println(sdf.format(new Date()) + " | " + tz);

which gives:

2017/06/05 | +3


问:
Aspectj Pointcut expression not working for one method and working for another method in single class
I have written below code in controller.

For this controllerMethod method the aspectj Pointcut expression is working fine but for executeService method Aspect is not working.

```<code>@RequestMapping(value = "URL", method = RequestMethod.POST)
public ModelAndView controllerMethod(@ModelAttribute ModelAttribute reqModel, HttpServletRequest req, HttpServletResponse res) {

    try {
        response = executeService(param1, param2);

    } catch (Exception e) {

    }

    }
private ResponseObject executeService(String param1, String param2){
    //Code....
}
</code>```

I have written the aspect as below.

```<code>@Before("execution(* com.*.*.Controller.executeService(..))")
public void logBefore(JoinPoint joinPoint) {
    logger.info("Before aspect: " + joinPoint.getSignature().getName());
}
</code>```

Can you please let me know where is the issues. I need to execute aspect before calling executeService method.

答:
Because the AOP not intercept internal call ,so you can add a self-controller field,and call the internal method by self.method(...).
Following code:

```<code>@Controller
public class ExampleController{

    @Autowired
    private ExampleController self;

    @RequestMapping(value = "URL", method = RequestMethod.POST)
    public ModelAndView controllerMethod(@ModelAttribute ModelAttribute reqModel, HttpServletRequest req, HttpServletResponse res) {

        try {
            response = self.executeService(param1, param2);

        } catch (Exception e) {

        }

    }
    public ResponseObject executeService(String param1, String param2){
        //Code....
    }
}
</code>```

Body:
I have written below code in controller.

For this controllerMethod method the aspectj Pointcut expression is working fine but for executeService method Aspect is not working.

@RequestMapping(value = "URL", method = RequestMethod.POST)
public ModelAndView controllerMethod(@ModelAttribute ModelAttribute reqModel, HttpServletRequest req, HttpServletResponse res) {

    try {
        response = executeService(param1, param2);

    } catch (Exception e) {

    }

    }
private ResponseObject executeService(String param1, String param2){
    //Code....
}

I have written the aspect as below.

@Before("execution(* com.*.*.Controller.executeService(..))")
public void logBefore(JoinPoint joinPoint) {
    logger.info("Before aspect: " + joinPoint.getSignature().getName());
}

Can you please let me know where is the issues. I need to execute aspect before calling executeService method.

Body:
Because the AOP not intercept internal call ,so you can add a self-controller field,and call the internal method by self.method(...).
Following code:

@Controller
public class ExampleController{

    @Autowired
    private ExampleController self;

    @RequestMapping(value = "URL", method = RequestMethod.POST)
    public ModelAndView controllerMethod(@ModelAttribute ModelAttribute reqModel, HttpServletRequest req, HttpServletResponse res) {

        try {
            response = self.executeService(param1, param2);

        } catch (Exception e) {

        }

    }
    public ResponseObject executeService(String param1, String param2){
        //Code....
    }
}


问:
How to delete folder from drawable folder of resource?
I created by mistake a folder inside /app/src/main/res/drawable-v21/

Now it's giving me this error
Error: The file name must end with .xml or .png
, but I'm not seeing that folder inside the directory.

How can i delete that folder?

答:
[Right click on the drawable folder and select Show in Explorer]

[Here you can delete the error causing folders][2]


问:
BigQuery - set "" as Null
I get csv files where string null value expressed as "",
when I load the file to BigQuery the value of the field is empty string
and not Null.

Is there a way to set BigQuery to see "" as Null value?

答:
Are you using the command line tool that comes with the Google Cloud SDK (https://cloud.google.com/sdk/downloads)?  If so, check out bq help load to see the parameters on the load command.  One of the flags that you can pass is --null_marker.

I haven't verified whether or not this flag supports the empty string, but if Google Cloud supported it, it would be there.

Title: BigQuery - set "" as Null


问:
Unresolved requirement: Import-Package: com.fasterxml.jackson.annotation; version="[2.8.0,3.0.0)"
IN my Liferay 7 project When i tried to add below dependency in build.gradle getting error

compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.8.8'

Err:

org.osgi.framework.BundleException: Could not resolve module:
  Unresolved requirement: Import-Package: com.fasterxml.jackson.annotation; version="[2.8.0,3.0.0)"

答: Download jackson-annotations-2.8.8.jar, jackson-core-2.8.8.jar & jackson-databind-2.8.8.jar bundles from central repository and put them in liferay-home\deploy folder. Check if they are installed properly in GoGo shell.</p>


答:
You can't write boolean expressions like this in C++. Every side of boolean expression is a boolean, so in your case all three if are always true because non-empty string is a true in boolean expression.
Please read about boolean expressions and write smthing like
If (input == "str1" || input == "str2" etc. )</p>

Title: Trying to get user input and cout a message expect when I enter a valid name it couts all of them


问:
How to automatically add user account AND password with a Bash script?
I need to have the ability to create user accounts on my Linux (Fedora 10) and automatically assign a password via a bash script(or otherwise, if need be).

It's easy to create the user via Bash e.g.:

```<code>[whoever@server ]#  /usr/sbin/useradd newuser
</code>```

Is it possible to assign a password in Bash, something functionally similar to this, but automatically:

```<code>[whoever@server ]# passwd newuser
Changing password for user testpass.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
[whoever@server ]#
</code>```

答:
Single liner to create a sudo user with home directory and password.</p>

```<code>useradd -m -p $(openssl passwd -1 ${PASSWORD}) -s /bin/bash -G sudo ${USERNAME}
</code>```

Body:
I need to have the ability to create user accounts on my Linux (Fedora 10) and automatically assign a password via a bash script(or otherwise, if need be).

It's easy to create the user via Bash e.g.:

[whoever@server ]#  /usr/sbin/useradd newuser

Is it possible to assign a password in Bash, something functionally similar to this, but automatically:

[whoever@server ]# passwd newuser
Changing password for user testpass.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
[whoever@server ]#

Body:
Single liner to create a sudo user with home directory and password.

useradd -m -p $(openssl passwd -1 ${PASSWORD}) -s /bin/bash -G sudo ${USERNAME}


问:
Objective-C: UIImageWriteToSavedPhotosAlbum() + asynchronous = problems
Update: This problem was also reported here, with a more detailed treatment of the cause:

UIImageWriteToSavedPhotosAlbum saves only 5 image out of 10. Why?

In my case as well, the error was: "Write busy" - this seems to be an issue related to device speed. There is probably some solution that involves manually handling threading or similar - but, inspired by Tommy's answer below, I serialized the saving of images, and that works around the problem.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Situation:

I'm trying to save a large-ish collection of images to the camera roll using a for-loop (number of images depends on user input - may be 1, 2, 3, or theoretically hundreds). Images are pointed to by an NSSet (though I could just as easily do an NSArray), and the NSSet is set to nil after the for-loop completes.

I'm using UIImageWriteToSavedPhotosAlbum() to save out the images on a detached thread (using NSThread's detachNewThreadSelector:toTarget:withObject: class method), and starting a UIActivityIndicator spinner on the main thread.

Problem:

When I attempt to save out more than ~5, any image after the ~5th will output this error in the log:

*** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL

For example, let's say I exported 9 images. The for-loop will run through all 9 images (confirmed by NSLogging), but I'll get around 4 iterations of the error above (and only 5 images saved to the camera roll).

If I add a breakpoint in the loop and wait a second or two in between each iteration, however, they are all saved correctly without complaint. So..

Theory:

Based on my logs and observations, UIImageWriteToSavedPhotosAlbum() is clearly running asynchronously and is somehow 'too slow' to keep up with my application.

Is there a simple way to force it to run synchronously (ideally on the main thread)? I've been experimenting with adding reference counts to the images I'm trying to save out, but (1) this feels hacky, and (2) I haven't solved the problem regardless.

Any advice would be great. Thanks!

答:
In this Code Work Save image :</p>

```<code>  UIImageWriteToSavedPhotosAlbum([self screenshot], nil, nil, nil);

UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Save" message:@"Photo saved to album" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
</code>```

Body:
In this Code Work Save image :

  UIImageWriteToSavedPhotosAlbum([self screenshot], nil, nil, nil);

UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Save" message:@"Photo saved to album" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];


问:
Check and uncheck checkboxes in Asp.net GridView using jQuery
iam using checkboxes in gridview. i want to check and uncheck checkboxes in gridview using jquery. i tried this with live method. it's working for the first page in the gridview but not in the page index changing event.</p>

```<code> $(document).ready(function () {

        var checkBoxSelector = '#<%=grv_ClientList.ClientID%> input[id*="chck_itemSelect"]:checkbox';

        //header checkbox
        $('[id$=chck_headSelect]').live("click", function () {

            if ($(this).is(":checked")) {

                $(checkBoxSelector).attr('checked', true);

            }
            else {

                $(checkBoxSelector).attr('checked', false);
            }
        });

    });
</code>```

答:
Please go through the sample code.

```<code><script src="jquery-1.4.1.js" type="text/javascript"></script>

<script src="jquery-1.4.1-vsdoc.js" type="text/javascript"></script>

<script type="text/javascript" >

    $(document).ready(function() {

    var ab = 0 ;

        $("[id$=myCheck]").click(function() {

            if (ab == 0) {

                $('#<%=GridView1.ClientID %> >tbody >tr >td:first-child > input:checkbox').attr('checked', true);

                ab = 1;

            }

            else {

                $('#<%=GridView1.ClientID %> >tbody >tr >td:first-child > input:checkbox').attr('checked', false);

              ab =0 ;

            }

        })

    })

</script>
</code>```

```<code>        <Columns>

            <asp:TemplateField>

            <HeaderTemplate>

            <asp:CheckBox ID="myCheck" runat="server"   />

            </HeaderTemplate>

            <ItemTemplate><asp:CheckBox ID="urCheck" runat="server" /></ItemTemplate>

            </asp:TemplateField>

            <asp:BoundField DataField="UnitName" HeaderText="Unit Name" />

            <asp:BoundField DataField="Description" HeaderText="Description" />

            <asp:TemplateField HeaderText="Status">

            <ItemTemplate>

            <asp:DropDownList ID="AttendId" runat="server"    >

            <asp:ListItem  style="Color:Green" Text="Present" Value="0"></asp:ListItem>

            <asp:ListItem  style="Color:Red" Text="Absent" Value="1"></asp:ListItem>

            <asp:ListItem  style="Color:Blue" Text="Leave" Value="2"></asp:ListItem>

            </asp:DropDownList>

            </ItemTemplate>

            </asp:TemplateField>

        </Columns>

    </asp:GridView>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
iam using checkboxes in gridview. i want to check and uncheck checkboxes in gridview using jquery. i tried this with live method. it's working for the first page in the gridview but not in the page index changing event.

 $(document).ready(function () {

        var checkBoxSelector = '#<%=grv_ClientList.ClientID%> input[id*="chck_itemSelect"]:checkbox';

        //header checkbox
        $('[id$=chck_headSelect]').live("click", function () {

            if ($(this).is(":checked")) {

                $(checkBoxSelector).attr('checked', true);

            }
            else {

                $(checkBoxSelector).attr('checked', false);
            }
        });

    });

Body:
Please go through the sample code.

<script src="jquery-1.4.1.js" type="text/javascript"></script>

<script src="jquery-1.4.1-vsdoc.js" type="text/javascript"></script>

<script type="text/javascript" >

    $(document).ready(function() {

    var ab = 0 ;

        $("[id$=myCheck]").click(function() {

            if (ab == 0) {

                $('#<%=GridView1.ClientID %> >tbody >tr >td:first-child > input:checkbox').attr('checked', true);

                ab = 1;

            }

            else {

                $('#<%=GridView1.ClientID %> >tbody >tr >td:first-child > input:checkbox').attr('checked', false);

              ab =0 ;

            }

        })

    })

</script>

        <Columns>

            <asp:TemplateField>

            <HeaderTemplate>

            <asp:CheckBox ID="myCheck" runat="server"   />

            </HeaderTemplate>

            <ItemTemplate><asp:CheckBox ID="urCheck" runat="server" /></ItemTemplate>

            </asp:TemplateField>

            <asp:BoundField DataField="UnitName" HeaderText="Unit Name" />

            <asp:BoundField DataField="Description" HeaderText="Description" />

            <asp:TemplateField HeaderText="Status">

            <ItemTemplate>

            <asp:DropDownList ID="AttendId" runat="server"    >

            <asp:ListItem  style="Color:Green" Text="Present" Value="0"></asp:ListItem>

            <asp:ListItem  style="Color:Red" Text="Absent" Value="1"></asp:ListItem>

            <asp:ListItem  style="Color:Blue" Text="Leave" Value="2"></asp:ListItem>

            </asp:DropDownList>

            </ItemTemplate>

            </asp:TemplateField>

        </Columns>

    </asp:GridView>


问:
How to add key with unique random value in HTTP Request defaults in Jmeter
I am trying to apply load  sample request is like

http://54.174.110.64:8080/adserver/html5/inwapads/?adFormat=preappvideo&ak=O4DCX2&version=1.0&adu=5&cb=1494853894218&output=vast&priority=1&size=[vdo_adSize]&pageURL=http://qa.vdopia.com/qa/Ruchi/ssp_preroll1.html?0.7888977&domain=vdopia.com&refURL=&category=[CATEGORY]&siteName=vdopia&displayManager=Vdopia-SPP-Web&di=[COOKIE_ID]&dif=fpcm&sex=[GENDER]&age=[AGE];ipAddress=203.122.9.130;di=abcdefghijklmn

I have single request, what I want is that same request should have unique di (last key in query param). Nothing else I want to change.

My test is based on unique di in request keeping other parameters constant.

答:
I would suggest using __UUID() function which will generate a GUID structure which is unique according to the underlying algorithm each time being called.

If you don't like dashes you can remove them via __groovy() function like

```<code>${__groovy("${__UUID}".replaceAll("-"\, ""),)}
</code>```

Demo:

See Apache JMeter Functions - An Introduction to get started with JMeter Functions.

Body:
I would suggest using __UUID() function which will generate a GUID structure which is unique according to the underlying algorithm each time being called.

If you don't like dashes you can remove them via __groovy() function like

${__groovy("${__UUID}".replaceAll("-"\, ""),)}

Demo:

See Apache JMeter Functions - An Introduction to get started with JMeter Functions.


问:
upload multiple files which shows attributes say file size,file Name, and also remove option and cancel etc
I came across this requirement, in which I need to upload multiple file with showing other attributes like showing file names , file size and also when someone click on remove option that particular file should be removed as well.

I thought to post this question as a reference for other, just to purpose of help someone

答:
To achieve this just proceed as bellow</p>

```<code> var app=angular.module("MyApp",[]);
            app.directive('fileUpload', function () {
                return {
                    scope: true,        //create a new scope
                    link: function (scope, el, attrs) {
                        el.bind('change', function (event) {
                            var files = event.target.files;
                            //iterate files since 'multiple' may be specified on the element
                            for (var i = 0;i<files.length;i++) {
                                //emit event upward
                                scope.$emit("fileSelected", { file: files[i] });
                            }
                        });
                    }
                };
            });

            app.controller("MyCtrl",function($scope, $http) {

                //a simple model to bind to and send to the server
                $scope.model = {
                    name: "",
                    comments: ""
                };

                //an array of files selected
                $scope.files = [];

                //listen for the file selected event
                $scope.$on("fileSelected", function (event, args) {
                    $scope.$apply(function () {
                        //add the file object to the scope's files collection
                        $scope.files.push(args.file);
                    });
                });

                $scope.remove=function(file,files){
                console.log("size: "+($scope.files).length);
                if(files.indexOf(file)!=-1){
            files.splice(files.indexOf(file),1);
                }
                }

                $scope.validate=function(size,file,files){
                var status=false;
                console.log("size @@: "+($scope.files).length);
                if(size >2048){

            if(files.indexOf(file)!=-1){
            files.splice(files.indexOf(file),1);
            return true;
                }
                }

                if(files.length>5){

                if(files.indexOf(file)!=-1){
            files.splice(files.indexOf(file),1);
            return false;
                }
                }

                }

                $scope.cancel=function(files){
                console.log("Cancelled");
                files.length=0;
                }
            });
</code>```

Body:
To achieve this just proceed as bellow

 var app=angular.module("MyApp",[]);
            app.directive('fileUpload', function () {
                return {
                    scope: true,        //create a new scope
                    link: function (scope, el, attrs) {
                        el.bind('change', function (event) {
                            var files = event.target.files;
                            //iterate files since 'multiple' may be specified on the element
                            for (var i = 0;i<files.length;i++) {
                                //emit event upward
                                scope.$emit("fileSelected", { file: files[i] });
                            }
                        });
                    }
                };
            });

            app.controller("MyCtrl",function($scope, $http) {

                //a simple model to bind to and send to the server
                $scope.model = {
                    name: "",
                    comments: ""
                };

                //an array of files selected
                $scope.files = [];

                //listen for the file selected event
                $scope.$on("fileSelected", function (event, args) {
                    $scope.$apply(function () {
                        //add the file object to the scope's files collection
                        $scope.files.push(args.file);
                    });
                });

                $scope.remove=function(file,files){
                console.log("size: "+($scope.files).length);
                if(files.indexOf(file)!=-1){
            files.splice(files.indexOf(file),1);
                }
                }

                $scope.validate=function(size,file,files){
                var status=false;
                console.log("size @@: "+($scope.files).length);
                if(size >2048){

            if(files.indexOf(file)!=-1){
            files.splice(files.indexOf(file),1);
            return true;
                }
                }

                if(files.length>5){

                if(files.indexOf(file)!=-1){
            files.splice(files.indexOf(file),1);
            return false;
                }
                }

                }

                $scope.cancel=function(files){
                console.log("Cancelled");
                files.length=0;
                }
            });


问:
How to let cscope use absolute path in cscope.out file?
Everytime after load a cscope.out in Vim, I need to change Vim's "pwd" to the same directory as cscope.out file is under, which might be due to that cscope use relative path when generating tag file. So if there is a way to force cscope to use absolute path in its tag file - cscope.out, then it will be regardless of whether the pwd of your Vim session is the same as the directory that cscope.out file is under.</p>

答:
@Aaron H. is right.

For my configuration I used the cscope_maps.vim plugin and modified the following lines:

```<code>  40     " add any cscope database in current directory
  41     if filereadable("/usr/project/cscope.out")
  42         cs add /usr/project/cscope.out /usr/project
  43     " else add the database pointed to by environment variable
  44     elseif $CSCOPE_DB != ""
  45         cs add $CSCOPE_DB
  46     endif
</code>```

Where "/usr/project" is the location of the cscope.out file and the absolute path I want to use.

Body:
@Aaron H. is right.

For my configuration I used the cscope_maps.vim plugin and modified the following lines:

  40     " add any cscope database in current directory
  41     if filereadable("/usr/project/cscope.out")
  42         cs add /usr/project/cscope.out /usr/project
  43     " else add the database pointed to by environment variable
  44     elseif $CSCOPE_DB != ""
  45         cs add $CSCOPE_DB
  46     endif

Where "/usr/project" is the location of the cscope.out file and the absolute path I want to use.


问:
Html/Css dynamic centering
what I want to achieve is the following,
I have 6 divs in the bottom which are aligned horizontal and have the rest of the screen size as equal margin left and right.

Now when the screen's width is to small to display them in one row, I want to display them in two rows (with 3 divs each). All of this is working right now, but when it becomes a two row layout the equal margin left and right is gone and they clip at the left of the screen.

Am I missing something ?

.container{
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container{
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container{
  display: inline-block;
}

.group-container{
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element{
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="center-container">
      <div class="inner-container">
          <div class="group-container">
              <div class="element"></div>
              <div class="element"></div>
              <div class="element"></div>
          </div>
          <div class="group-container">
              <div class="element"></div>
              <div class="element"></div>
              <div class="element"></div>
          </div>
      </div>
  </div>
</div></code>```

JsFiddle example of working one row layout: https://jsfiddle.net/7ef7xLhu/

JsFiddle example of non working two row layout: https://jsfiddle.net/9oc19oky/

Thank you in advance :)

答:
Added text-align: center; to .inner-container

.container {
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container {
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container {
  display: inline-block;
  text-align: center;
}

.group-container {
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element {
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="center-container">
    <div class="inner-container">
      <div class="group-container">
        <div class="element"></div>
        <div class="element"></div>
        <div class="element"></div>
      </div>
      <div class="group-container">
        <div class="element"></div>
        <div class="element"></div>
        <div class="element"></div>
      </div>
    </div>
  </div>
</div></code>```

Title: Html/Css dynamic centering

Body:
what I want to achieve is the following,
I have 6 divs in the bottom which are aligned horizontal and have the rest of the screen size as equal margin left and right.

Now when the screen's width is to small to display them in one row, I want to display them in two rows (with 3 divs each). All of this is working right now, but when it becomes a two row layout the equal margin left and right is gone and they clip at the left of the screen.

Am I missing something ?

.container{
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container{
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container{
  display: inline-block;
}

.group-container{
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element{
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}

JsFiddle example of working one row layout: https://jsfiddle.net/7ef7xLhu/

JsFiddle example of non working two row layout: https://jsfiddle.net/9oc19oky/

Thank you in advance :)

Body:
Added text-align: center; to .inner-container

.container {
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container {
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container {
  display: inline-block;
  text-align: center;
}

.group-container {
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element {
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}

<div class="container">
  <div class="center-container">
    <div class="inner-container">
      <div class="group-container">
        <div class="element"></div>
        <div class="element"></div>
        <div class="element"></div>
      </div>
      <div class="group-container">
        <div class="element"></div>
        <div class="element"></div>
        <div class="element"></div>
      </div>
    </div>
  </div>
</div>


问:
How do i unit test a class that uses IoC container classes
I am using Autofac in my project,but i am unable to do a unit test on one particular class.

Consider the following Scenario :

```<code>//Class to be tested
public Class A
{
  private SomeAutoFacClass B;

  public void DoSomething()
  {
    B = scope.Resolve<ClassName>();// Resolve the object needed
    // Do something with instance B
  }
}

// Test class
public Class ATest
{
  private A a;

  [test]
  public void TestMethod()
  {
    a.DoSomething();//*This method causes a null reference exception as it tries to resolve the objects*
  }
}
</code>```

In the code above,i am not able to unit test case due to the dependency injection which is only specific to that particular class.
how do i solve this? I also tried creating a autofaccontainer using Moq.
But that too fails.

答:
The reason you are not able to test your class is because your class takes a dependency on your DI Container. This is an implementation of the Service Locator anti-pattern. It's an anti-pattern because:

the problem with Service Locator is that it hides a class' dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.

Instead, design your classes around

Constructor Injection in case the class is a component (a class that contains the applications behavior), where you inject the dependencies that a class directly needs through the constructor

Method Injection when the class is a data-centric object like an entity, which means the dependency is supplied to a the public method of such class, where the consuming class only uses that dependency, but not stores it.

Components are built-up by your DI Container and are registered in your Composition Root, while data-centric objects are newed up in code outside the Composition Root. In that case you need to pass along a dependency to an already constructed object.

In case you build and test a component, your code would typically look as follows:

```<code>public class ComponentA
{
    private ClassName b;

    public ComponentA(ClassName b)
    {
        this.b = b;
    }

    public void DoSomething()
    {
        // Do something with instance B
    }
}

// Test class
public Class ATest
{
    [test]
    public void TestMethod()
    {
        // Arrange
        B b = new FakeB();

        var a = new ComponentA(b);

        // Act
        a.DoSomething();

        // Assert
        // Check whether be was invoked correctly.
    }
}
</code>```

In case you build and test a data-centric object that requires a dependency for one of its operations, your code would typically look as follows:

```<code>public class EntityA
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void DoSomething(ClassName b)
    {
        // Do something with instance B
    }
}

// Test class
public Class ATest
{
    [test]
    public void TestMethod()
    {
        // Arrange
        B b = new FakeB();

        var a = new EntityA { Name = "Bert", Age = 56 };

        // Act
        a.DoSomething(b);

        // Assert
        // Check whether be was invoked correctly.
    }
}
</code>```

So to answer your initial question:

How do i unit test a class that uses IoC container classes

You don't. Your application code should not depend on the DI Container, because that leads to all kinds of complications such as being hard to test.

Body:
I am using Autofac in my project,but i am unable to do a unit test on one particular class.

Consider the following Scenario :

//Class to be tested
public Class A
{
  private SomeAutoFacClass B;

  public void DoSomething()
  {
    B = scope.Resolve<ClassName>();// Resolve the object needed
    // Do something with instance B
  }
}

// Test class
public Class ATest
{
  private A a;

  [test]
  public void TestMethod()
  {
    a.DoSomething();//*This method causes a null reference exception as it tries to resolve the objects*
  }
}

In the code above,i am not able to unit test case due to the dependency injection which is only specific to that particular class.
how do i solve this? I also tried creating a autofaccontainer using Moq.
But that too fails.

Body:
The reason you are not able to test your class is because your class takes a dependency on your DI Container. This is an implementation of the Service Locator anti-pattern. It's an anti-pattern because:

the problem with Service Locator is that it hides a class' dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.

Instead, design your classes around

Constructor Injection in case the class is a component (a class that contains the applications behavior), where you inject the dependencies that a class directly needs through the constructor

Method Injection when the class is a data-centric object like an entity, which means the dependency is supplied to a the public method of such class, where the consuming class only uses that dependency, but not stores it.

Components are built-up by your DI Container and are registered in your Composition Root, while data-centric objects are newed up in code outside the Composition Root. In that case you need to pass along a dependency to an already constructed object.

In case you build and test a component, your code would typically look as follows:

public class ComponentA
{
    private ClassName b;

    public ComponentA(ClassName b)
    {
        this.b = b;
    }

    public void DoSomething()
    {
        // Do something with instance B
    }
}

// Test class
public Class ATest
{
    [test]
    public void TestMethod()
    {
        // Arrange
        B b = new FakeB();

        var a = new ComponentA(b);

        // Act
        a.DoSomething();

        // Assert
        // Check whether be was invoked correctly.
    }
}

In case you build and test a data-centric object that requires a dependency for one of its operations, your code would typically look as follows:

public class EntityA
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void DoSomething(ClassName b)
    {
        // Do something with instance B
    }
}

// Test class
public Class ATest
{
    [test]
    public void TestMethod()
    {
        // Arrange
        B b = new FakeB();

        var a = new EntityA { Name = "Bert", Age = 56 };

        // Act
        a.DoSomething(b);

        // Assert
        // Check whether be was invoked correctly.
    }
}

So to answer your initial question:

How do i unit test a class that uses IoC container classes

You don't. Your application code should not depend on the DI Container, because that leads to all kinds of complications such as being hard to test.


问:
Android: is there a way to listen to fragment's enter/exit animations inside the fragment itself?
I have an activity and two fragments implementing master-detail flow.

when the detail fragment enters, it is animated to slide in from right to left.
the fragment also contains a FloatingActionMenu (https://github.com/Clans/FloatingActionButton). Now I want to animate this fab after the enter and exit animation of detail fragment.

what I have done till now is:
hide the fab in fragments onCreate()
in onStart() added a postDelay() to show that fab with animation (I know this is not good)

So I wanted to know if there is a way to attach a listener to animator that is performing fragment enter and exit transition animations, so that I can animate the fab accordingly

答:
Override public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) method. It called when a fragment loads an animation

int transit - transition type, see this.

boolean enter - true if animation is enterAnimation

int nextAnim - the resource ID of the animation

For example:

```<code>@Override
public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
    Animator animator = AnimatorInflater.loadAnimator(getActivity(), nextAnim);
    if (nextAnim == R.animator.your_animator){
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

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

Body:
Override public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) method. It called when a fragment loads an animation

int transit - transition type, see this.

boolean enter - true if animation is enterAnimation

int nextAnim - the resource ID of the animation

For example:

@Override
public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
    Animator animator = AnimatorInflater.loadAnimator(getActivity(), nextAnim);
    if (nextAnim == R.animator.your_animator){
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }
    return animator;
}