问:
AngularJS give me rounded big number
I use my AngularJS application to display Twitter account, and big account ID give me a rounded number such as :

748598350317031424 give me 748598350317031400 when displayed on page with ng-repeat.

Have you got an idea ?

答:
This occurs due to javascript JSON roundup. When id is set to 748598350317031424, it actually assigned to the nearest representable double-precision value, which is 748598350317031400. Because Numbers in ECMAScript are internally represented double-precision floating point.

check this for the details.

I once stuck in a situation like that and what I did was something that I'm not proud of. But you can send XMLHttpRequest that responseType='text'(check this) which will return the whole json response as string. now since the id comes as string value json roundup will not occur. then you can split the json by property name and get the value.  As i said before this is not the best way to do this. But I'm hoping this will useful to someone.

Title: AngularJS give me rounded big number


来源: stackexchange

问:
Converting XML response to POJO using SimpleXMLConverter in Retrofit
I am stuck at this error below.
This is the XML response

```<code><rss xmlns:content="http://purl.org/rss/1.0/modules/content/"     xmlns:dcterms="http://purl.org/dc/terms/"  xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        <title>SnagFilms Recent Additions</title>
        <item>
            <media:title>Sink or Swim - Trailer</media:title>
            <title>Sink or Swim - Trailer</title>
            <media:description> Jon Bowermaster's documentary on a learn-to-swim camp for third graders and their moms on the island-nation of the Maldives
            </media:description>
            <media:credit role="Director" scheme="urn:ebu">Jon Bowermaster</media:credit>
            <media:thumbnail type="landscape" url="http://snagfilms-a.akamaihd.net/sinkorswim-video.jpg"/>
            <media:content duration="117" height="323"  width="500"/>
            <media:rights status="official"/>
            <media:player height="323" url="http://embed.snagfilms.com/embed/player?filmId=00000158-b20c-d8f9-affd-b32ce8700000" width="500"/>
         </item>
    </channel>
</rss>
</code>```

This is my Rest Call code using an observable

```<code>rx.Observable<Rss> videosObservable = RetrofitHelper.createListObs();
    videosObservable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Rss>() {
                @Override
                public void onCompleted() {

                    Log.d(TAG, "onCompleted: ");
                }

                @Override
                public void onError(Throwable e) {
                    Log.d(TAG, "onError: " + e.toString());
                }

                @Override
                public void onNext(Rss rss) {
                    Log.d(TAG, "onNext: " );

                }
            });
</code>```

This is the error I am getting

```<code>onError: java.lang.RuntimeException: org.simpleframework.xml.core.ElementException: Element 'item' does not have a match in class com.example.singh.xmlParser.model.Channel at line 12
</code>```

My Rss class

```<code>@Root(strict = false)
public class Rss {

public Channel getChannel() {
    return channel;
}
@Element
public Channel channel;

}
</code>```

My Channel class

```<code>@Element
public class Channel {

@Element(name = "title")
String title;

@ElementList
List<Item> items;

public List getItems(){
    return items;
}

}
</code>```

I need help making proper POJOs for XML in Java. I would really appreciate if someone could make all POJOs for the given format. Response link http://www.snagfilms.com/feeds/. Converter documentation http://simple.sourceforge.net/home.php

答:
Your list of items is an inline list within the channel object. You have to specify that in your annotaion:

```<code>@ElementList(inline=true)
List<Item> items;
</code>```

Check the official documentation.

ContentLicense: CC BY-SA 3.0

Body:
I am stuck at this error below.
This is the XML response

<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"     xmlns:dcterms="http://purl.org/dc/terms/"  xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        <title>SnagFilms Recent Additions</title>
        <item>
            <media:title>Sink or Swim - Trailer</media:title>
            <title>Sink or Swim - Trailer</title>
            <media:description> Jon Bowermaster's documentary on a learn-to-swim camp for third graders and their moms on the island-nation of the Maldives
            </media:description>
            <media:credit role="Director" scheme="urn:ebu">Jon Bowermaster</media:credit>
            <media:thumbnail type="landscape" url="http://snagfilms-a.akamaihd.net/sinkorswim-video.jpg"/>
            <media:content duration="117" height="323"  width="500"/>
            <media:rights status="official"/>
            <media:player height="323" url="http://embed.snagfilms.com/embed/player?filmId=00000158-b20c-d8f9-affd-b32ce8700000" width="500"/>
         </item>
    </channel>
</rss>

This is my Rest Call code using an observable

rx.Observable<Rss> videosObservable = RetrofitHelper.createListObs();
    videosObservable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Rss>() {
                @Override
                public void onCompleted() {

                    Log.d(TAG, "onCompleted: ");
                }

                @Override
                public void onError(Throwable e) {
                    Log.d(TAG, "onError: " + e.toString());
                }

                @Override
                public void onNext(Rss rss) {
                    Log.d(TAG, "onNext: " );

                }
            });

This is the error I am getting

onError: java.lang.RuntimeException: org.simpleframework.xml.core.ElementException: Element 'item' does not have a match in class com.example.singh.xmlParser.model.Channel at line 12

My Rss class

@Root(strict = false)
public class Rss {

public Channel getChannel() {
    return channel;
}
@Element
public Channel channel;

}

My Channel class

@Element
public class Channel {

@Element(name = "title")
String title;

@ElementList
List<Item> items;

public List getItems(){
    return items;
}

}

I need help making proper POJOs for XML in Java. I would really appreciate if someone could make all POJOs for the given format. Response link http://www.snagfilms.com/feeds/. Converter documentation http://simple.sourceforge.net/home.php

Body:
Your list of items is an inline list within the channel object. You have to specify that in your annotaion:

@ElementList(inline=true)
List<Item> items;

Check the official documentation.


问:
How to set dynamic route in codeigniter from database?
In my routes.php file I have added the following code for routing:

```<code>$route['report/:num'] = "home/reportcard/$1";
</code>```

Here is my controller code:

```<code><?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Home extends CI_Controller
    {

        function __construct() {
            parent::__construct();

        if(empty($this->session->userdata('id_user'))){
            $this->session->set_flashdata('flash_data', 'You cannot access');
                    redirect('login');
        }
        }
        public function index(){
            $this->load->model("item_model");
            $data['records'] = $this->item_model->getAllItems();
            $this->load->view('home',$data);
        }

       function reportcard($id){
            $this->load->model("item_model");
            $data['report'] = $this->item_model->getReport($id);
            $this->load->view('report', $data);
        }

        function logout(){
            $data=['id_user','username'];
            $this->session->unset_userdata($data);
            redirect('login');

        }
    }
</code>```

Here is my model code:

```<code><?php
    class Item_model extends CI_Model
    {
        function getAllItems()
        {
            $this->load->database();
            $q = $this->db->get("item");
            if($q->num_rows() > 0)
            {
                return $q->result();
            }
            return array();
        }

        public function getReport($id){
            $this->db->select('*');
            $this->db->from('item');
            $this->db->where('item.id', $id);
            $query = $this->db->get();
            if($query->num_rows() > 0)
                return $data->result();
        }

}
?>
</code>```

this is the code of view. I just print the array in my report_view for testing purpose:

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
print_r($report);
?>
</code>```

this is my home_view code:

```<code><div class="row">
                <ul class="home-grid">
                    <?php foreach ($query->result() as $row): ?>
                    <li>
                        <a  href="<?php echo base_url() ?>report/<?=$row->item ?>/<?=$row->id ?>" class="btn btn-lg btn-warning view-report"><span class="glyphicon glyphicon-list-alt"></span> <br/>
                        <?=$row->item ?><br/>
                         <small>Click here for see report</small>
                        </a>
                    </li>
                    <?php endforeach; ?>
                </ul>
</code>```

I have tried multiple times to view the array. But failed to get array. How can I load the view? When I click my items from home, it will create a url like http://localhost/super_shop_register/report/1

But didn't show any data. Show "Object not found!". Here is the image of my view:
After Clicking item, it will show like this:

How can I solve this?

答:
Simple you can try this

```<code>$route['report/(:num)'] = "home/reportcard";
</code>```

then you can get ID with below method in controller and nothing pass in function reportcard argument

```<code>$report_id = $this->uri->segment(2);
</code>```

Body:
In my routes.php file I have added the following code for routing:

$route['report/:num'] = "home/reportcard/$1";

Here is my controller code:

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Home extends CI_Controller
    {

        function __construct() {
            parent::__construct();

        if(empty($this->session->userdata('id_user'))){
            $this->session->set_flashdata('flash_data', 'You cannot access');
                    redirect('login');
        }
        }
        public function index(){
            $this->load->model("item_model");
            $data['records'] = $this->item_model->getAllItems();
            $this->load->view('home',$data);
        }

       function reportcard($id){
            $this->load->model("item_model");
            $data['report'] = $this->item_model->getReport($id);
            $this->load->view('report', $data);
        }

        function logout(){
            $data=['id_user','username'];
            $this->session->unset_userdata($data);
            redirect('login');

        }
    }

Here is my model code:

<?php
    class Item_model extends CI_Model
    {
        function getAllItems()
        {
            $this->load->database();
            $q = $this->db->get("item");
            if($q->num_rows() > 0)
            {
                return $q->result();
            }
            return array();
        }

        public function getReport($id){
            $this->db->select('*');
            $this->db->from('item');
            $this->db->where('item.id', $id);
            $query = $this->db->get();
            if($query->num_rows() > 0)
                return $data->result();
        }

}
?>

this is the code of view. I just print the array in my report_view for testing purpose:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
print_r($report);
?>

this is my home_view code:

                    <?php foreach ($query->result() as $row): ?>

                        <a  href="<?php echo base_url() ?>report/<?=$row->item ?>/<?=$row->id ?>" class="btn btn-lg btn-warning view-report">

                        <?=$row->item ?>

                         Click here for see report

                    <?php endforeach; ?>

I have tried multiple times to view the array. But failed to get array. How can I load the view? When I click my items from home, it will create a url like http://localhost/super_shop_register/report/1

But didn't show any data. Show "Object not found!". Here is the image of my view:
After Clicking item, it will show like this:

How can I solve this?

Body:
Simple you can try this

$route['report/(:num)'] = "home/reportcard";

then you can get ID with below method in controller and nothing pass in function reportcard argument

$report_id = $this->uri->segment(2);


问:
Angular 2 pass local variable ngFor to a parent
I am trying to implement event delegation, but I can't find a way to pass the local variable from ngFor to the parent.

```<code>  <ul (click)="doSomething(hero)">
    <li *ngFor="let hero of data">{{hero.name}}</li>
  </ul>
</code>```

According to the event delegation technique, I need to click on the parent and check if the target is what I need and run the listener.

Is it possible to do this?

答:
This should be working

export class YourComponent {
    data = ['a', 'b'];

    doSomething($event: any) {
        //$event.data is 'a'
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <ul (click)="doSomething($event)">
        <li *ngFor="let hero of data" (click)="$event.data = hero;">{{hero}}</li>
    </ul></code>```

Body:
I am trying to implement event delegation, but I can't find a way to pass the local variable from ngFor to the parent.

{{hero.name}}

According to the event delegation technique, I need to click on the parent and check if the target is what I need and run the listener.

Is it possible to do this?

Body:
This should be working

export class YourComponent {
    data = ['a', 'b'];

    doSomething($event: any) {
        //$event.data is 'a'
    }
}

    <ul (click)="doSomething($event)">
        <li *ngFor="let hero of data" (click)="$event.data = hero;">{{hero}}</li>
    </ul>


问:
What is misconfigured when Drupal homepage works ok, but all links fail?
I have recently renamed the root folder of a development Drupal site from:

www.example.com/foo/

to

www.example.com/bar/

The site stayed on the same host. During this transition, I made sure to include the .htaccess file. I also updated $base_url in sites/default/settings.php to the new filesystem path. As a result, The homepage works just fine, and all hyperlinks on the homepage go where they should ( example.com/bar/content/ ). Unfortunately, clicking on any the hyperlinks sends me to an error page:

Not Found

  The requested URL /foo/index.php was not found on this server.

This looks like a misconfiguration, but all sources I can see only site the .htaccess file and $base_url as possible points of failure. What else should I be checking? Thanks.

答: Try clearing your cache. You may have to do it manually in the database. Here's a page that gives a few options: http://drupal.org/node/42055. Here's another way of doing it: http://drupal.org/node/152983#d6.</p>

ContentLicense: CC BY-SA 2.5


问:
How to initialize variable without value
I want to show value inside Textview. But problem is that its showing 0 in my Textview. It is coming from int total=0. I am doing setText but its not giving value I want.

If I remove 0 and keep int total then it's showing variable total is not initialized. If I initialize it then it shows that value in Textview.

```<code>public int getTotal(ArrayList<Integer> price){
    int total=0;
    for(int i=0;i<price.size();i++){
        total= total+Integer.parseInt(String.valueOf(price.get(i)));
    }
    return total;
}

textViewamount=(TextView)findViewById(R.id.amountdisplay);
textViewamount.setText(" "+getTotal(price));
</code>```

答:
Hi try to this hope this can help you..</p>

```<code>int[] price = {0, 1, 1, 10, 2, 5};
TextView total;

int total1 = 0;

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

    total = (TextView) findViewById(R.id.total);

    btn = (Button) findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            total1 = 0;
            getTotal();
            total.setText("" + total1);
        }
    });
}

 private void getTotal() {

    for (int i = 0; i < price.length; i++) {
        total1 = total1 + price[i];
    }
}
</code>```

Body:
I want to show value inside Textview. But problem is that its showing 0 in my Textview. It is coming from int total=0. I am doing setText but its not giving value I want.

If I remove 0 and keep int total then it's showing variable total is not initialized. If I initialize it then it shows that value in Textview.

public int getTotal(ArrayList<Integer> price){
    int total=0;
    for(int i=0;i<price.size();i++){
        total= total+Integer.parseInt(String.valueOf(price.get(i)));
    }
    return total;
}

textViewamount=(TextView)findViewById(R.id.amountdisplay);
textViewamount.setText(" "+getTotal(price));

Body:
Hi try to this hope this can help you..

int[] price = {0, 1, 1, 10, 2, 5};
TextView total;

int total1 = 0;

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

    total = (TextView) findViewById(R.id.total);

    btn = (Button) findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            total1 = 0;
            getTotal();
            total.setText("" + total1);
        }
    });
}

 private void getTotal() {

    for (int i = 0; i < price.length; i++) {
        total1 = total1 + price[i];
    }
}


问:
NPM start giving error
```<code>npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v0.12.7
npm ERR! npm  v2.11.3
npm ERR! path C:\angularjs2\package.json
npm ERR! code ENOENT
npm ERR! errno -4058

npm ERR! enoent ENOENT, open 'C:\angularjs2\package.json'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     C:\angularjs2\npm-debug.log
</code>```

答:
To run npm start you need to be in a directory where a package.json of a module that you want to start is located:

```<code>cd /path/to/module
npm start
</code>```

If you don't have a package.json yet then you can create one with:

```<code>npm init
</code>```

Remember that you need to define a start script, like this:

```<code>"scripts": {
    "start": "node module.js"
}
</code>```

in package.json.

Title: NPM start giving error

Body:
To run npm start you need to be in a directory where a package.json of a module that you want to start is located:

cd /path/to/module
npm start

If you don't have a package.json yet then you can create one with:

npm init

Remember that you need to define a start script, like this:

"scripts": {
    "start": "node module.js"
}

in package.json.


问:
Ionic Storage, how to stay simple in the Promise scope
I am using Ionic Storage, and it returns a Promise...which is really impractical.

I need to get a value from Storage and depending on its boolean value, do something.

That was the code I had in Angular 1:

```<code>$scope.isUser = UserService.getUser() ? true : false;
$scope.isUserTemp = storageService.get("userTemp") ? true : false;
$scope.data.showLoginClose = ($scope.isUser || $scope.isUserTemp || !$rootScope.isMobile );
</code>```

Here's the new code in typescript:

```<code>    let isUser: boolean;
    let isUserTemp: boolean;
    this.storage.ready().then(() => {
        this.storage.get('userTemp').then((val) => {
            isUserTemp = true ;
            isUser = UserService.getUser() ? true : false;
            this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f() );
        })
        .catch( (e) => {
            isUserTemp = false ;
            isUser = UserService.getUser() ? true : false;
            this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f() );
        })
    });
</code>```

3 lines vs 14 lines, that's not an improvement.

Can you help me write something clean in the Promise scope for Angular2 / typescript, for all the cases (isUser true, userTemp : true   ; isUser false, userTemp : true  ; etc...) ?

答:
Based on @VinceOPS, but with fixed logic, because Ionic Storage is based on localForage, .then() is executed even if the variable you looking for is not present in Storage, and in this case ̀val is null.

```<code>    let that = this;
    this.storage.ready().then(() => {
        return this.storage.get('userTemp');
    })
    .then(retrieved => updateLoginClose(retrieved))
    .catch(e =>  console.error('ERROR: could not read Storage, error:', e));
    function updateLoginClose(retrieved) {
       let isUserTemp:boolean;
       if (retrieved !== null) {
          isUserTemp = true;
       } else {
          isUserTemp = false;
       }
       that.data.showLoginClose = isUserTemp || that.UserService.getUser() || !that.isCordova.f();
    }
</code>```

Body:
I am using Ionic Storage, and it returns a Promise...which is really impractical.

I need to get a value from Storage and depending on its boolean value, do something.

That was the code I had in Angular 1:

$scope.isUser = UserService.getUser() ? true : false;
$scope.isUserTemp = storageService.get("userTemp") ? true : false;
$scope.data.showLoginClose = ($scope.isUser || $scope.isUserTemp || !$rootScope.isMobile );

Here's the new code in typescript:

    let isUser: boolean;
    let isUserTemp: boolean;
    this.storage.ready().then(() => {
        this.storage.get('userTemp').then((val) => {
            isUserTemp = true ;
            isUser = UserService.getUser() ? true : false;
            this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f() );
        })
        .catch( (e) => {
            isUserTemp = false ;
            isUser = UserService.getUser() ? true : false;
            this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f() );
        })
    });

3 lines vs 14 lines, that's not an improvement.

Can you help me write something clean in the Promise scope for Angular2 / typescript, for all the cases (isUser true, userTemp : true   ; isUser false, userTemp : true  ; etc...) ?

Body:
Based on @VinceOPS, but with fixed logic, because Ionic Storage is based on localForage, .then() is executed even if the variable you looking for is not present in Storage, and in this case ̀val is null.

    let that = this;
    this.storage.ready().then(() => {
        return this.storage.get('userTemp');
    })
    .then(retrieved => updateLoginClose(retrieved))
    .catch(e =>  console.error('ERROR: could not read Storage, error:', e));
    function updateLoginClose(retrieved) {
       let isUserTemp:boolean;
       if (retrieved !== null) {
          isUserTemp = true;
       } else {
          isUserTemp = false;
       }
       that.data.showLoginClose = isUserTemp || that.UserService.getUser() || !that.isCordova.f();
    }


问:
Check if timestamp older than 30 seconds
I am trying to determine if a timestamp is older than 30 seconds, but for some reason it is coming back as older than 30 seconds when it hasn't even been a couple seconds. </p>

<p>Example: https://ideone.com/KLIIBz </p>

```<code>public static Boolean cooldown(int id) {

    Calendar now = Calendar.getInstance();
    now.add(Calendar.SECOND, -secondsAgo);
    long timeAgo = now.getTimeInMillis();
    if ( cooldown.containsKey(id) ) {

        System.out.println(cooldown.get(id) + " | " + timeAgo);

        // Stored timestamp always older than timeAgo
        if ( cooldown.get(id) < timeAgo ) {

            cooldown.remove(id);

        } else {

            // This code should be executed, as I am running the function one after another from same UUID not even a second or two apart.
            return false;

        }

    }

    now = Calendar.getInstance();
    cooldown.put(id, now.getTimeInMillis());

    return true;

}
</code>```

答:
To judge from the code on Ideone that you link to, the problem is that secondsAgo is 0, not 30. You set it to 30 in the constructor, but since you never create an object from the class, the constructor is never executed. secondsAgo is a static field, so you can access it without an object and without it having been initialized. You just get the initial value that all int fields have, namely 0.

The output I see in Ideone certainly confirms what I am saying. In all lines of the form 1491194338577 | 1491194338578 the numbers are either identical or just 1 millisecond apart. Even though you have subtracted secondsAgo seconds from the Calendar object that you get timeAgo from, timeAgo is never anywhere near 30 seconds earlier than the timestamp that you put into the map a millisecond ago. So no, you are not subtracting 30 seconds; you are subtracting 0 seconds.

That said I still agree with Basil Bourque’s answer: if there is any way you can use Java 8, you should throw the Calendar class away and use Instant and Duration. You get much clearer and more readable code. Put Instant objects in your map instead of Longs and it’s suddenly self-explanatory what they are.

Body:
I am trying to determine if a timestamp is older than 30 seconds, but for some reason it is coming back as older than 30 seconds when it hasn't even been a couple seconds.

Example: https://ideone.com/KLIIBz

public static Boolean cooldown(int id) {

    Calendar now = Calendar.getInstance();
    now.add(Calendar.SECOND, -secondsAgo);
    long timeAgo = now.getTimeInMillis();
    if ( cooldown.containsKey(id) ) {

        System.out.println(cooldown.get(id) + " | " + timeAgo);

        // Stored timestamp always older than timeAgo
        if ( cooldown.get(id) < timeAgo ) {

            cooldown.remove(id);

        } else {

            // This code should be executed, as I am running the function one after another from same UUID not even a second or two apart.
            return false;

        }

    }

    now = Calendar.getInstance();
    cooldown.put(id, now.getTimeInMillis());

    return true;

}


问:
How to use a # in .htaccess (not as comment)
Hey this should be a pretty easy question but I can't find the answer to it.

How can I use a # in my .htaccess, without turning it into a comment.
I want to rewrite my url from www.sitename/index.php#contact to www.sitename/index.php.

答:
I think that all you want to know can be find there:

'hash' url rewrite in .htaccess

Redirect URL with hash using .htaccess file


问:
How can i get x indexed row from a table in PL/SQL?
First of all feel free to correct my English and
I have just started PL/SQL.

Here is my PL/SQL code.
There is table called 'EMP' with employees's information.

My goal is to get the median of the employees's wage.
So if the number of employees is odd then i need the middle one.

If it is even then i need the two mid ones's average.

It does the job so far, im just confused after the "if" statement.
What is the easiest way to get the nth indexed row's value?

```<code>SET SERVEROUTPUT ON

DECLARE
    counter Int(4);
    osszeg Int(5);
    temp EMP.sal%TYPE;

CURSOR wage IS
  SELECT EMP.SAL
  FROM EMP
  ORDER BY EMP.SAL ASC;

BEGIN
     OPEN wage;
     counter := 0;

LOOP
  FETCH wage
  INTO temp;
  EXIT WHEN wage%NOTFOUND;
  counter := counter + 1;
END LOOP;
CLOSE wage;
</code>```

AND i need help from here

```<code>IF MOD(counter,2) = 0 THEN

ELSE

END IF;

END;
</code>```

答:
You can use analytic functions, it's much easier to solve your in SQL , without using PL/SQL.

```<code>select t.*,
       case
          when mod(totcnt, 2) = 0 then
           (Wage + LeadWage) / 2
          else
           Wage
       end
  from (select rownum RN, num, count(*) over(partition by 1) TotCnt,
                lead(Wage) over (order by Wage) LeadWage
           from Emp) t
 where t.Rn = round(TotCnt / 2);
</code>```

or, if you  want to use PL/SQL, you should store your median value as pair of variables (current wage value and previous wage value inside you fetch operator , until you don't know is your set of wages odd or even), and while looping inside fetch use should always calculate median value in each step for previous iterations.

Body:
First of all feel free to correct my English and
I have just started PL/SQL.

Here is my PL/SQL code.
There is table called 'EMP' with employees's information.

My goal is to get the median of the employees's wage.
So if the number of employees is odd then i need the middle one.

If it is even then i need the two mid ones's average.

It does the job so far, im just confused after the "if" statement.
What is the easiest way to get the nth indexed row's value?

SET SERVEROUTPUT ON

DECLARE
    counter Int(4);
    osszeg Int(5);
    temp EMP.sal%TYPE;

CURSOR wage IS
  SELECT EMP.SAL
  FROM EMP
  ORDER BY EMP.SAL ASC;

BEGIN
     OPEN wage;
     counter := 0;

LOOP
  FETCH wage
  INTO temp;
  EXIT WHEN wage%NOTFOUND;
  counter := counter + 1;
END LOOP;
CLOSE wage;

AND i need help from here

IF MOD(counter,2) = 0 THEN

ELSE

END IF;

END;

Body:
You can use analytic functions, it's much easier to solve your in SQL , without using PL/SQL.

select t.*,
       case
          when mod(totcnt, 2) = 0 then
           (Wage + LeadWage) / 2
          else
           Wage
       end
  from (select rownum RN, num, count(*) over(partition by 1) TotCnt,
                lead(Wage) over (order by Wage) LeadWage
           from Emp) t
 where t.Rn = round(TotCnt / 2);

or, if you  want to use PL/SQL, you should store your median value as pair of variables (current wage value and previous wage value inside you fetch operator , until you don't know is your set of wages odd or even), and while looping inside fetch use should always calculate median value in each step for previous iterations.


问:
python sort strings with digits at the end
what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

```<code>>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']
</code>```

should  put the 1234 one on the end. is there an easy way to do this?

Body:
what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']

should  put the 1234 one on the end. is there an easy way to do this?

Body: L.sort(key=lambda s:int(''.join(filter(str.isdigit,s[-4:]))))


问:
Yii2 : Subdirectory in yii2 not working
I created a sub folder in yii2 installed project and I want to work this sub folder as a normal html website but its redirecting to yii2 login page. How to make it work as a normal html website?</p>

答: Create your subfolder with your HTML page within your /web folder. When your Yii2 Website is reachable via http://localhost/ you're now able to call your HTML Website via http://localhost/your-subfolder/your-html-file.html.

Title: Yii2 : Subdirectory in yii2 not working

ContentLicense: CC BY-SA 4.0


问:
Does executing a prepared statement skip the planning stage in PostgreSQL
I'm wondering if I prepare a statement in PostgreSQL, i.e.:

```<code>PREPARE newquery(int) AS
SELECT * FROM table1 WHERE somefield > $1;
</code>```

Will the backend call the parse analysis and the planner when I execute:

```<code>EXECUTE newquery(123);
</code>```

I found some documentation where it says that PostgreSQL "skips" parse analysis and planning of prepared queries, and by doing that significantly optimizes query execution.

I tried testing this by overwriting the post_parse_analyze_hook and planner_hook, and from them simply writing some stuff into log files(i.e. "Planner called"), so I can see if the planner and parse analyzer are called. Is this testing method valid?

I'm confused, because every time I execute EXECUTE newquery(some number); both the parse analyzer and the planner are called.

I'm doing all this because I want to count how many times a query was compiled to get a better understanding of "query caching".

Note: I'm doing this in a single session. Every time I connect to the server I prepare the statements again.

Why are planner and parse analyzer called?

答:
This must be the “custom plan” feature introduced in 9.2.
For the first few executions of a prepared statement it will generate a custom plan that uses the parameter values and then switch to the generic plan (that does not use the parameter values) if these plans don't look better than the generic plan.

Try to EXECUTE the prepared statement at least six times and see if the planner is still called.

Body:
I'm wondering if I prepare a statement in PostgreSQL, i.e.:

PREPARE newquery(int) AS
SELECT * FROM table1 WHERE somefield > $1;

Will the backend call the parse analysis and the planner when I execute:

EXECUTE newquery(123);

I found some documentation where it says that PostgreSQL "skips" parse analysis and planning of prepared queries, and by doing that significantly optimizes query execution.

I tried testing this by overwriting the post_parse_analyze_hook and planner_hook, and from them simply writing some stuff into log files(i.e. "Planner called"), so I can see if the planner and parse analyzer are called. Is this testing method valid?

I'm confused, because every time I execute EXECUTE newquery(some number); both the parse analyzer and the planner are called.

I'm doing all this because I want to count how many times a query was compiled to get a better understanding of "query caching".

Note: I'm doing this in a single session. Every time I connect to the server I prepare the statements again.

Why are planner and parse analyzer called?


问:
docker-compose INTERNAL ERROR: cannot create temporary directory
Am trying to use docker-compose command and bring up container. But am facing error INTERNAL ERROR: cannot create temporary directory!. Am not able to pull, stop, rm or UP and container. Can anyone suggest how to resolve this?</p>

答:
I was suffering from the same issue. It turned out that I'd ran out of Disk Space.

All I needed to do was clear down the old containers and images by running the below commands. I ran these on my Docker directory and everything was good afterwards.

Remove Containers Command:

```<code>#!/bin/bash
# Remove all stopped containers
docker rm $(docker ps -a -q)
# Remove all containers
docker rm -f $(docker ps -a -q)
</code>```

Command options:

--force or -f: Force the removal of running container (uses SIGKILL).

--volumes or -v: Remove the Volumes associated with the container.

--link or -l: Remove the specified link.

Remove Images Command:

```<code># Delete all images
docker rmi $(docker images -q)
</code>```

Command options:

--force or -f: Force removal of the image.
--no-prune: Do not delete untagged parents.

System Prune Command: -- Suggested by Ryan Allan in comments.

```<code>#!/bin/bash
#System Prune
docker system prune
</code>```

--all or -a: Remove all unused images not just dangling ones.

--filter Provide filter values (e.g. 'label==') <-- From API 1.28+

--force or -f: Do not prompt for confirmation.

--volumes: Prune volumes.

Base Command:

docker: The base command for Docker CLI.

Code referenced from Docker remove all images and containers

Body:
I was suffering from the same issue. It turned out that I'd ran out of Disk Space.

All I needed to do was clear down the old containers and images by running the below commands. I ran these on my Docker directory and everything was good afterwards.

Remove Containers Command:

#!/bin/bash
# Remove all stopped containers
docker rm $(docker ps -a -q)
# Remove all containers
docker rm -f $(docker ps -a -q)

Command options:

--force or -f: Force the removal of running container (uses SIGKILL).

--volumes or -v: Remove the Volumes associated with the container.

--link or -l: Remove the specified link.

Remove Images Command:

# Delete all images
docker rmi $(docker images -q)

Command options:

--force or -f: Force removal of the image.
--no-prune: Do not delete untagged parents.

System Prune Command: -- Suggested by Ryan Allan in comments.

#!/bin/bash
#System Prune
docker system prune

--all or -a: Remove all unused images not just dangling ones.

--filter Provide filter values (e.g. 'label==') <-- From API 1.28+

--force or -f: Do not prompt for confirmation.

--volumes: Prune volumes.

Base Command:

docker: The base command for Docker CLI.

Code referenced from Docker remove all images and containers


问:
Jquery: Dynamic binding events on a Highcharts object
I'm trying to use, but to no luck

```<code>$("parent").on("click","child",function(){
  //
}
</code>```

My HTML sits this way

```<code><ul id="carouselRoot">
    <li id="container0"><div class="highcharts-container">.....</li>
    <li>
        <ul id="subCarousel">
             <li id="container1"><div class="highcharts-container">.....</li>
             <li id="container2"><div class="highcharts-container">.....</li>
             <li id="container3"><div class="highcharts-container">.....</li>
        </ul>
    </li>
</ul>
</code>```

I'm trying to capture the click event on each chart. So, $(".highcharts-container").click() works fine but I'm also adding charts dynamically to #subCarousel.

and doing

```<code>$("#subCarousel li").on("click",".highcharts-container",function(){});
</code>```

simply does not invoke the call. How do I get around this?

PS: I've also tried using body as the parent.

答: Use highcharts built-in events. But for custom events, install highcharts-custom-events.</p>

Body:
I'm trying to use, but to no luck

$("parent").on("click","child",function(){
  //
}

My HTML sits this way

.....

.....

.....

.....

I'm trying to capture the click event on each chart. So, $(".highcharts-container").click() works fine but I'm also adding charts dynamically to #subCarousel.

and doing

$("#subCarousel li").on("click",".highcharts-container",function(){});

simply does not invoke the call. How do I get around this?

PS: I've also tried using body as the parent.


问:
Canvas Clock with transparent background
here is a canvas clock based on example from w3schools.com:
https://jsfiddle.net/z529mk97/

Does anyone know how to make the background of the clock transparent?

Here is the code. I have tried to set ctx.fillStyle to transparent, but this leads into a situation where second hand is not erased after it has moved.

<canvas id="canvas" width="400" height="400">
</canvas>

```

Thanks in advance!

答:
Do this

Change code like this.

```<code>function drawClock() {
  ctx.clearRect(-radius, -radius, canvas.width, canvas.height);
  drawFace(ctx, radius);
  drawNumbers(ctx, radius);
  drawTime(ctx, radius);
}
</code>```

and
comment as shown below

```<code>function drawFace(ctx, radius) {
  var grad;
  ctx.beginPath();
/*  ctx.arc(0, 0, radius, 0, 2*Math.PI);
  ctx.fillStyle = "rgba(255, 255, 255, 0.7)";
  ctx.fill();*/
</code>```

Try giving background colour to your body tag

Js fiddle demo : https://jsfiddle.net/mhnwaa91/

:)

Body:
here is a canvas clock based on example from w3schools.com:
https://jsfiddle.net/z529mk97/

Does anyone know how to make the background of the clock transparent?

Here is the code. I have tried to set ctx.fillStyle to transparent, but this leads into a situation where second hand is not erased after it has moved.

<canvas id="canvas" width="400" height="400">
</canvas>

Thanks in advance!

Body:
Do this

Change code like this.

function drawClock() {
  ctx.clearRect(-radius, -radius, canvas.width, canvas.height);
  drawFace(ctx, radius);
  drawNumbers(ctx, radius);
  drawTime(ctx, radius);
}

and
comment as shown below

function drawFace(ctx, radius) {
  var grad;
  ctx.beginPath();
/*  ctx.arc(0, 0, radius, 0, 2*Math.PI);
  ctx.fillStyle = "rgba(255, 255, 255, 0.7)";
  ctx.fill();*/

Try giving background colour to your body tag

Js fiddle demo : https://jsfiddle.net/mhnwaa91/

:)


问:
Alternative solution to HostingEnvironment.QueueBackgroundWorkItem in .NET Core
We are working with .NET Core Web Api, and looking for a lightweight solution to log requests with variable intensity into database, but don't want client's to wait for the saving process.

Unfortunately there's no HostingEnvironment.QueueBackgroundWorkItem(..) implemented in dnx, and Task.Run(..) is not safe.

Is there any elegant solution?

答:
QueueBackgroundWorkItem is gone, but we've got IApplicationLifetime instead of IRegisteredObject, which is being used by the former one. And it looks quite promising for such scenarios, I think.

The idea (and I'm still not quite sure, if it's a pretty bad one; thus, beware!) is to register a singleton, which spawns and observes new tasks. Within that singleton we can furthermore register a "stopped event" in order to proper await still running tasks.

This "concept" could be used for short running stuff like logging, mail sending, and the like. Things, that should not take much time, but would produce unnecessary delays for the current request.

```<code>public class BackgroundPool
{
    protected ILogger<BackgroundPool> Logger { get; }

    public BackgroundPool(ILogger<BackgroundPool> logger, IApplicationLifetime lifetime)
    {
        if (logger == null)
            throw new ArgumentNullException(nameof(logger));
        if (lifetime == null)
            throw new ArgumentNullException(nameof(lifetime));

        lifetime.ApplicationStopped.Register(() =>
        {
            lock (currentTasksLock)
            {
                Task.WaitAll(currentTasks.ToArray());
            }

            logger.LogInformation(BackgroundEvents.Close, "Background pool closed.");
        });

        Logger = logger;
    }

    private readonly object currentTasksLock = new object();

    private readonly List<Task> currentTasks = new List<Task>();

    public void SendStuff(Stuff whatever)
    {
        var task = Task.Run(async () =>
        {
            Logger.LogInformation(BackgroundEvents.Send, "Sending stuff...");

            try
            {
                // do THE stuff

                Logger.LogInformation(BackgroundEvents.SendDone, "Send stuff returns.");
            }
            catch (Exception ex)
            {
                Logger.LogError(BackgroundEvents.SendFail, ex, "Send stuff failed.");
            }
        });

        lock (currentTasksLock)
        {
            currentTasks.Add(task);

            currentTasks.RemoveAll(t => t.IsCompleted);
        }
    }
}
</code>```

Such a BackgroundPool should be registered as a singleton and can be used by any other component via DI. I'm currently using it for sending mails and it works fine (tested mail sending during app shutdown too).

Note: accessing stuff like the current HttpContext within the background task should not work. The old solution uses UnsafeQueueUserWorkItem to prohibit that anyway.

What do you think?

Update:

With ASP.NET Core 2.0 there's new stuff for background tasks, which get's better with ASP.NET Core 2.1: Implementing background tasks in .NET Core 2.x webapps or microservices with IHostedService and the BackgroundService class

Body:
QueueBackgroundWorkItem is gone, but we've got IApplicationLifetime instead of IRegisteredObject, which is being used by the former one. And it looks quite promising for such scenarios, I think.

The idea (and I'm still not quite sure, if it's a pretty bad one; thus, beware!) is to register a singleton, which spawns and observes new tasks. Within that singleton we can furthermore register a "stopped event" in order to proper await still running tasks.

This "concept" could be used for short running stuff like logging, mail sending, and the like. Things, that should not take much time, but would produce unnecessary delays for the current request.

public class BackgroundPool
{
    protected ILogger<BackgroundPool> Logger { get; }

    public BackgroundPool(ILogger<BackgroundPool> logger, IApplicationLifetime lifetime)
    {
        if (logger == null)
            throw new ArgumentNullException(nameof(logger));
        if (lifetime == null)
            throw new ArgumentNullException(nameof(lifetime));

        lifetime.ApplicationStopped.Register(() =>
        {
            lock (currentTasksLock)
            {
                Task.WaitAll(currentTasks.ToArray());
            }

            logger.LogInformation(BackgroundEvents.Close, "Background pool closed.");
        });

        Logger = logger;
    }

    private readonly object currentTasksLock = new object();

    private readonly List<Task> currentTasks = new List<Task>();

    public void SendStuff(Stuff whatever)
    {
        var task = Task.Run(async () =>
        {
            Logger.LogInformation(BackgroundEvents.Send, "Sending stuff...");

            try
            {
                // do THE stuff

                Logger.LogInformation(BackgroundEvents.SendDone, "Send stuff returns.");
            }
            catch (Exception ex)
            {
                Logger.LogError(BackgroundEvents.SendFail, ex, "Send stuff failed.");
            }
        });

        lock (currentTasksLock)
        {
            currentTasks.Add(task);

            currentTasks.RemoveAll(t => t.IsCompleted);
        }
    }
}

Such a BackgroundPool should be registered as a singleton and can be used by any other component via DI. I'm currently using it for sending mails and it works fine (tested mail sending during app shutdown too).

Note: accessing stuff like the current HttpContext within the background task should not work. The old solution uses UnsafeQueueUserWorkItem to prohibit that anyway.

What do you think?

Update:

With ASP.NET Core 2.0 there's new stuff for background tasks, which get's better with ASP.NET Core 2.1: Implementing background tasks in .NET Core 2.x webapps or microservices with IHostedService and the BackgroundService class


问:
Aligning Text / Icon Within Button
I've tried many different things on the web and from SO and again can't seem to get this to work. First time I've been changing / styling my buttons and they're driving me mad! So I have a left floated button on the same line as my right floated button now. I'd like to see if I can have the icon to the left of the text on the left button and the right of the text on the right button. Like this:

<- Last Page //////////////////////////////////////////////// Next Page ->

```<code><span align="right">
<ul class="actions">
<li id="leftbutton"><a href="tfn.html" class="button special icon fa-arrow-left">TFN</a></li>
<li id="rightbutton"><a href="medical-indemnity-and-insurance.html" class="button special icon fa-arrow-right">Indemnity & Insurance</a></li>
</ul>
</span>
</code>```

Fiddle

For some reason on the above fiddle it doesn't seem to be showing the font awesome arrows?

Thank you so much!

S.

答:
class will be fa fa-arrow-right not icon fa-arrow-right.

Like
TFN

It's always best practice to use  tag when you use a font awesome icon

Like
TFN

Title: Aligning Text / Icon Within Button

Body:
I've tried many different things on the web and from SO and again can't seem to get this to work. First time I've been changing / styling my buttons and they're driving me mad! So I have a left floated button on the same line as my right floated button now. I'd like to see if I can have the icon to the left of the text on the left button and the right of the text on the right button. Like this:

<- Last Page //////////////////////////////////////////////// Next Page ->

TFN

Indemnity & Insurance

Fiddle

For some reason on the above fiddle it doesn't seem to be showing the font awesome arrows?

Thank you so much!

S.

Body:
class will be fa fa-arrow-right not icon fa-arrow-right.

Like
<a href="tfn.html" class="button special fa fa-arrow-left">TFN</a>

It's always best practice to use <i> tag when you use a font awesome icon

Like
<a href="tfn.html" class="button special"><i class="fa fa-arrow-left" aria-hidden="true"></i>TFN</a>


问:
openstack keystone reduce number of workers
i tried to reduce the number of keystone work and save some of memory

```<code>keystone  15467  0.0  0.0 782944 10104 ?        Sl   10:12   0:00 keystone-admin  -DFOREGROUND
keystone  15535  0.0  0.0 782944 10104 ?        Sl   10:12   0:00 keystone-admin  -DFOREGROUND
keystone  15622  1.6  0.2 992416 83788 ?        Sl   10:12   0:01 keystone-main   -DFOREGROUND
keystone  15665  0.0  0.0 782944 10104 ?        Sl   10:12   0:00 keystone-main   -DFOREGROUND
</code>```

there are more than 100 of this kind worker running on my system. I modified the keystone.conf public_workers and admin_workers to 16 only and reboot the system but the number of keystone workers are the same. I am using newton with packstack. please advise ! thanks a lot

答:
If public_workers and admin_workers in /etc/keystone/keystone.conf didn't change anything it probably means that your keystone runs under apache (httpd) WSGI. This is how majority of OpenStack distros run keystone now.

So now, depending on your Linux distribution your keystone worker configuration should be under httpd configuration. On Red Hat base systems you will find it in:

/etc/httpd/conf.d/10-keystone_wsgi_admin.conf

/etc/httpd/conf.d/10-keystone_wsgi_main.conf

Inside you will have line like below or something similar:

WSGIDaemonProcess keystone_main display-name=keystone-main group=keystone processes=8 threads=8 user=keystone

And this is where you need to change number of processes and threads.

Body:
i tried to reduce the number of keystone work and save some of memory

keystone  15467  0.0  0.0 782944 10104 ?        Sl   10:12   0:00 keystone-admin  -DFOREGROUND
keystone  15535  0.0  0.0 782944 10104 ?        Sl   10:12   0:00 keystone-admin  -DFOREGROUND
keystone  15622  1.6  0.2 992416 83788 ?        Sl   10:12   0:01 keystone-main   -DFOREGROUND
keystone  15665  0.0  0.0 782944 10104 ?        Sl   10:12   0:00 keystone-main   -DFOREGROUND

there are more than 100 of this kind worker running on my system. I modified the keystone.conf public_workers and admin_workers to 16 only and reboot the system but the number of keystone workers are the same. I am using newton with packstack. please advise ! thanks a lot


问:
Count where value is 1
I got this SELECT. And I want to count (or sum?) Yellow and Red card of players (Count Yellow cards only where YellowCard = 1, and Count Red cards only where RedCard = 1).. This SELECT does not work correctly. It count card even if there are 0 or NULL.. How can i correct it? </p>

```<code>SELECT Firstname, Lastname, COUNT(YellowCard) AS Yellow, COUNT(RedCard) AS Red, Team.Name
FROM PlayerMatch
Inner join Player On PlayerMatch.PlayerId = Player.PlayerId
INNER JOIN Team ON Player.TeamId = Team.TeamId
INNER JOIN Match ON PlayerMatch.MatchId = Match.MatchId
WHERE(YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC
</code>```

答:
Use SUM() instead of COUNT():

```<code>SELECT Firstname, Lastname,
       SUM(YellowCard) AS Yellow, SUM(RedCard) AS Red, t.Name
FROM PlayerMatch pm Inner join
     Player p
     On pm.PlayerId = p.PlayerId INNER JOIN
     Team t
     ON p.TeamId = t.TeamId INNER JOIN
     Match m
     ON pm.MatchId = m.MatchId
WHERE (YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC;
</code>```

This assumes that the values of YellowCard and RedCard are always 0 or 1 (or NULL).  That seems like a reasonable assumption.

If that is not the case, then use CASE:

```<code>SELECT Firstname, Lastname,
       SUM(CASE WHEN YellowCard = 1 THEN 1 ELSE 0 END) AS Yellow,
       SUM(CASE WHEN RedCard = 1 THEN 1 ELSE 0 END) AS Red,
       t.Name
</code>```

Title: Count where value is 1

Body:
I got this SELECT. And I want to count (or sum?) Yellow and Red card of players (Count Yellow cards only where YellowCard = 1, and Count Red cards only where RedCard = 1).. This SELECT does not work correctly. It count card even if there are 0 or NULL.. How can i correct it?

SELECT Firstname, Lastname, COUNT(YellowCard) AS Yellow, COUNT(RedCard) AS Red, Team.Name
FROM PlayerMatch
Inner join Player On PlayerMatch.PlayerId = Player.PlayerId
INNER JOIN Team ON Player.TeamId = Team.TeamId
INNER JOIN Match ON PlayerMatch.MatchId = Match.MatchId
WHERE(YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC

Body:
Use SUM() instead of COUNT():

SELECT Firstname, Lastname,
       SUM(YellowCard) AS Yellow, SUM(RedCard) AS Red, t.Name
FROM PlayerMatch pm Inner join
     Player p
     On pm.PlayerId = p.PlayerId INNER JOIN
     Team t
     ON p.TeamId = t.TeamId INNER JOIN
     Match m
     ON pm.MatchId = m.MatchId
WHERE (YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC;

This assumes that the values of YellowCard and RedCard are always 0 or 1 (or NULL).  That seems like a reasonable assumption.

If that is not the case, then use CASE:

SELECT Firstname, Lastname,
       SUM(CASE WHEN YellowCard = 1 THEN 1 ELSE 0 END) AS Yellow,
       SUM(CASE WHEN RedCard = 1 THEN 1 ELSE 0 END) AS Red,
       t.Name


问:
Server returned HTTP response code: 400 facebook
I'm gettting a problem:

ERROR : Server returned HTTP response code: 400 for URL

URL: https://graph.facebook.com/me?fields=id%2Cname%2Cemail%2Cgender&
  access_token=XXXXXXXXXXXXXXXXXXX

Below is my code :

```<code>public String getFBGraph() {
    String graph = null;

    try {

        String g ="https://graph.facebook.com/me?fields=id%2Cname%2Cemail%2Cgender&"+accessToken;

        URL u=new URL(g);
        URLConnection c=u.openConnection();

        BufferedReader in=new BufferedReader(new InputStreamReader(c.getInputStream()));
        String inputLine;

        StringBuffer b=new StringBuffer();
        while ((inputLine=in.readLine())!=null)
            b.append(inputLine+"\n");
        in.close();
        graph=b.toString();
        //System.out.println(graph);
    } catch (Exception e) {
        e.printStackTrace();

        throw new RuntimeException("ERROR in getting FB graph data. "+e);
    }
    return graph;

}
</code>```

I'm getting error while I run it from calling method and when I copy paste same url to browser getting output, please help me my accesstocken is perfect, what is the problem?

答:
Most probably you just forgot to add access_token= parameter name to your URL string:

String g ="https://graph.facebook.com/me?fields=id%2Cname%2Cemail%2Cgender&"+accessToken

Facebook will respond with the HTTP status code 400, in this case:

10.4.1 400 Bad Request
  The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

and will say something along the lines of

"An active access token must be used to query information about the current user."

in the response body.

Body:
I'm gettting a problem:

ERROR : Server returned HTTP response code: 400 for URL

URL: https://graph.facebook.com/me?fields=id%2Cname%2Cemail%2Cgender&
  access_token=XXXXXXXXXXXXXXXXXXX

Below is my code :

public String getFBGraph() {
    String graph = null;

    try {

        String g ="https://graph.facebook.com/me?fields=id%2Cname%2Cemail%2Cgender&"+accessToken;

        URL u=new URL(g);
        URLConnection c=u.openConnection();

        BufferedReader in=new BufferedReader(new InputStreamReader(c.getInputStream()));
        String inputLine;

        StringBuffer b=new StringBuffer();
        while ((inputLine=in.readLine())!=null)
            b.append(inputLine+"\n");
        in.close();
        graph=b.toString();
        //System.out.println(graph);
    } catch (Exception e) {
        e.printStackTrace();

        throw new RuntimeException("ERROR in getting FB graph data. "+e);
    }
    return graph;

}

I'm getting error while I run it from calling method and when I copy paste same url to browser getting output, please help me my accesstocken is perfect, what is the problem?


问:
use string variable as query in codeigniter
i am using codeigniter and i need to use aggregate function in query. so i have this query.

```<code>"SELECT Dated, CASE WHEN `Account_ID` = 2 then SUM(Total_Bricks) ELSE 0 end as 'Nadeem',
CASE WHEN Account_ID = 2 then SUM(Kaat_Bricks) ELSE 0 end as 'NadeemKaat',
CASE WHEN `Account_ID` = 7 then SUM(Total_Bricks) ELSE 0 end as 'Abid',
CASE WHEN Account_ID = 7 then SUM(Kaat_Bricks) ELSE 0 end as 'AbidKaat',
CASE WHEN `Account_ID` = 8 then SUM(Total_Bricks) ELSE 0 end as 'Sajid',
CASE WHEN Account_ID = 8 then SUM(Kaat_Bricks) ELSE 0 end as 'SajidKaat'
FROM `tblstockdetail` GROUP BY `Dated`"
</code>```

i have generated this query through a simple foreach loop

```<code>$stock = $this->Kharkaar_Model->get_stockdetail();

        $sql = '"SELECT Dated, ';

        $numItems = count($stock);
        $i = 0;
        foreach ($stock as $key => $value)
        {

            if(++$i === $numItems)
            {
                $sql.= "CASE WHEN `Account_ID` = ".$value['Account_ID']." then SUM(Total_Bricks) ELSE 0 end as '".$value['AccountName']."', <br />
            CASE WHEN Account_ID = ".$value['Account_ID']." then SUM(Kaat_Bricks) ELSE 0 end as '".$value['AccountName']."Kaat' <br /> FROM `tblstockdetail` GROUP BY `Dated`";
            }
            else
            {
                $sql.= "CASE WHEN `Account_ID` = ".$value['Account_ID']." then SUM(Total_Bricks) ELSE 0 end as '".$value['AccountName']."', <br />
            CASE WHEN Account_ID = ".$value['Account_ID']." then SUM(Kaat_Bricks) ELSE 0 end as '".$value['AccountName']."Kaat', <br /> ";

            }

        }

        $sql.= '"';
</code>```

now when i try to get result of this query

```<code>$result = $this->db->query($sql);
</code>```

it is giving me a syntax error, otherwise when i put this query direct into

```<code>$result = $this->db->query(// string query here );
</code>```

it is running fine.

答:
Your foreach should be like this

```<code>$stock = $this->Kharkaar_Model->get_stockdetail();

$sql = "SELECT Dated, ";

$numItems = count($stock);
$i = 0;
foreach ($stock as $key => $value)
{

    if(++$i === $numItems)
    {
        $Account_ID = $value['Account_ID'];
        $AccountName = $value['AccountName'];

        $sql.= "CASE WHEN `Account_ID` =  $Account_ID then SUM(Total_Bricks) ELSE 0 end as $AccountName,
        CASE WHEN Account_ID = $Account_ID then SUM(Kaat_Bricks) ELSE 0 end as $AccountName
        FROM `tblstockdetail` GROUP BY `Dated`";
    }
    else
    {
        $sql.= "CASE WHEN `Account_ID` = $Account_ID then SUM(Total_Bricks) ELSE 0 end as $AccountName,
        CASE WHEN Account_ID = $Account_ID then SUM(Kaat_Bricks) ELSE 0 end as $AccountName";

    }

}
</code>```

if TRUE

```<code>"SELECT Dated,
CASE WHEN `Account_ID` =  $Account_ID then SUM(Total_Bricks) ELSE 0 end as $AccountName,
CASE WHEN Account_ID = $Account_ID then SUM(Kaat_Bricks) ELSE 0 end as $AccountName
FROM `tblstockdetail` GROUP BY `Dated`"
</code>```

if FALSE

```<code>"SELECT Dated,
CASE WHEN `Account_ID` = $Account_ID then SUM(Total_Bricks) ELSE 0 end as $AccountName,
ASE WHEN Account_ID = $Account_ID then SUM(Kaat_Bricks) ELSE 0 end as $AccountName"
</code>```

Wrong in your code

Wrapping too much with ' and "

 don't use irrelevant tags

Suggestion

Use Variable ($Account_ID) instead of actual array pointer ($value['Account_ID'];) - It's EASY to UNDERSTAND and easy to DEBUG

Body:
i am using codeigniter and i need to use aggregate function in query. so i have this query.

"SELECT Dated, CASE WHEN `Account_ID` = 2 then SUM(Total_Bricks) ELSE 0 end as 'Nadeem',
CASE WHEN Account_ID = 2 then SUM(Kaat_Bricks) ELSE 0 end as 'NadeemKaat',
CASE WHEN `Account_ID` = 7 then SUM(Total_Bricks) ELSE 0 end as 'Abid',
CASE WHEN Account_ID = 7 then SUM(Kaat_Bricks) ELSE 0 end as 'AbidKaat',
CASE WHEN `Account_ID` = 8 then SUM(Total_Bricks) ELSE 0 end as 'Sajid',
CASE WHEN Account_ID = 8 then SUM(Kaat_Bricks) ELSE 0 end as 'SajidKaat'
FROM `tblstockdetail` GROUP BY `Dated`"

i have generated this query through a simple foreach loop

$stock = $this->Kharkaar_Model->get_stockdetail();

        $sql = '"SELECT Dated, ';

        $numItems = count($stock);
        $i = 0;
        foreach ($stock as $key => $value)
        {

            if(++$i === $numItems)
            {
                $sql.= "CASE WHEN `Account_ID` = ".$value['Account_ID']." then SUM(Total_Bricks) ELSE 0 end as '".$value['AccountName']."',

            CASE WHEN Account_ID = ".$value['Account_ID']." then SUM(Kaat_Bricks) ELSE 0 end as '".$value['AccountName']."Kaat'
 FROM `tblstockdetail` GROUP BY `Dated`";
            }
            else
            {
                $sql.= "CASE WHEN `Account_ID` = ".$value['Account_ID']." then SUM(Total_Bricks) ELSE 0 end as '".$value['AccountName']."',

            CASE WHEN Account_ID = ".$value['Account_ID']." then SUM(Kaat_Bricks) ELSE 0 end as '".$value['AccountName']."Kaat',
 ";

            }

        }

        $sql.= '"';

now when i try to get result of this query

$result = $this->db->query($sql);

it is giving me a syntax error, otherwise when i put this query direct into

$result = $this->db->query(// string query here );

it is running fine.

Body:
Your foreach should be like this

$stock = $this->Kharkaar_Model->get_stockdetail();

$sql = "SELECT Dated, ";

$numItems = count($stock);
$i = 0;
foreach ($stock as $key => $value)
{

    if(++$i === $numItems)
    {
        $Account_ID = $value['Account_ID'];
        $AccountName = $value['AccountName'];

        $sql.= "CASE WHEN `Account_ID` =  $Account_ID then SUM(Total_Bricks) ELSE 0 end as $AccountName,
        CASE WHEN Account_ID = $Account_ID then SUM(Kaat_Bricks) ELSE 0 end as $AccountName
        FROM `tblstockdetail` GROUP BY `Dated`";
    }
    else
    {
        $sql.= "CASE WHEN `Account_ID` = $Account_ID then SUM(Total_Bricks) ELSE 0 end as $AccountName,
        CASE WHEN Account_ID = $Account_ID then SUM(Kaat_Bricks) ELSE 0 end as $AccountName";

    }

}

if TRUE

"SELECT Dated,
CASE WHEN `Account_ID` =  $Account_ID then SUM(Total_Bricks) ELSE 0 end as $AccountName,
CASE WHEN Account_ID = $Account_ID then SUM(Kaat_Bricks) ELSE 0 end as $AccountName
FROM `tblstockdetail` GROUP BY `Dated`"

if FALSE

"SELECT Dated,
CASE WHEN `Account_ID` = $Account_ID then SUM(Total_Bricks) ELSE 0 end as $AccountName,
ASE WHEN Account_ID = $Account_ID then SUM(Kaat_Bricks) ELSE 0 end as $AccountName"

Wrong in your code

Wrapping too much with ' and "

<br /> don't use irrelevant tags

Suggestion

Use Variable ($Account_ID) instead of actual array pointer ($value['Account_ID'];) - It's EASY to UNDERSTAND and easy to DEBUG


问:
How to remove duplicates that are case SENSITIVE in Excel (for 100k records or more)?
I have tried using this formula field and copying to all >100k records I have.

=IF(SUMPRODUCT(--EXACT(A2,$B$1:B1)),"",A2)

where:

column A = column with all data including duplicates

column B = column to display data (from column A) if unique otherwise empty string

However I hit this issue:

Yes my Excel 2016 is 32bit and yes my laptop is only 8GB RAM. But I have read up that people with 64bit and 16GB RAM experienced the same error as me.

I know there is a function in Excel function : Data > Select Column(s)> Remove Duplicates. However this function deletes case INSENSITIVE data only.

Please advise me how I can overcome this issue. I am open to using stuff like Crystal Reports or some sort of freeware to solve this issue. Please advise.

答:
You may try something like this.
Before trying this backup your data.
The code below will remove the duplicates from the column A and it is case sensitive.

```<code>Sub GetUniqueValues()
Dim x, dict
Dim lr As Long
lr = Cells(Rows.Count, 1).End(xlUp).Row
x = Range("A2:A" & lr).Value
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(x, 1)
    dict.Item(x(i, 1)) = ""
Next i
Range("A2:A" & lr).ClearContents
Range("A2").Resize(dict.Count).Value = Application.Transpose(dict.keys)
End Sub
</code>```

Edited Code:

```<code>Sub GetUniqueValues()
Dim x, dict, y
Dim lr As Long
Application.ScreenUpdating = False

lr = Cells(Rows.Count, 1).End(xlUp).Row
x = Range("A2:A" & lr).Value
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(x, 1)
    dict.Item(x(i, 1)) = ""
Next i
ReDim y(1 To dict.Count, 1 To 1)

i = 0
For Each it In dict.keys
   i = i + 1
   y(i, 1) = it
Next it

Range("A2:A" & lr).ClearContents
Range("A2").Resize(dict.Count).Value = y

Application.ScreenUpdating = True
End Sub
</code>```

Body:
You may try something like this.
Before trying this backup your data.
The code below will remove the duplicates from the column A and it is case sensitive.

Sub GetUniqueValues()
Dim x, dict
Dim lr As Long
lr = Cells(Rows.Count, 1).End(xlUp).Row
x = Range("A2:A" & lr).Value
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(x, 1)
    dict.Item(x(i, 1)) = ""
Next i
Range("A2:A" & lr).ClearContents
Range("A2").Resize(dict.Count).Value = Application.Transpose(dict.keys)
End Sub

Edited Code:

Sub GetUniqueValues()
Dim x, dict, y
Dim lr As Long
Application.ScreenUpdating = False

lr = Cells(Rows.Count, 1).End(xlUp).Row
x = Range("A2:A" & lr).Value
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(x, 1)
    dict.Item(x(i, 1)) = ""
Next i
ReDim y(1 To dict.Count, 1 To 1)

i = 0
For Each it In dict.keys
   i = i + 1
   y(i, 1) = it
Next it

Range("A2:A" & lr).ClearContents
Range("A2").Resize(dict.Count).Value = y

Application.ScreenUpdating = True
End Sub


问:
How to avoid overflow in realloc?
One can safely allocate x elements of size y in C by using calloc(x, y) and calloc() will take care of the multiplication x*y.

However realloc() for example only takes the new size as parameter and I was wondering how I could safely realloc x*y bytes using realloc().

What if x*y doesn't fit in size_t? How does calloc() handle this?

答:
The size_t is an unsigned type, and the maximum value of size_t is the absolute maximum size of object that can be allocated with realloc or malloc; this is available in the macro SIZE_MAX. On 32-bit personal computers the size_t is often 32 bits; 64 bits on 64-bit computers. It should be enough.

To ensure that the calculation of item_size * n_items does not overflow, you can divide the SIZE_MAX by item_size and ensure that the resulting value is greater than or equal to n_items:

```<code>size_t max_items = SIZE_MAX / item_size;
if (max_items < n_items) {
    // an overflow would occur
}
else {
    // it is ok
}
</code>```

calloc must return NULL if the allocation did not succeed, so calloc most probably has a check similar to one above.

Title: How to avoid overflow in realloc?

Body:
The size_t is an unsigned type, and the maximum value of size_t is the absolute maximum size of object that can be allocated with realloc or malloc; this is available in the macro SIZE_MAX. On 32-bit personal computers the size_t is often 32 bits; 64 bits on 64-bit computers. It should be enough.

To ensure that the calculation of item_size * n_items does not overflow, you can divide the SIZE_MAX by item_size and ensure that the resulting value is greater than or equal to n_items:

size_t max_items = SIZE_MAX / item_size;
if (max_items < n_items) {
    // an overflow would occur
}
else {
    // it is ok
}

calloc must return NULL if the allocation did not succeed, so calloc most probably has a check similar to one above.


问:
PHP FPDF error on generateing Pdf
I am trying to generate pdf using Fpdf. But i got this error while submitting the button.

Fatal error: Uncaught exception 'Exception' with message 'FPDF error: Some data has already been output, can't send PDF file (output started at C:\xampp\htdocs\AutoMall2\testindex.php:237)' in C:\xampp\htdocs\AutoMall2\fpdf\fpdf.php:271 Stack trace: #0 C:\xampp\htdocs\AutoMall2\fpdf\fpdf.php(1040): FPDF->Error('Some data has a...') #1 C:\xampp\htdocs\AutoMall2\fpdf\fpdf.php(987): FPDF->_checkoutput() #2 C:\xampp\htdocs\AutoMall2\testindex.php(274): FPDF->Output('2017-04-0313.pd...', 'I') #3 {main} thrown in C:\xampp\htdocs\AutoMall2\fpdf\fpdf.php on line 271

I already search for this error but no success I also look some similar question but same.

```<code><?php
include_once('connect.php');
date_default_timezone_set("Asia/Karachi");
$date=date("Y-m-d");
$time=date("h:i:s A");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Car Parking System</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-theme.css"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="js/bootstrap.min.js" type="text/javascript"></script>
</head>

<style type="text/css">
    body{
        background: #222222;
    }
    label{
        color: white;
        font-size: 1.4em;
        text-transform: uppercase;
        font-family: 'gatepassfont';
        font-weight: 600;
    }
    .heading
    {
        color:white;
    }

    table tr td
    {
        padding: 50px;
    }
    .custom_button
    {
        background:red;
        color:white;
        padding:4px 20px 4px 20px;
        font-weight: 50px;
        font-size: 24px;
        /*margin:0px 0px 0px 115px;*/
    }
    .custom_button:hover
    {
        background:#b30000;
        color:white;
    }

    .select_text
    {
        border-radius: 0px;
        background:#4d4d4d;
        color:white;

        border-style: none;
        font-size: 1.2em;
        text-transform: uppercase;
        font-family: 'gatepassfont';
        font-weight: 100;
    }

    .textbox_color
    {
        background:#4d4d4d;
        color:white;
        border-style: none;
        border-radius:0px;
        font-family: 'gatepassfont';
        font-size: 1.2em;
        /*text-transform: uppercase;*/
        font-weight: 100;
    }
    @font-face {
        font-family: 'gatepassfont';
        src: url('BebasNeue-webfont.woff') format('woff');/* Super Modern Browsers */
    }

    h2.gatepass
    {
        /*border-bottom:solid 5px #fa565a;*/
        padding-top: 5px;
        padding-bottom: 5px;
        font-family: 'gatepassfont';
        font-size: 2em;
        background:#ed1c24 ;

        font-weight: 300;
        padding-right: -200px;

    }

    .logo
    {
        width:250px;
        height:auto;
        padding: 10px;
    }
    .slogan
    {
        color:white;
        font-size: 0.5em;
        font-style: italic;
        position: relative;
        top:33px;
        left: -130px;
    }

</style>

<script type="text/javascript" src="tableExport/jquery.js"></script>
<script type="text/javascript" src="tableExport/tableExport.js"></script>
<script type="text/javascript" src="tableExport/jquery.base64.js"></script>
<script type="text/javascript" src="tableExport/html2canvas.js"></script>

<script type="text/javascript" src="tableExport/jspdf/jspdf.js"></script>
<script type="text/javascript" src="tableExport/jspdf/libs/base64.js"></script>
<script type="text/javascript" src="tableExport/jspdf/libs/sprintf.js"></script>
<script type="text/javascript">

</script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
<script type="text/javascript" src="jsPDFautotable/jspdf.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.3.0/jspdf.plugin.autotable.js"></script>
<!--Sweet Alert-->

<link rel="stylesheet" type="text/css" href="sweetalert2/dist/sweetalert2.min.css">
<script src="sweetalert2/dist/sweetalert2.min.js"></script>
<body>

    <div class="container">

        <!--form horizontal-->
        <div class="row">
            <div class="container">

                <img src="automalllogo.png" class="img-responsive col-lg-4 col-md-4 col-sm-12 col-xs-12 col-lg-offset-4 col-md-offset-4 logo" />
                <p class="slogan">Pleasure of Extreme Machines</p>
                <h2 class="heading gatepass text-center col-lg-4 col-md-4 col-sm-12 col-xs-12 col-lg-offset-4 col-md-offset-4"><strong>GATE PASS</strong></h2>

            </div>
        </div>
        <!--form-->
        <form method="POST" action="">

            <div class="form-group col-lg-4 col-md-4 col-lg-offset-4 col-md-offset-4" >
                <label class="control-label " >VEHICLE</label>
                <div  >
                    <select name="vehicle" class="form-control select_text">

                        <option value="Toyota" >Toyota</option>
                        <option value="Civic">Civic</option>

                    </select>
                </div>
            </div>

            <div class="form-group col-lg-4 col-md-4 col-lg-offset-4 col-md-offset-4  ">
                <label  >REG/CH.NO</label>

                <div >
                    <input type="text" name="registration" class="form-control textbox_color"  placeholder="Enter Registration No" required="">
                </div>
            </div>
            <div class="form-group col-lg-4 col-md-4 col-lg-offset-4 col-md-offset-4 ">
                <label class="control-label " >MILEAGE</label>
                <div >
                    <input type="text" name="mileage" class="form-control textbox_color"  placeholder="Enter Mileage" required="">
                </div>
            </div>

            <div class="form-group col-lg-4 col-md-4 col-lg-offset-4 col-md-offset-4 ">
                <label class="control-label " >TO</label>
                <div >
                    <input type="text" name="to" class="form-control textbox_color"  placeholder="Enter To" required="">
                </div>
            </div>

            <div class="form-group col-lg-4 col-md-4 col-lg-offset-4 col-md-offset-4 ">
                <label class="control-label " >DRIVER</label>
                <div >
                    <input type="text" name="driver" class="form-control textbox_color"  placeholder="Enter driver" required="">
                </div>
            </div>

            <div class="form-group col-lg-4 col-md-4 col-lg-offset-4 col-md-offset-4">
                <label class="control-label " >C/O:</label>
                <div >
                    <input type="text" name="co" class="form-control textbox_color"  placeholder="Enter C/O" required="">
                </div>
            </div>

            <div class="form-group col-lg-4 col-md-4 col-lg-offset-4 col-md-offset-4 " >
                <label class="control-label " >APPROVED BY</label>
                <div  >
                    <select name="approvedby" class="form-control select_text">

                        <option value="Irfan">Irfan</option>
                        <option value="Rizwan">Rizwan</option>

                    </select>
                </div>
            </div>

            <div class="form-group col-lg-8 col-md-8 col-lg-offset-4 col-md-offset-4">
                <div >
                    <button type="submit" name="submit" class="btn custom_button" id="submit">Submit</button>

                </div>
            </div>
        </form>
        <!--form-->

    </div>
    <!--end-->

</body>
</html>

<?php

if(isset($_POST['submit']))
{
    $vehicle=$_POST['vehicle'];
    $registration=$_POST['registration'];
    $mileage=$_POST['mileage'];
    $to=$_POST['to'];
    $driver=$_POST['driver'];
    $co=$_POST['co'];
    $approvedby=$_POST['approvedby'];
    $date;
    $time;

    $query="INSERT INTO gatepass (vehicle,registration,mileage,to_location,driver,co,approvedby,currentdate,currenttime) VALUES ('$vehicle','$registration','$mileage','$to','$driver','$co','$approvedby','$date','$time')";
    $queryrun=mysqli_query($connection,$query);

    $connection=mysqli_connect($localhost,$username,$password,$db);
    $query="SELECT id from gatepass WHERE currentdate='$date' AND currenttime='$time'";

    $queryrun=mysqli_query($connection,$query);

    $row=mysqli_fetch_array($queryrun);
    $ID=$row['id'];
    if($queryrun==TRUE)
    {
        require('fpdf/fpdf.php');
        $pdf = new FPDF();
        $pdf->AddPage();
        $pdf->SetFont('Arial','B',16);
        $pdf->Cell(40,10,'working or not?!');
        $pdf->Output($date.$ID.'.pdf','I');

    }
    else{
        mysqli_error($connection);
    }
}
?>
</code>```

答:
There is problem in your library which you are using. try any different or use dompdf it will be helpful for you.
https://github.com/dompdf/dompdf</p>

Title: PHP FPDF error on generateing Pdf

Body:
I am trying to generate pdf using Fpdf. But i got this error while submitting the button.

Fatal error: Uncaught exception 'Exception' with message 'FPDF error: Some data has already been output, can't send PDF file (output started at C:\xampp\htdocs\AutoMall2\testindex.php:237)' in C:\xampp\htdocs\AutoMall2\fpdf\fpdf.php:271 Stack trace: #0 C:\xampp\htdocs\AutoMall2\fpdf\fpdf.php(1040): FPDF->Error('Some data has a...') #1 C:\xampp\htdocs\AutoMall2\fpdf\fpdf.php(987): FPDF->_checkoutput() #2 C:\xampp\htdocs\AutoMall2\testindex.php(274): FPDF->Output('2017-04-0313.pd...', 'I') #3 {main} thrown in C:\xampp\htdocs\AutoMall2\fpdf\fpdf.php on line 271

I already search for this error but no success I also look some similar question but same.

<?php
include_once('connect.php');
date_default_timezone_set("Asia/Karachi");
$date=date("Y-m-d");
$time=date("h:i:s A");
?>
<!DOCTYPE html>

    <title>Car Parking System</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-theme.css"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" type="text/css" href="sweetalert2/dist/sweetalert2.min.css">

Pleasure of Extreme Machines

GATE PASS

        <form method="POST" action="">

                VEHICLE

                    <select name="vehicle" class="form-control select_text">

                        <option value="Toyota" >Toyota</option>
                        <option value="Civic">Civic</option>

                    </select>

                REG/CH.NO

                    <input type="text" name="registration" class="form-control textbox_color"  placeholder="Enter Registration No" required="">

                MILEAGE

                    <input type="text" name="mileage" class="form-control textbox_color"  placeholder="Enter Mileage" required="">

                TO

                    <input type="text" name="to" class="form-control textbox_color"  placeholder="Enter To" required="">

                DRIVER

                    <input type="text" name="driver" class="form-control textbox_color"  placeholder="Enter driver" required="">

                C/O:

                    <input type="text" name="co" class="form-control textbox_color"  placeholder="Enter C/O" required="">

                APPROVED BY

                    <select name="approvedby" class="form-control select_text">

                        <option value="Irfan">Irfan</option>
                        <option value="Rizwan">Rizwan</option>

                    </select>

                    <button type="submit" name="submit" class="btn custom_button" id="submit">Submit</button>

        </form>

<?php

if(isset($_POST['submit']))
{
    $vehicle=$_POST['vehicle'];
    $registration=$_POST['registration'];
    $mileage=$_POST['mileage'];
    $to=$_POST['to'];
    $driver=$_POST['driver'];
    $co=$_POST['co'];
    $approvedby=$_POST['approvedby'];
    $date;
    $time;

    $query="INSERT INTO gatepass (vehicle,registration,mileage,to_location,driver,co,approvedby,currentdate,currenttime) VALUES ('$vehicle','$registration','$mileage','$to','$driver','$co','$approvedby','$date','$time')";
    $queryrun=mysqli_query($connection,$query);

    $connection=mysqli_connect($localhost,$username,$password,$db);
    $query="SELECT id from gatepass WHERE currentdate='$date' AND currenttime='$time'";

    $queryrun=mysqli_query($connection,$query);

    $row=mysqli_fetch_array($queryrun);
    $ID=$row['id'];
    if($queryrun==TRUE)
    {
        require('fpdf/fpdf.php');
        $pdf = new FPDF();
        $pdf->AddPage();
        $pdf->SetFont('Arial','B',16);
        $pdf->Cell(40,10,'working or not?!');
        $pdf->Output($date.$ID.'.pdf','I');

    }
    else{
        mysqli_error($connection);
    }
}
?>


问:
how to create array for cart with session id variable after adding item into cart and display list of cart array items and Update the quantity
I am working with a cart item where user can add multiple item into the cart and update or delete the item from cart. i assign selection_id in addition of every newly added one item. i am increment id one by one on each add new item into cart the code is working is fine.

i show you my cart code here. when i click add item to cart this below code has execute.

```<code>   if(!isset($_SESSION['cart'])){
        $_SESSION['cart']=array();
        }
    $no_of_itm_in_cart= count($_SESSION[cart]);

    //$sl_id is Selction Id

    $sl_id=$no_of_itm_in_cart+1;
    $item_sl = array();
        $item_sl['item_sl_id']= $sl_id;
        $item_sl['item_id']=$pid;
        $item_sl['item_qty']  =$quantity;

     $_SESSION['cart'][$sl_id] = $item_sl;
</code>```

Please share me, how to display each element and how to update and remove any element where "item_id" is a parameter.

答:
```<code>echo '<table>
         <tr>
            <th>SL ID</th>
            <th>ID</th>
            <th>Quantity</th>
            <th>Actions</th>
         </tr>';
foreach($_SESSION['cart'] as $row){

    echo ' <tr>
            <td>'.$row['item_sl_id'].'</td>
            <td>'.$row['item_id'].'</td>
            <td>'.$row['item_qty'].'/td>
            <td>
                 <button class="remove" data-id="'.$row['item_sl_id'].'">Remove</button>
                 <button class="edit" data-id="'.$row['item_sl_id'].'">Edit</button>
            </td>
         </tr>';
}
     echo '</table>';
</code>```

JS.

```<code>$('.delete').click(function(e){
    id = $(this).data('id');
    $.ajax({
        url         : 'path/to/delete.php',
        type        : 'POST',
        data        : {'id':id},
        timeout     : 30000,
        success: function(e) {}
    });
});
</code>```

delete.php

```<code>    unset($_SESSION['cart'][$_POST['id']]);die;
</code>```

Body:
I am working with a cart item where user can add multiple item into the cart and update or delete the item from cart. i assign selection_id in addition of every newly added one item. i am increment id one by one on each add new item into cart the code is working is fine.

i show you my cart code here. when i click add item to cart this below code has execute.

   if(!isset($_SESSION['cart'])){
        $_SESSION['cart']=array();
        }
    $no_of_itm_in_cart= count($_SESSION[cart]);

    //$sl_id is Selction Id

    $sl_id=$no_of_itm_in_cart+1;
    $item_sl = array();
        $item_sl['item_sl_id']= $sl_id;
        $item_sl['item_id']=$pid;
        $item_sl['item_qty']  =$quantity;

     $_SESSION['cart'][$sl_id] = $item_sl;

Please share me, how to display each element and how to update and remove any element where "item_id" is a parameter.

Body:
echo '<table>
         <tr>
            <th>SL ID</th>
            <th>ID</th>
            <th>Quantity</th>
            <th>Actions</th>
         </tr>';
foreach($_SESSION['cart'] as $row){

    echo ' <tr>
            <td>'.$row['item_sl_id'].'</td>
            <td>'.$row['item_id'].'</td>
            <td>'.$row['item_qty'].'/td>
            <td>
                 <button class="remove" data-id="'.$row['item_sl_id'].'">Remove</button>
                 <button class="edit" data-id="'.$row['item_sl_id'].'">Edit</button>
            </td>
         </tr>';
}
     echo '</table>';

JS.

$('.delete').click(function(e){
    id = $(this).data('id');
    $.ajax({
        url         : 'path/to/delete.php',
        type        : 'POST',
        data        : {'id':id},
        timeout     : 30000,
        success: function(e) {}
    });
});

delete.php

    unset($_SESSION['cart'][$_POST['id']]);die;


问:
Create a CardView with a semicircle on top
I am very much into designing a login screen.

Something like this:

How Do I actually cut the card from the top so as to fill the drawable on top of it? Any help would be of great value.

[Source: https://www.uplabs.com/posts/login-android-app/]

答:
This screen is very complex in terms of what can be done with the current implementation of shapes and shadows on Android. It might actually be impossible to implement correctly using official libraries. You have to solve two problems - how to cut the view and how to provide a shadow for that view.

The support CardView's shadow is created using some kind of a gradient and supports only one case - the rounded rectangle. The Lollipop's shadow can take any shape as long as the shape is convex - which is not your case. As far as I know, there's no 3rd party library which could help you with that. You'd have to make your own shadow using RenderScript blur or just provide a background with a shadow.

It's possible to cut out the circular shape at the top. It requires some custom drawing/masking, but can be done pretty easily using standard Android library. You can do that using Canvas.saveLayer/restore() + PorterDuff.Mode.CLEAR. More or less like this:

```<code>Path circle, card;
PorterDuffXfermode xfereMode = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
Bitmap avatar;

// make a layer to make cutting shapes possible
int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);

// draw the card and its content
canvas.drawPath(card, paint);
super.draw(canvas);

// clear the circular shape
paint.setXfermode(xfereMode);
canvas.drawPath(circle, paint);

// composite
canvas.restoreToCount(saveCount);
paint.setXfermode(null);

// draw the avatar
canvas.drawBitmap(avatar, x, y, paint);
</code>```

It's not a compplete solution, but I hope you get the idea. To make a shadow, add a black filter, blur it with RenderScript and draw beneath the actual view.

It's a ton of work. Most likely will be very time consuming to implement correctly and very slow to execute. Layer composition and per-pixel operations are very slow even on modern desktop hardware.

Body:
This screen is very complex in terms of what can be done with the current implementation of shapes and shadows on Android. It might actually be impossible to implement correctly using official libraries. You have to solve two problems - how to cut the view and how to provide a shadow for that view.

The support CardView's shadow is created using some kind of a gradient and supports only one case - the rounded rectangle. The Lollipop's shadow can take any shape as long as the shape is convex - which is not your case. As far as I know, there's no 3rd party library which could help you with that. You'd have to make your own shadow using RenderScript blur or just provide a background with a shadow.

It's possible to cut out the circular shape at the top. It requires some custom drawing/masking, but can be done pretty easily using standard Android library. You can do that using Canvas.saveLayer/restore() + PorterDuff.Mode.CLEAR. More or less like this:

Path circle, card;
PorterDuffXfermode xfereMode = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
Bitmap avatar;

// make a layer to make cutting shapes possible
int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);

// draw the card and its content
canvas.drawPath(card, paint);
super.draw(canvas);

// clear the circular shape
paint.setXfermode(xfereMode);
canvas.drawPath(circle, paint);

// composite
canvas.restoreToCount(saveCount);
paint.setXfermode(null);

// draw the avatar
canvas.drawBitmap(avatar, x, y, paint);

It's not a compplete solution, but I hope you get the idea. To make a shadow, add a black filter, blur it with RenderScript and draw beneath the actual view.

It's a ton of work. Most likely will be very time consuming to implement correctly and very slow to execute. Layer composition and per-pixel operations are very slow even on modern desktop hardware.


问:
Vagrant: multiple playbooks for ansible provisioner
Is it possible / valid to run more than one playbooks for a vagrant ansible provisioner in the following form:</p>

```<code> config.vm.define "repo", primary: true do |d|
    d.vm.hostname = "some.hostname"
    # Create a private network, which allows host-only access to the machine
    # using a specific IP.
    d.vm.network :private_network, ip: "10.10.2.90"
    d.vm.provision 'ansible' do |ansible|
      ansible.config_file = 'ansible/ansible.cfg'
      ansible.playbook = 'ansible/playbook1.yml'
      ansible.playbook = 'ansible/playbook2.yml'
      ansible.sudo = true
      ansible.inventory_path = 'ansible/inventory/site'
      ansible.host_key_checking = false
    end
  end
</code>```

答:
no it will not be valid

If you want to run 2 playbook, you would need to run the ansible provisioner twice, this can be done like

```<code> config.vm.define "repo", primary: true do |d|
    d.vm.hostname = "some.hostname"
    # Create a private network, which allows host-only access to the machine
    # using a specific IP.
    d.vm.network :private_network, ip: "10.10.2.90"

    # First playbook
    d.vm.provision  "playbook1", type:'ansible' do |ansible|
      ansible.config_file = 'ansible/ansible.cfg'
      ansible.playbook = 'ansible/playbook1.yml'
      ansible.sudo = true
      ansible.inventory_path = 'ansible/inventory/site'
      ansible.host_key_checking = false
    end

    # Second playbook
    d.vm.provision  "playbook2", type:'ansible' do |ansible|
      ansible.config_file = 'ansible/ansible.cfg'
      ansible.playbook = 'ansible/playbook2.yml'
      ansible.sudo = true
      ansible.inventory_path = 'ansible/inventory/site'
      ansible.host_key_checking = false
    end
  end
</code>```

Body:
Is it possible / valid to run more than one playbooks for a vagrant ansible provisioner in the following form:

 config.vm.define "repo", primary: true do |d|
    d.vm.hostname = "some.hostname"
    # Create a private network, which allows host-only access to the machine
    # using a specific IP.
    d.vm.network :private_network, ip: "10.10.2.90"
    d.vm.provision 'ansible' do |ansible|
      ansible.config_file = 'ansible/ansible.cfg'
      ansible.playbook = 'ansible/playbook1.yml'
      ansible.playbook = 'ansible/playbook2.yml'
      ansible.sudo = true
      ansible.inventory_path = 'ansible/inventory/site'
      ansible.host_key_checking = false
    end
  end

Body:
no it will not be valid

If you want to run 2 playbook, you would need to run the ansible provisioner twice, this can be done like

 config.vm.define "repo", primary: true do |d|
    d.vm.hostname = "some.hostname"
    # Create a private network, which allows host-only access to the machine
    # using a specific IP.
    d.vm.network :private_network, ip: "10.10.2.90"

    # First playbook
    d.vm.provision  "playbook1", type:'ansible' do |ansible|
      ansible.config_file = 'ansible/ansible.cfg'
      ansible.playbook = 'ansible/playbook1.yml'
      ansible.sudo = true
      ansible.inventory_path = 'ansible/inventory/site'
      ansible.host_key_checking = false
    end

    # Second playbook
    d.vm.provision  "playbook2", type:'ansible' do |ansible|
      ansible.config_file = 'ansible/ansible.cfg'
      ansible.playbook = 'ansible/playbook2.yml'
      ansible.sudo = true
      ansible.inventory_path = 'ansible/inventory/site'
      ansible.host_key_checking = false
    end
  end


问:
How to resolve "local edit, incoming delete upon update" message
When I do a svn status ., I get this:

```<code>!     C auto-complete-config.elc
      >   local edit, incoming delete upon update
!  +  C auto-complete.elc
      >   local edit, incoming delete upon update
!  +  C popup.elc
      >   local edit, incoming delete upon update
!  +  C fuzzy.elc
      >   local edit, incoming delete upon update
</code>```

basically, these files shouldn't be in the repository. A developer has removed them. Then, I think I did a svn rm ... after the fact by mistake (should've done svn update . instead).

So now, when I do svn status ., I get these tree conflict messages.

I found the doc here but not sure how to “merge” it according to the doc.

How to get rid of them?

I think my working copy is in sync with the repository. Don't know why these messages shows. These files should be removed and are removed as far as I know everywhere. I tried svn update . and svn revert . but I still get this message when I do svn status ..

答:
Try to resolve the conflict using</p>

```<code>svn resolve --accept=working PATH
</code>```

Body:
When I do a svn status ., I get this:

!     C auto-complete-config.elc
      >   local edit, incoming delete upon update
!  +  C auto-complete.elc
      >   local edit, incoming delete upon update
!  +  C popup.elc
      >   local edit, incoming delete upon update
!  +  C fuzzy.elc
      >   local edit, incoming delete upon update

basically, these files shouldn't be in the repository. A developer has removed them. Then, I think I did a svn rm ... after the fact by mistake (should've done svn update . instead).

So now, when I do svn status ., I get these tree conflict messages.

I found the doc here but not sure how to “merge” it according to the doc.

How to get rid of them?

I think my working copy is in sync with the repository. Don't know why these messages shows. These files should be removed and are removed as far as I know everywhere. I tried svn update . and svn revert . but I still get this message when I do svn status ..

Body:
Try to resolve the conflict using

svn resolve --accept=working PATH


问:
CMake: ‘sqrtf’ is not a member of ‘std’
After compiling my program with

```<code>$ cmake .
$ make
</code>```

I get 5 errors of this form:

```<code>$ make
Scanning dependencies of target Project
[ 50%] Building CXX object CMakeFiles/myproj.dir/main.cpp.o
In file included from /path/to/my/proj/main.cpp:2:0:
/path/to/my/proj/library.hpp: In member function ‘virtual double MyProjClass::get_value(double, double) const’:
/path/to/my/proj/library.hpp:419:26: error: ‘sqrtf’ is not a member of ‘std’
     const float F = (std::sqrtf(1.0f + 2.0f) - 1.0f) / 2;
                      ^
</code>```

Other errors include floorf not being a member of std.

Looking at this thread, it's because I'm not compiling with C++11, and looking at this thread thread, "[...] CMake will make sure the C++ compiler is invoked with the appropriate command line flags."

Well, my CMake is obviously not doing this. Why am I getting these errors, and how do I go about fixing them?

Edit: Here's my CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.5)
project(Noise)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp vector.hpp noise.hpp)
add_executable(Noise ${SOURCE_FILES})

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})
target_link_libraries(Noise ${SDL2_LIBRARIES})
</code>```

答:
You don't say what C++ compiler you are using but assuming it is g++ 5.x though 7, sqrtf
and floorf are not within the std namespace under -std=c++11, -std=c++14 or -std=c++1z. They are
simply in the global namespace, when cmath is included.

Title: CMake: ‘sqrtf’ is not a member of ‘std’

Body:
After compiling my program with

$ cmake .
$ make

I get 5 errors of this form:

$ make
Scanning dependencies of target Project
[ 50%] Building CXX object CMakeFiles/myproj.dir/main.cpp.o
In file included from /path/to/my/proj/main.cpp:2:0:
/path/to/my/proj/library.hpp: In member function ‘virtual double MyProjClass::get_value(double, double) const’:
/path/to/my/proj/library.hpp:419:26: error: ‘sqrtf’ is not a member of ‘std’
     const float F = (std::sqrtf(1.0f + 2.0f) - 1.0f) / 2;
                      ^

Other errors include floorf not being a member of std.

Looking at this thread, it's because I'm not compiling with C++11, and looking at this thread thread, "[...] CMake will make sure the C++ compiler is invoked with the appropriate command line flags."

Well, my CMake is obviously not doing this. Why am I getting these errors, and how do I go about fixing them?

Edit: Here's my CMakeLists.txt

cmake_minimum_required(VERSION 3.5)
project(Noise)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp vector.hpp noise.hpp)
add_executable(Noise ${SOURCE_FILES})

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})
target_link_libraries(Noise ${SDL2_LIBRARIES})